Skip to content

Instantly share code, notes, and snippets.

@rickumali
Last active March 29, 2023 02:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rickumali/10f4e56f26f7d6a309b0d696b7b2d8ac to your computer and use it in GitHub Desktop.
Save rickumali/10f4e56f26f7d6a309b0d696b7b2d8ac to your computer and use it in GitHub Desktop.
Starting a Browser in a Swift Script File

This code was originally posted by Jens in:

https://developer.apple.com/forums/thread/5137

He writes "Below is the 'Webkit Browser in 30 Lines of Swift' from Practical Swift, with some small changes to make it run on latest beta with Swift 2."

I have modified it to work on MacOS Big Sur 11.7.4 Swift 5.5.2

#!/usr/bin/swift
import WebKit
let application = NSApplication.shared
application.setActivationPolicy(NSApplication.ActivationPolicy.regular)
let window = NSWindow(contentRect: NSMakeRect(0, 0, 960, 720), styleMask: NSWindow.StyleMask( rawValue: NSWindow.StyleMask.titled.rawValue|NSWindow.StyleMask.closable.rawValue|NSWindow.StyleMask.miniaturizable.rawValue), backing: NSWindow.BackingStoreType.buffered, defer: false)
window.center()
window.title = "Minimal Swift WebKit Browser"
window.makeKeyAndOrderFront(window)
class WindowDelegate: NSObject, NSWindowDelegate {
func windowWillClose(_ notification: Notification) {
NSApplication.shared.terminate(0)
}
}
let windowDelegate = WindowDelegate()
window.delegate = windowDelegate
class ApplicationDelegate: NSObject, NSApplicationDelegate {
var _window: NSWindow
init(window: NSWindow) {
self._window = window
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
let webView = WKWebView(frame: self._window.contentView!.frame)
self._window.contentView!.addSubview(webView)
webView.load(URLRequest(url: URL(string: "https://forums.developer.apple.com/thread/5137")!))
}
}
let applicationDelegate = ApplicationDelegate(window: window)
application.delegate = applicationDelegate
application.activate(ignoringOtherApps: true)
application.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment