API Docs

hs.ui.webview

A web browser element for embedding in hs.ui.window layouts

Available on macOS 26.0 or later, hs.ui.webview() creates a web browser element backed by a SwiftUI WebView and WebPage. Embed it in any hs.ui.window using .webview(element) — it fills the available space and can sit alongside other elements in stacks.

Create the element first, configure it, then embed it into a window:

const wv = hs.ui.webview()
    .toolbar(["back", "forward", "reload", "url"])
    .loadURL("https://apple.com")

hs.ui.window({x: 100, y: 100, w: 1024, h: 768})
    .titled(true)
    .closable(true)
    .allowResize(true)
    .level("normal")
    .webview(wv)
    .show()

Because wv is a regular JavaScript object you can keep a reference and call navigation methods on it at any time after the window is shown:

wv.loadURL("https://google.com")
wv.goBack()

Custom Toolbar Example

const wv = hs.ui.webview()
    .toolbar([
        "back", "forward", "reload", "url",
        {title: "Home", systemImage: "house", callback: () => wv.loadURL("https://apple.com")},
        {title: "Reload HS", callback: () => hs.reload()}
    ])
    .loadURL("https://apple.com")

hs.ui.window({x: 100, y: 100, w: 1024, h: 768})
    .webview(wv)
    .show()

Full Example with Callbacks

const wv = hs.ui.webview()
    .toolbar(["back", "forward", "reload", "url"])
    .inspectable(true)
    .onNavigate((url) => console.log("Navigated to: " + url))
    .onTitleChange((title) => console.log("Title: " + title))
    .onLoadChange((loading, url, title, progress) => {
        if (!loading) console.log("Page ready: " + url)
    })
    .loadURL("https://apple.com")

hs.ui.window({x: 100, y: 100, w: 1024, h: 768})
    .webview(wv)
    .show()

Navigation Policy Example

const wv = hs.ui.webview()
    .toolbar(["back", "forward", "reload", "url"])
    .onNavigationDecision((url) => {
        return !url.includes("evil.com")
    })
    .loadURL("https://apple.com")

hs.ui.window({x: 100, y: 100, w: 1024, h: 768})
    .webview(wv)
    .show()

Page Messages Example

The page can call back into your config with webkit.messageHandlers.<name>.postMessage(body), which returns a Promise that settles with whatever your callback returns:

const wv = hs.ui.webview()
    .onMessage("hs", (body) => {
        console.log("Page says: " + body.text)
        return "Thanks!"
    })
    .loadHTML(`<button onclick="send()">Send</button><script>
        async function send() {
            const reply = await webkit.messageHandlers.hs.postMessage({text: "hello"})
            document.body.append(reply)
        }
    </script>`)

hs.ui.window({x: 100, y: 100, w: 400, h: 300}).webview(wv).show()

JavaScript Evaluation Example

const wv = hs.ui.webview().loadURL("https://apple.com")
hs.ui.window({x: 100, y: 100, w: 1024, h: 768}).webview(wv).show()

// Fire and forget
wv.execJS("document.body.style.backgroundColor = 'lightyellow'")

// With result (the script must `return` its value)
wv.evalJSResult("return document.title", (result, error) => {
    if (error) { console.log("Error: " + error) }
    else { console.log("Title: " + result) }
})

Properties

url

string

The URL of the current page, or null if no page is loaded

isLoading

boolean

Whether the web view is currently loading a page

estimatedProgress

number

The estimated loading progress from 0.0 to 1.0

canGoBack

boolean

Whether the web view can navigate back in history

canGoForward

boolean

Whether the web view can navigate forward in history

Methods

loadURL(urlString) -> UIWebView

Load a URL in the web view

loadURL(urlString) -> UIWebView
Name Type Description
urlString string The URL to load (e.g. "https://apple.com")
UIWebView
Self for chaining
hs.ui.webview().loadURL("https://apple.com")

loadHTML(html) -> UIWebView

Load an HTML string directly into the web view

loadHTML(html) -> UIWebView
Name Type Description
html string The HTML content to display
UIWebView
Self for chaining
hs.ui.webview().loadHTML("<html><body><h1>Hello from Hammerspoon!</h1></body></html>")

