How to open Safari Extension ToolbarItem popover programmatically

蓝咒 提交于 2019-11-30 08:31:31

问题


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:


SFSafariApplication.getActiveWindow { (window) in
    window?.getToolbarItem(completionHandler: { (item) in
        item?.showPopover()
    })
}



回答2:


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

}


来源:https://stackoverflow.com/questions/40554363/how-to-open-safari-extension-toolbaritem-popover-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!