chrome扩展在后台页面和内容脚本下使用相同的socket.io连接

fox*_*hen 5 javascript google-chrome-extension socket.io

我正在使用socket.io进行chrome扩展,我有一个内容脚本,可以连接到服务器进行实时聊天,但我也希望从后台页面的服务器获取一些信息.它像这样分开工作

在内容脚本中

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

在背景页面

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

但有没有办法只连接一次和服务器有类似的东西

app.js socket.emit('dosomething');

并将触发后台页面或内容脚本有哪些 socket.on('dosomething')

我试着用发送由后台页面内容脚本建立的插座 chrome.runtime.sendMessagechrome.runtime.onMessage.addListener,

但它不起作用:(

有什么解决方案吗?

非常感谢!

Chi*_*ice 6

我尝试在内容脚本中编写一个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){});
});
Run Code Online (Sandbox Code Playgroud)

背景页面:

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

服务器端:

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!"});
});
Run Code Online (Sandbox Code Playgroud)

背景控制台的屏幕截图:

在此输入图像描述

希望这对你有所帮助.