Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

chrome extension use the same socket.io connection under background page and content scripts

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!

like image 828
fox chen Avatar asked Jul 23 '13 08:07

fox chen


1 Answers

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:

enter image description here

Hope this is helpful for you.

like image 83
Chickenrice Avatar answered Nov 15 '22 07:11

Chickenrice