I'm doing a chrome extension with socket.io , i have a content script that keep connecting to server to make a real-time chat, but i also want to get some information from server in background page. it works well separately like this
in content script
var socket = io.connect('http://localhost:3700');
socket.on('dosomething',function(){
console.log("test");
});
in background page
var socket = io.connect('http://localhost:3700');
socket.on('dosomething',function(){
console.log("test");
});
but is there any way to only connect one time and when server have something like
app.js socket.emit('dosomething');
and will trigger either background page or content script which has socket.on('dosomething')
?
I've tried sending the socket established by background page to content script by using
chrome.runtime.sendMessage
and chrome.runtime.onMessage.addListener
,
but it didn't work :(
Is there any solution?
Thanks a lot!
I tried to write a socket.io client in content script which will send message to background page when socket.io server send "hello" request.
Content Script:
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){});
});
Background page:
chrome.runtime.onMessage.addListener(
function(request,sender,senderResponse){
if(request.msg==="socket"){
console.log("receive from socket server: "+request.text);
}
}
);
Server side:
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!"});
});
Screen shot of background console:
Hope this is helpful for you.
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