goBack() -> UIWebView

Navigate back in the browser history

goBack() -> UIWebView
UIWebView
Self for chaining
if (wv.canGoBack) wv.goBack()

goForward() -> UIWebView

Navigate forward in the browser history

goForward() -> UIWebView
UIWebView
Self for chaining
if (wv.canGoForward) wv.goForward()

reload() -> UIWebView

Reload the current page

reload() -> UIWebView
UIWebView
Self for chaining
wv.reload()

stopLoading() -> UIWebView

Stop loading the current page

stopLoading() -> UIWebView
UIWebView
Self for chaining
wv.stopLoading()

userAgent(ua) -> UIWebView

Set a custom User-Agent string for HTTP requests

userAgent(ua) -> UIWebView
Name Type Description
ua string The User-Agent string
UIWebView
Self for chaining
hs.ui.webview().userAgent("MyApp/1.0 AppleWebKit")

inspectable(value) -> UIWebView

Enable or disable the Safari Web Inspector for this web view

When enabled, the web view appears in Safari → Develop menu.

inspectable(value) -> UIWebView
Name Type Description
value boolean Pass true to enable the Web Inspector
UIWebView
Self for chaining
hs.ui.webview().inspectable(true)

toolbar(items) -> UIWebView

Configure the toolbar with a list of standard and custom items

The toolbar renders above the web view. Each element of the array is either a string naming a standard control or a dictionary describing a custom button. An empty array (or omitting this call) hides the toolbar.

Standard string items: "back", "forward", "reload", "url", "spacer".

Custom button dictionaries accept:

  • title (string, optional) — button label
  • systemImage (string, optional) — SF Symbol name (e.g. "house")
  • callback (function, required) — called when the button is clicked
toolbar(items) -> UIWebView
Name Type Description
items JSValue Toolbar items in display order
UIWebView
Self for chaining
The toolbar will not be shown if the web view is in a borderless window
hs.ui.webview()
    .toolbar(["back", "forward", "reload", "url",
              {title: "Home", systemImage: "house", callback: () => wv.loadURL("https://apple.com")}])

backForwardGestures(enabled) -> UIWebView

Enable or disable the macOS back/forward trackpad swipe gestures

Gestures are enabled by default. Pass false to disable them.

backForwardGestures(enabled) -> UIWebView
Name Type Description
enabled boolean Pass false to disable back/forward swipe gestures
UIWebView
Self for chaining
wv.backForwardGestures(false)

magnificationGestures(enabled) -> UIWebView

Enable or disable the trackpad pinch-to-zoom magnification gesture

The gesture is enabled by default. Pass false to disable it.

magnificationGestures(enabled) -> UIWebView
Name Type Description
enabled boolean Pass false to disable pinch-to-zoom
UIWebView
Self for chaining
wv.magnificationGestures(false)

linkPreviews(enabled) -> UIWebView

Enable or disable link preview popovers shown on force-click

Link previews are enabled by default. Pass false to disable them.

linkPreviews(enabled) -> UIWebView
Name Type Description
enabled boolean Pass false to disable link previews
UIWebView
Self for chaining
wv.linkPreviews(false)

contentBackground(visible) -> UIWebView

Control whether the web page background is visible

Pass false to make the web view background transparent. Enabled (visible) by default.

contentBackground(visible) -> UIWebView
Name Type Description
visible boolean Pass false to hide the web content background
UIWebView
Self for chaining
wv.contentBackground(false)

onLoadChange(callback) -> UIWebView

Register a callback that fires when loading state or progress changes

Called whenever isLoading, url, title, or estimatedProgress changes.

onLoadChange(callback) -> UIWebView
Name Type Description
callback function Called with current loading state
UIWebView
Self for chaining
If you register a callback here, it is no longer possible to automatically release the webview via JS garbage collection. You will need to manually call `.destroy()` and also cause this callback to trigger
wv.onLoadChange((loading, url, title, progress) => {
    if (!loading) console.log("Finished loading: " + url)
})

