macossafarisafari-app-extension

Can I make text badges for Safari App Extension toolbar buttons less ugly?


Safari App Extensions don’t allow you to change toolbar button images dynamically, but they do let you add a string to the button as a badge by passing a string to the extension handler’s validationHandler method:

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, "1")
    }

Unfortunately, this badged text doesn’t look great:

enter image description here

I can’t find anything in the documentation about customising the look of the badged text, but just in case, is there any way to avoid the clipping of what is presumably meant to be a circular badge?


Solution

  • I don't think it's possible to change the look of the badge text. However, it is now possible to set the button image dynamically, using the toolbar item's setImage method.

    For example, including the following in your SFSafariExtensionHandler will change the toolbar item icon to the default user icon when the button is clicked:

    override func toolbarItemClicked(in window: SFSafariWindow) {
        let image = NSImage(named: NSImageNameUser)
        window.getToolbarItem { $0?.setImage(image) }
    }
    

    You can provide any NSImage, though it should conform to Apple's guidelines for template images.

    I don't know why this isn't documented in the Safari App Extension Programming Guide you linked to. I suspect this feature may have been added later and that the Guide is out of date.