]> git.r.bdr.sh - rbdr/junction/blob - safari/Junction/ViewController.swift
91786953d642ea0bdaddd635a93594fce6261d67
[rbdr/junction] / safari / Junction / ViewController.swift
1 import Cocoa
2 import SafariServices
3 import WebKit
4
5 let extensionBundleIdentifier = "systems.tranquil.Junction.Extension"
6
7 class ViewController: NSViewController, WKNavigationDelegate, WKScriptMessageHandler {
8
9 @IBOutlet var webView: WKWebView!
10
11 override func viewDidLoad() {
12 super.viewDidLoad()
13
14 self.webView.navigationDelegate = self
15
16 self.webView.configuration.userContentController.add(self, name: "controller")
17
18 self.webView.loadFileURL(Bundle.main.url(forResource: "Main", withExtension: "html")!, allowingReadAccessTo: Bundle.main.resourceURL!)
19 }
20
21 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
22 SFSafariExtensionManager.getStateOfSafariExtension(withIdentifier: extensionBundleIdentifier) { (state, error) in
23 guard let state = state, error == nil else {
24 // Insert code to inform the user that something went wrong.
25 return
26 }
27
28 DispatchQueue.main.async {
29 if #available(macOS 13, *) {
30 webView.evaluateJavaScript("show(\(state.isEnabled), true)")
31 } else {
32 webView.evaluateJavaScript("show(\(state.isEnabled), false)")
33 }
34 }
35 }
36 }
37
38 func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
39 if (message.body as! String != "open-preferences") {
40 return;
41 }
42
43 SFSafariApplication.showPreferencesForExtension(withIdentifier: extensionBundleIdentifier) { error in
44 DispatchQueue.main.async {
45 // NSApplication.shared.terminate(nil)
46 }
47 }
48 }
49
50 }