Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically change icon of Safari browser extension?

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?

like image 726
David Tuite Avatar asked Oct 02 '12 10:10

David Tuite


2 Answers

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

like image 138
David Tuite Avatar answered Oct 26 '22 05:10

David Tuite


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(...))
}
like image 36
Andreas detests censorship Avatar answered Oct 26 '22 03:10

Andreas detests censorship