5

I have a Safari browser extension with a disabled mode. What I'd like to do is to programmatically change the toolbar icon when the user enters disabled mode.

Is there an API which will allow me to achieve this and if so what is it?

Cœur
  • 37,241
  • 25
  • 195
  • 267
David Tuite
  • 22,258
  • 25
  • 106
  • 176

2 Answers2

10

Any toolbar items your extension has can be referenced as an array in

safari.extension.toolbarItems

Each toolbar item will have an image property which you can change. This will cause the toolbar icon to change immediately.

// Change the toolbar icon.
var changeToolbarIcon = function(newIconName) {
  var iconUri = safari.extension.baseURI + 'icons/' + newIconName;
  safari.extension.toolbarItems[0].image = iconUri;
};

The Safari Documentation

David Tuite
  • 22,258
  • 25
  • 106
  • 176
  • 1
    Of note: The above applies to Safari Extensions JS. Safari App Extensions (new in Safari 10 / macOS 10.12) do not seem to currently provide a public API to change the toolbar item image (just enabled/disabled state and the badge). – breakingobstacles Oct 22 '16 at 02:19
1

Using the new Safari App Extensions API, as long as you have a reference to an SFSafariPage, and that this page is not pinned (pinned tabs' windows are nil), you can get that page's tab's window's toolbar item, through a chain of callbacks, and then set the icon for each of these toolbar items.

extension SFSafariPage {

    func getContainingWindow(completionHandler: @escaping (SFSafariWindow?) -> Void) {
        self.getContainingTab { $0.getContainingWindow { completionHandler($0) } }
    }

    func getToolbarItem(completionHandler: @escaping (SFSafariToolbarItem?) -> Void) {
        self.getContainingWindow {
            ($0 == nil) ? completionHandler(nil) : $0.unsafelyUnwrapped.getToolbarItem { completionHandler($0) }
        }
    }
}


let tab: SFSafariTab = ...

tab.getToolbarItem { item in
    item?.setImage(NSImage(...))
}