views:

69

answers:

4

I have a Safari 5 extension that contains a toolbar. Whenever the current tab changes, that toolbar should be updated. I would like to do something like this from my bar's script:

safari.self.browserWindow.addEventListener("activeTab", tabChanged, false);

However, that doesn't seem to work. I have tried a number of other event names as well:

  • activeTab
  • activeTabChanged
  • onActiveTab
  • onActiveTabChanged
  • tab
  • tabChanged
  • onTab
  • onTabChanged
  • selectionChanged
  • onSelectionChanged

Does anybody know how to detect when the active tab changes?

Not that this is in any way related, but it looks like I would do this in Chrome with:

 chrome.tabs.onSelectionChanged.addListener(tabChanged);
A: 

It seems Apple doesn't provide much API for us manipulating tabs like Chrome does. Currently, there is no way to detect tab event.

imiaou
A: 

I have the same problem. Is anyone can help?

JackieLi
+1  A: 

I agree with @imiaou 's answer: from looking at Apple's docs there doesn't seem to be a way to do this :(.

Since I needed to detect tab changes for my extension (which I'm porting over from Chrome), I did the following polling-based workaround which seems to be working fine (in my global page):

var prevActiveTab;

setInterval("poorMansOnTabChange()", 1500); //poll every 1.5 sec

function poorMansOnTabChange() {
    var curTab = safari.application.activeBrowserWindow.activeTab;
    if (curTab != prevActiveTab) {
        prevActiveTab= curTab;
        console.log("active tab changed!");
        //do work here
    }
}

I'm unhappy with constantly polling the browser, but I see no other way around this until Apple adds support for these tab-events. If your extension can live with a relatively relaxed tab-switch event trigger latency then this could be a reasonable workaround for now (1.5 sec. max latency is acceptable for my extension, and it doesn't feel like its slowing down the browser).

Amos
Yes, I think this is the best current answer. Unfortunately, it doesn't work for my particular situation unless I reduce the polling delay to something like 200 ms, which seems too frequent for my tastes. Still, thanks for the suggestion.
Daniel Yankowsky
A: 

Unlike chrome which provides a special API for events like window and tab changes, you can still do it with safari extensions.

You simply have to have your injected javascript set up event listeners for the events that you want.

Then if that info is needed by global or other parts of the extension, you can pass the info in messages using the postMessage command.

injected.js:

window.addEventListener("load", loaded, false);

safari.self.tab.dispatchMessage("somethinghappened","load");

Galt
Right, this much I understand. Unfortunately, there's no DOM standard event that fires when a window's tab changes. That's the thing that Apple would need to provide. Perhaps they do, but I can't find any documentation.
Daniel Yankowsky