5

我正在用 socket.io 做一个 chrome 扩展,我有一个内容脚本,它不断连接到服务器以进行实时聊天,但我也想从后台页面中的服务器获取一些信息。它像这样单独工作得很好

在内容脚本中

var socket = io.connect('http://localhost:3700');
socket.on('dosomething',function(){
  console.log("test");
});

在后台页面

var socket = io.connect('http://localhost:3700');
socket.on('dosomething',function(){
  console.log("test");
});

但是有没有办法只连接一次,当服务器有类似的东西时

应用程序.js socket.emit('dosomething');

并且将触发具有?的背景页面或内容脚本 socket.on('dosomething')

我尝试使用 chrome.runtime.sendMessage and 将后台页面建立的套接字发送到内容脚本chrome.runtime.onMessage.addListener

但它没有用:(

有什么解决办法吗?

非常感谢!

4

1 回答 1

8

我试图在内容脚本中编写一个 socket.io 客户端,当 socket.io 服务器发送“hello”请求时,它将向后台页面发送消息。

内容脚本:

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){});
});

背景页面:

chrome.runtime.onMessage.addListener(
    function(request,sender,senderResponse){
        if(request.msg==="socket"){
            console.log("receive from socket server: "+request.text);
        }
    }
);

服务器端:

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!"});
});

后台控制台截图:

在此处输入图像描述

希望这对你有帮助。

于 2013-07-24T08:23:25.680 回答