Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open Safari Extension ToolbarItem popover programmatically

I want to programmatically trigger a 'click' event on my Safari Extension toolbarItem so that my custom popover appears after something happens on the webpage. I'm using the new Xcode extension IDE and have built my popover using interface builder. All of the answers on StackOverflow currently deal with extensions built in the Safari extension builder and not in the Xcode interface. For example, I have tried injected Safari JS solutions like:

safari.extension.toolbarItems[0].showPopover();

But nothing happens, and I don't think it's supposed to work when you build extensions in Xcode. I don't care whether the popover is triggered in the injected javascript or in my SafariExtensionHandler.Swift file -- I just need a way to show it without a user click on the toolbar item.

I have associated my popover with my toolbar item using the extension's info.plist which I have linked to below:

https://i.stack.imgur.com/VxyLs.png

The extension is bundled with a native CocoaOS app, and it's constructed using the new Xcode paradigm introduced at WWDC '15 (link below). I can access the Toolbaritem in SafariExtensionHandler.Swift with this method:

 func getToolbarItem(completionHandler: @escaping (SFSafariToolbarItem?) -> Void) {
    SFSafariApplication.getActiveWindow {$0?.getToolbarItem (completionHandler: completionHandler)}
}

But the toolbarItem object doesn't seem to have a method to show the popover.

https://developer.apple.com/videos/play/wwdc2016/214/

like image 853
michael_head Avatar asked Nov 11 '16 18:11

michael_head


2 Answers

SFSafariApplication.getActiveWindow { (window) in
    window?.getToolbarItem(completionHandler: { (item) in
        item?.showPopover()
    })
}
like image 172
David Kyslenko Avatar answered Nov 14 '22 09:11

David Kyslenko


Open the Info.plist of your Safari extension and locate the SFSafariToolbarItem key, then look for Action sub-key and make sure it's set to Popover.

Also, make sure that your SFSafariExtensionViewController subclass assigns the desired preferredContentSize.

import SafariServices

class SafariExtensionViewController: SFSafariExtensionViewController {

    static let shared = SafariExtensionViewController()

    override func viewDidLoad() {
        super.viewDidLoad()

        preferredContentSize = NSSize(width: 330, height: 119)
    }

}
like image 22
Rob Zombie Avatar answered Nov 14 '22 08:11

Rob Zombie