PyObjC WebKit Framework Bindings

12.1 · active · verified Mon Apr 13

PyObjC-framework-WebKit provides Python wrappers for Apple's WebKit and JavaScriptCore frameworks on macOS, enabling Python applications to embed web content and execute JavaScript. It is part of the larger PyObjC project, which acts as a bridge between Python and Objective-C. The library is actively maintained with regular updates to support new macOS SDKs and Python versions, typically following a release cadence aligned with major macOS and Python releases.

Warnings

Install

Imports

Quickstart

This minimal example demonstrates how to create a basic macOS application window using AppKit and embed a WKWebView to display a webpage. It defines an AppDelegate to manage the application lifecycle and sets up a window with a WKWebView loading a URL. To run this, save it as a .py file and execute it on macOS with PyObjC installed. Note that a full macOS application with an Info.plist and bundle identifier is typically created using tools like `py2app` for deployment, but this script provides a runnable demonstration within a standard Python environment. The URL is conditionally set to avoid issues when run from an unbundled script without a default bundle ID.

import AppKit
import Foundation
import WebKit

class AppDelegate(AppKit.NSObject):
    def applicationDidFinishLaunching_(self, notification):
        rect = Foundation.NSMakeRect(0, 0, 800, 600)
        self.window = AppKit.NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(
            rect, AppKit.NSWindowStyleMaskTitled | AppKit.NSWindowStyleMaskClosable | AppKit.NSWindowStyleMaskResizable, AppKit.NSBackingStoreBuffered, False
        )
        self.window.setTitle_("PyObjC WebKit Demo")

        self.webView = WebKit.WKWebView.alloc().initWithFrame_(rect)
        self.window.contentView().addSubview_(self.webView)

        url = Foundation.NSURL.URLWithString_("https://www.apple.com/" if not Foundation.NSBundle.mainBundle().bundleIdentifier() else "https://www.google.com")
        request = Foundation.NSURLRequest.requestWithURL_(url)
        self.webView.loadRequest_(request)

        self.window.makeKeyAndOrderFront_(None)

    def applicationShouldTerminateAfterLastWindowClosed_(self, sender):
        return True

if __name__ == "__main__":
    app = AppKit.NSApplication.sharedApplication()
    delegate = AppDelegate.alloc().init()
    app.setDelegate_(delegate)
    app.run()

view raw JSON →