Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension Socket io node js

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!"});
});
like image 404
Dinesh Jeyasankar Avatar asked Jun 25 '15 22:06

Dinesh Jeyasankar


2 Answers

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 enter image description here

but with socket.io.js 2.3.0 worked correctly as it should enter image description here 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

like image 159
Gleb L Avatar answered Sep 21 '22 04:09

Gleb L


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

like image 30
Rahat Mahbub Avatar answered Sep 22 '22 04:09

Rahat Mahbub