开发者

How to differentiate between Firefox tabs?

I am currently developing a Firefox extension, and I need the ability to be able to differentiate between each open tab.

The idea is to be able to associate outgoing HTTP requests with its origin tab. For each 'on-modify-request' event that is observed, for example, I would know开发者_运维百科 that it came from tab #2, or tab #3.

This would have to be good enough to differentiate between multiple instances of the same website. Enumerating through all open tabs will not work if I have three 'www.google.com' tabs open for example.

As far as I know, tabbrowser objects in Mozilla do not have any unique identifiers or properties.

Any ideas?


http-on-modify-request gives you the actual request object. From there you need to get the associated window, the way to go is nsILoadContext here. I use this code:

function getRequestWindow(request)
{
  try
  {
    if (request.notificationCallbacks)
      return request.notificationCallbacks
                    .getInterface(Components.interfaces.nsILoadContext)
                    .associatedWindow;
  } catch(e) {}

  try
  {
    if (request.loadGroup && request.loadGroup.notificationCallbacks)
      return request.loadGroup.notificationCallbacks
                              .getInterface(Components.interfaces.nsILoadContext)
                              .associatedWindow;
  } catch(e) {}

  return null;
}

That's a content window (and probably even a frame). So you have to find the corresponding tab - use gBrowser.getBrowserForDocument(). Like this:

var wnd = getRequestWindow(request);
var browser = (wnd ? gBrowser.getBrowserForDocument(wnd.top.document) : null);

Now you have the <browser> element that the request belongs to - if any. Because the request might also originate from the Firefox UI or a different browser window. You can set your own expando property on that element to get a tab identifier (choose a unique name to avoid conflicts with other extensions). Something like this:

if (!("_myExtensionTabId" in browser))
    browser._myExtensionTabId = ++maxTabId;
var tabId = browser._myExtensionTabId;

Here maxTabId would be a global variable that's initially zero. And "myExtension" would be ideally replaced by something unique to your extension (e.g. its name).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