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