[英]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. 我正在使用socket.io进行chrome扩展,我有一个内容脚本,可以连接到服务器进行实时聊天,但我也希望从后台页面的服务器获取一些信息。 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');
app.js socket.emit('dosomething');
and will trigger either background page or content script which has socket.on('dosomething')
? 并将触发具有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
, 我已经尝试使用chrome.runtime.sendMessage
和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. 我尝试在内容脚本中编写一个socket.io客户端,当socket.io服务器发送“hello”请求时,它将向后台页面发送消息。
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. 希望这对你有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.