在多个窗口帮助Firefox扩展 [英] help with Firefox extension in multiple windows
问题描述
我正在写一个Firefox扩展,创建一个套接字服务器,当客户端连接到它时,它将输出活动标签的URL。我的JavaScript文件中有以下代码:
I'm writing a Firefox extension that creates a socket server which will output the active tab's URL when a client makes a connection to it. I have the following code in my javascript file:
var serverSocket;
function startServer()
{
var listener =
{
onSocketAccepted : function(socket, transport)
{
try {
var outputString = gBrowser.currentURI.spec + "\n";
var stream = transport.openOutputStream(0,0,0);
stream.write(outputString,outputString.length);
stream.close();
} catch(ex2){ dump("::"+ex2); }
},
onStopListening : function(socket, status){}
};
try {
serverSocket = Components.classes["@mozilla.org/network/server-socket;1"]
.createInstance(Components.interfaces.nsIServerSocket);
serverSocket.init(7055,true,-1);
serverSocket.asyncListen(listener);
} catch(ex){ dump(ex); }
document.getElementById("status").value = "Started";
}
function stopServer ()
{
if (serverSocket)
serverSocket.close();
}
window.addEventListener("load", function() { startServer(); }, false);
window.addEventListener("unload", function() { stopServer(); }, false);
实际上,它适用于单个窗口中的多个选项卡。如果我打开多个窗口,它会忽略其他窗口。我认为它是为每个窗口创建一个服务器套接字,但由于它们使用相同的端口,所以额外的套接字无法初始化。我需要它在浏览器启动时创建服务器套接字,并在关闭窗口(Mac OS X)时继续运行。事实上,当我关闭一个窗口,但Firefox仍然运行,套接字关闭,我不得不重新启动Firefox来启动它的运行。如何解决这个问题?
As it is, it works for multiple tabs in a single window. If I open multiple windows, it ignores the additional windows. I think it is creating a server socket for each window, but since they are using the same port, the additional sockets fail to initialize. I need it to create a server socket when the browser launches and continue running when I close the windows (Mac OS X). As it is, when I close a window but Firefox remains running, the socket closes and I have to restart firefox to get it up an running. How do I go about that?
推荐答案
您可能想要:
You probably want to:
- 将您的代码移动到JavaScript组件中
- 将组件注册为
更改后的配置文件
观察者 - 每当有人连接到您的套接字,找到活动窗口并返回它的URL。
- Move your code into a JavaScript component
- Register your component as a
profile-after-change
observer - Whenever someone makes a connection to your socket, find the active window and return its URL.
使用类似于
Use something like
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var win = wm.getMostRecentWindow("navigator:browser");
var spec = win ? win.getBrowser().currentURI.spec : "";
var outputString = spec + "\n";
等。
这篇关于在多个窗口帮助Firefox扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!