Safari 5 Extension: How can I detect when a window

2020-02-29 11:14发布

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);

8条回答
等我变得足够好
2楼-- · 2020-02-29 11:59

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:

var tabInFocus = function( event )
{
 safari.self.tab.dispatchMessage("tabFocusSwitched","");
}

window.addEventListener("focus", tabInFocus, false);

You can then update your extension's UI, with the data relevant to safari.application.activeBrowserWindow.activeTab

查看更多
兄弟一词,经得起流年.
3楼-- · 2020-02-29 11:59

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");

查看更多
登录 后发表回答