Skip to content

Instantly share code, notes, and snippets.

@kopyl
Created January 10, 2025 15:24
Show Gist options
  • Select an option

  • Save kopyl/73b6cfe6bbc3962caf9f644c41e7108c to your computer and use it in GitHub Desktop.

Select an option

Save kopyl/73b6cfe6bbc3962caf9f644c41e7108c to your computer and use it in GitHub Desktop.
import SafariServices
import SwiftUI
struct Popover: View {
@State private var content = ""
var body: some View {
VStack(spacing: 16) {
Text("URL")
.font(.headline)
Text(content)
}
.frame(minWidth: 300)
.padding()
.onAppear {
SFSafariApplication.getActiveWindow { (window) in
window?.getActiveTab { (tab) in
tab?.getActivePage(completionHandler: { (page) in
page?.getPropertiesWithCompletionHandler( { (properties) in
DispatchQueue.main.async {
if let url = properties?.url {
content = url.absoluteString
}
}
})
})
}
}
}
}
}
final class PopoverViewController: SFSafariExtensionViewController {
init() {
super.init(nibName: nil, bundle: nil)
let popover = Popover()
self.view = NSHostingView(rootView: popover)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class SafariExtensionHandler: SFSafariExtensionHandler {
override func popoverViewController() -> SFSafariExtensionViewController {
PopoverViewController()
}
override func validateToolbarItem(in window: SFSafariWindow, validationHandler: @escaping ((Bool, String) -> Void)) {
window.getActiveTab { (tab) in
tab?.getActivePage(completionHandler: { (page) in
page?.getPropertiesWithCompletionHandler( { (properties) in
validationHandler(properties?.url != nil, "")
})
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment