Skip to content

Instantly share code, notes, and snippets.

@uchcode
Created December 31, 2016 06:57
Show Gist options
  • Save uchcode/0b8e4b6863345c9f62896495991c0272 to your computer and use it in GitHub Desktop.
Save uchcode/0b8e4b6863345c9f62896495991c0272 to your computer and use it in GitHub Desktop.
JXA (JavaScript for Automation) WebView applet template.
ObjC.import('Cocoa')
ObjC.import('WebKit')
MyWindow = WebViewWindow('http://www.youtube.com/')
MyWindow.makeKeyAndOrderFront(null)
//=====================================================================
function Window(x, y, width, height) {
let r = $.NSMakeRect(x, y, width, height)
let s = $.NSTitledWindowMask
s|= $.NSClosableWindowMask
s|= $.NSMiniaturizableWindowMask
let b = $.NSBackingStoreBuffered
let d = false
let w = $.NSWindow.alloc.initWithContentRectStyleMaskBackingDefer(r, s, b, d)
w.releasedWhenClosed = false
if (x==-1 && y==-1) w.center
return w
}
function WindowDelegate() {
if (!$.WindowDelegate) ObjC.registerSubclass({
name:'WindowDelegate',
protocols: ['NSWindowDelegate'],
methods: {
'windowWillClose:' (notification) {
return $.NSApplication.sharedApplication.terminate(null)
},
},
})
return $.WindowDelegate.alloc.init
}
function WebView(url) {
let z = $.NSZeroRect
let c = $.WKWebViewConfiguration.alloc.init
let w = $.WKWebView.alloc.initWithFrameConfiguration(z, c)
let u = $.NSURL.URLWithString(url)
let r = $.NSURLRequest.requestWithURL(u)
w.loadRequest(r)
return w
}
function WebViewWindow(url, x=-1, y=-1, width=1024, height=576) {
let web = WebView(url)
web.frame = $.NSMakeRect(0, 0, width, height)
web.autoresizingMask = $.NSViewWidthSizable | $.NSViewHeightSizable
let win = Window(x, y, width, height)
win.styleMask |= $.NSResizableWindowMask
win.delegate = WindowDelegate()
win.contentView.addSubview(web)
return win
}
@stephancasas
Copy link

This is brilliant. You've saved me hours of trial and error. Thank you for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment