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);
While Safari doesn't have Chrome's specific tab-related API, it does have a perfect solution to this problem.
@Galt was 99% of the way there, with the idea to add an event listener to your injected JavaScript and to
dispatchMessage
that information to your extension.The event handler you're looking for is named
focus
, and gets fired every time a tab or window gets selected.In your injected code:
You can then update your extension's UI, with the data relevant to
safari.application.activeBrowserWindow.activeTab
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");