How to open Safari Extension ToolbarItem popover p

2019-02-17 12:03发布

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/

1条回答
ら.Afraid
2楼-- · 2019-02-17 13:03

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)
    }

}
查看更多
登录 后发表回答