onNavigate(callback) -> UIWebView

Register a callback that fires when navigation to a new page completes

onNavigate(callback) -> UIWebView
Name Type Description
callback function Called with the final URL
UIWebView
Self for chaining
If you register a callback here, it is no longer possible to automatically release the webview via JS garbage collection. You will need to manually call `.destroy()` and also cause this callback to trigger
wv.onNavigate((url) => console.log("Navigated to: " + url))

onTitleChange(callback) -> UIWebView

Register a callback that fires when the page title changes

onTitleChange(callback) -> UIWebView
Name Type Description
callback function Called with the new title
UIWebView
Self for chaining
If you register a callback here, it is no longer possible to automatically release the webview via JS garbage collection. You will need to manually call `.destroy()` and also cause this callback to trigger
wv.onTitleChange((title) => console.log("New title: " + title))

onNavigationDecision(callback) -> UIWebView

Register a callback that controls whether navigation is allowed

Called before each navigation. Return true to allow or false to block.

onNavigationDecision(callback) -> UIWebView
Name Type Description
callback function Return true to allow, false to block
UIWebView
Self for chaining
wv.onNavigationDecision((url) => {
    return !url.startsWith("file://")
})

onMessage(name, callback) -> UIWebView

Let the page send messages to a callback

Adds webkit.messageHandlers.<name> to the page, for this and every later page the web view loads. When the page calls webkit.messageHandlers.<name>.postMessage(body), the callback is called with body, and the Promise postMessage() returns settles with the callback's result:

  • a plain value resolves it with that value
  • a Promise resolves or rejects it once that Promise settles
  • a thrown error rejects it with the error's message

The body and the result can be strings, numbers, booleans, null, dates, and arrays and plain objects of those. Calling this again with the same name replaces the callback.

onMessage(name, callback) -> UIWebView
Name Type Description
name string The handler name the page uses, as in webkit.messageHandlers.<name>
callback function Called with each message the page sends. Its result is the reply
UIWebView
Self for chaining
Any page loaded in the web view can send these messages, so treat them as untrusted input
wv.onMessage("clipboard", (body) => {
    hs.pasteboard.setString(body)
    return true
})
// In the page:
// await webkit.messageHandlers.clipboard.postMessage("copied from a web page")

removeMessageHandler(name) -> UIWebView

Stop the page from sending messages with a name registered by onMessage()

Removes webkit.messageHandlers.<name> from the page.

removeMessageHandler(name) -> UIWebView
Name Type Description
name string The handler name passed to onMessage()
UIWebView
Self for chaining
wv.removeMessageHandler("clipboard")

execJS(script) -> UIWebView

Execute JavaScript in the web page without capturing the result

The script runs as the body of an async function, so it can use await.

execJS(script) -> UIWebView
Name Type Description
script string The JavaScript function body to execute
UIWebView
Self for chaining
wv.execJS("document.body.style.backgroundColor = 'lightyellow'")

evalJSResult(script, callback) -> UIWebView

Execute JavaScript in the web page and deliver the result to a callback

The script is not evaluated as an expression: it runs as the body of an async function, and the result is the value it returns. Use return to send a value back — a script without one, such as "document.title", gives a result of null. Because the function is async, the script can use await, and if it returns a Promise the callback gets the value the Promise resolves to.

The result is copied out of the page, so it must be a number, string, boolean, array, plain object, null or undefined (which arrives as null). Anything else, such as a DOM element or a function, is delivered as an error.

If the script throws, or returns a Promise that rejects, the error is the page's own message for it, such as "Error: boom" or "SyntaxError: Unexpected token '}'".

evalJSResult(script, callback) -> UIWebView
Name Type Description
script string The JavaScript function body to run, which should return the result
callback function Called with the result or an error message
UIWebView
Self for chaining
wv.evalJSResult("return document.title", (result, error) => {
    if (error) { console.log("Error: " + error) }
    else { console.log("Title: " + result) }
})

// Statements and await work too
wv.evalJSResult(`
    const response = await fetch("/api/status")
    return (await response.json()).state
`, (result, error) => console.log(result))