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

折月煮酒 提交于 2020-01-11 19:58:49

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/17805140/chrome-extension-use-the-same-socket-io-connection-under-background-page-and-con

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