我正在使用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.sendMessage
和 chrome.runtime.onMessage.addListener
,
但它不起作用:(
有什么解决方案吗?
非常感谢!
我收到这个错误 Uncaught Error: Attempting to use a disconnected port object
当我第一次打开弹出页面后,我之间的联系很长
内容脚本< - >后台页面< - >弹出页面.
当我点击浏览器操作图标时,弹出页面将从服务器通过后台页面获取一些信息进行初始化.
所有的东西在第一次点击时工作正常,但如果我关闭弹出窗口并再次点击它,它只是无法从后台页面获取信息.
这是我的代码
弹出页面
window.onload = function() {
var port = chrome.runtime.connect({name: "stadium"});
chrome.tabs.query({ currentWindow: true, active: true }, function callback(tabs){
console.log("send TabID to background page");
port.postMessage({"method":"sendTabId","content": tabs[0].id});
});
port.postMessage({"method" : "initialPopup"});//initilaize request
port.onMessage.addListener(function(msg) {
console.log("somthing");
if (msg.method == "updatePage"){
initialize....
}
else if(...){...}
});
Run Code Online (Sandbox Code Playgroud)
和背景页面
var socket = io.connect('http://localhost:3700/');
chrome.tabs.onRemoved.addListener(function(tabId,removeInfo){
if(tabId==stadiumTabId){
//change to the original style popup page
chrome.browserAction.setPopup({"popup":"../pages/popup_out_guest.html"});
}
});
chrome.runtime.onConnect.addListener(function(port) { …
Run Code Online (Sandbox Code Playgroud)