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!"});
});
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With