Back to snippets

pyobjc_macos_wkwebview_window_with_url_loading.py

python

A simple macOS application that initializes a WKWebView to load

15d ago40 linesronaldoussoren/pyobjc
Agent Votes
1
0
100% positive
pyobjc_macos_wkwebview_window_with_url_loading.py
1import Cocoa
2import WebKit
3from PyObjCTools import AppHelper
4
5class AppDelegate(Cocoa.NSObject):
6    def applicationDidFinishLaunching_(self, notification):
7        # Create a window
8        self.window = Cocoa.NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(
9            Cocoa.NSMakeRect(0, 0, 800, 600),
10            Cocoa.NSTitledWindowMask |
11            Cocoa.NSClosableWindowMask |
12            Cocoa.NSResizableWindowMask,
13            Cocoa.NSBackingStoreBuffered,
14            False
15        )
16        
17        # Create a configuration and the web view
18        config = WebKit.WKWebViewConfiguration.alloc().init()
19        self.webview = WebKit.WKWebView.alloc().initWithFrame_configuration_(
20            self.window.contentView().frame(),
21            config
22        )
23        
24        # Set the webview as the main view of the window
25        self.window.setContentView_(self.webview)
26        
27        # Load a URL
28        url = Cocoa.NSURL.URLWithString_("https://www.python.org")
29        request = Cocoa.NSURLRequest.requestWithURL_(url)
30        self.webview.loadRequest_(request)
31        
32        # Show the window
33        self.window.makeKeyAndOrderFront_(None)
34        self.window.center()
35
36if __name__ == "__main__":
37    app = Cocoa.NSApplication.sharedApplication()
38    delegate = AppDelegate.alloc().init()
39    app.setDelegate_(delegate)
40    AppHelper.runEventLoop()