How to change toolbar item icon dynamically ?

Basically I will want to show some speal icon when specific set of websites are loaded, otherwise will show default icon.


Can anyone shed some lights on dynamically changing toolbar item icon ?

Replies

Found solution and adding here so that it will be useful for others.



override func validateToolbarItem(in window: SFSafariWindow, validationHandler: @escaping ((Bool, String) -> Void)) {

// This is called when Safari's state changed in some way that would require the extension's toolbar item to be validated again.

validationHandler(true, "")


window.getToolbarItem { (toolbarItem) in

NSLog("updating toolbar icon");


window.getActiveTab(completionHandler: { (tab) in

tab?.getActivePage(completionHandler: { (page) in

page?.getPropertiesWithCompletionHandler({ (prop) in

let url = prop?.url;

let strURL = url?.absoluteString;


var strIconFileName : String = "sad-icon"


if (strURL?.contains("apple.com"))! {

strIconFileName = "happy-icon"

}


let path = Bundle.main.path(forResource: strIconFileName, ofType: "pdf")!;

let icon = NSImage(contentsOfFile: path);


toolbarItem?.setImage(icon);

})

})

})

}

}