0
# Navigation and URL Handling
1
2
URL loading, navigation management, browser history, and network request handling. Includes both modern WKNavigation system and legacy navigation approaches, providing comprehensive control over web content loading and user navigation.
3
4
## Capabilities
5
6
### Modern Navigation System
7
8
#### WKNavigation
9
10
Opaque object representing a navigation operation.
11
12
```python { .api }
13
class WKNavigation:
14
# WKNavigation is an opaque object with no public methods
15
# It serves as an identifier for navigation operations
16
pass
17
```
18
19
#### WKNavigationAction
20
21
Information about a navigation action that is about to be performed.
22
23
```python { .api }
24
class WKNavigationAction:
25
@property
26
def request(self) -> NSURLRequest: ...
27
@property
28
def sourceFrame(self) -> WKFrameInfo: ...
29
@property
30
def targetFrame(self) -> WKFrameInfo: ...
31
@property
32
def navigationType(self) -> WKNavigationType: ...
33
@property
34
def modifierFlags(self) -> int: ...
35
@property
36
def buttonNumber(self) -> int: ...
37
@property
38
def shouldPerformDownload(self) -> bool: ...
39
```
40
41
#### WKNavigationResponse
42
43
Response information for a navigation operation.
44
45
```python { .api }
46
class WKNavigationResponse:
47
@property
48
def response(self) -> NSURLResponse: ...
49
@property
50
def isForMainFrame(self) -> bool: ...
51
def canShowMIMEType(self) -> bool: ...
52
```
53
54
### Browser History
55
56
#### WKBackForwardList
57
58
Browser history management for web view navigation.
59
60
```python { .api }
61
class WKBackForwardList:
62
@property
63
def currentItem(self) -> WKBackForwardListItem: ...
64
@property
65
def backItem(self) -> WKBackForwardListItem: ...
66
@property
67
def forwardItem(self) -> WKBackForwardListItem: ...
68
@property
69
def backList(self) -> list: ...
70
@property
71
def forwardList(self) -> list: ...
72
73
def itemAtIndex_(self, index: int) -> WKBackForwardListItem: ...
74
```
75
76
#### WKBackForwardListItem
77
78
Individual entries in the browser history.
79
80
```python { .api }
81
class WKBackForwardListItem:
82
@property
83
def URL(self) -> NSURL: ...
84
@property
85
def title(self) -> str: ...
86
@property
87
def initialURL(self) -> NSURL: ...
88
```
89
90
### Download Management
91
92
#### WKDownload
93
94
File download management and control.
95
96
```python { .api }
97
class WKDownload:
98
@property
99
def originalRequest(self) -> NSURLRequest: ...
100
@property
101
def delegate(self) -> WKDownloadDelegate: ...
102
@property
103
def progress(self) -> NSProgress: ...
104
105
def cancel(self): ...
106
```
107
108
### Legacy Navigation System
109
110
#### WebView Navigation Methods
111
112
Legacy WebView navigation functionality.
113
114
```python { .api }
115
class WebView:
116
# Navigation control
117
def goBack(self) -> bool: ...
118
def goForward(self) -> bool: ...
119
def goToBackForwardItem_(self, item: WebHistoryItem) -> bool: ...
120
def reload_(self, sender: object): ...
121
def stopLoading_(self, sender: object): ...
122
123
# Navigation state
124
def canGoBack(self) -> bool: ...
125
def canGoForward(self) -> bool: ...
126
def isLoading(self) -> bool: ...
127
@property
128
def estimatedProgress(self) -> float: ...
129
130
# URL and content loading
131
@property
132
def mainFrameURL(self) -> str: ...
133
@property
134
def mainFrameDocument(self) -> DOMDocument: ...
135
@property
136
def mainFrameTitle(self) -> str: ...
137
@property
138
def mainFrame(self) -> WebFrame: ...
139
140
# History management
141
@property
142
def backForwardList(self) -> WebBackForwardList: ...
143
def setMaintainsBackForwardList_(self, flag: bool): ...
144
145
# Content type handling
146
@classmethod
147
def canShowMIMEType_(cls, MIMEType: str) -> bool: ...
148
@classmethod
149
def canShowMIMETypeAsHTML_(cls, MIMEType: str) -> bool: ...
150
@classmethod
151
def MIMETypesShownAsHTML(cls) -> list: ...
152
@classmethod
153
def setMIMETypesShownAsHTML_(cls, MIMETypes: list): ...
154
155
# Text encoding
156
def supportsTextEncoding(self) -> bool: ...
157
@property
158
def customTextEncodingName(self) -> str: ...
159
@property
160
def applicationNameForUserAgent(self) -> str: ...
161
@property
162
def customUserAgent(self) -> str: ...
163
164
# Page interaction
165
def stringByEvaluatingJavaScriptFromString_(self, script: str) -> str: ...
166
@property
167
def windowScriptObject(self) -> WebScriptObject: ...
168
169
# Search functionality
170
def searchFor_direction_caseSensitive_wrap_(self, string: str, forward: bool, caseFlag: bool, wrapFlag: bool) -> bool: ...
171
```
172
173
#### WebFrame
174
175
Represents a frame within a web page.
176
177
```python { .api }
178
class WebFrame:
179
# Frame properties
180
@property
181
def name(self) -> str: ...
182
@property
183
def webView(self) -> WebView: ...
184
@property
185
def frameView(self) -> WebFrameView: ...
186
@property
187
def DOMDocument(self) -> DOMDocument: ...
188
@property
189
def frameElement(self) -> DOMHTMLElement: ...
190
@property
191
def provisionalDataSource(self) -> WebDataSource: ...
192
@property
193
def dataSource(self) -> WebDataSource: ...
194
195
# Frame hierarchy
196
@property
197
def parentFrame(self) -> WebFrame: ...
198
@property
199
def childFrames(self) -> list: ...
200
def findFrameNamed_(self, name: str) -> WebFrame: ...
201
202
# Content loading
203
def loadRequest_(self, request: NSURLRequest): ...
204
def loadArchive_(self, archive: WebArchive): ...
205
def loadData_MIMEType_textEncodingName_baseURL_(self, data: NSData, MIMEType: str, encodingName: str, URL: NSURL): ...
206
def loadHTMLString_baseURL_(self, string: str, URL: NSURL): ...
207
def loadAlternateHTMLString_baseURL_forUnreachableURL_(self, string: str, baseURL: NSURL, unreachableURL: NSURL): ...
208
def stopLoading(self): ...
209
def reload(self): ...
210
211
# JavaScript execution
212
def windowObject(self) -> WebScriptObject: ...
213
@property
214
def globalContext(self) -> JSGlobalContextRef: ...
215
@property
216
def javaScriptContext(self) -> JSContext: ...
217
```
218
219
#### WebHistoryItem
220
221
Legacy browser history item.
222
223
```python { .api }
224
class WebHistoryItem:
225
@property
226
def URLString(self) -> str: ...
227
@property
228
def originalURLString(self) -> str: ...
229
@property
230
def title(self) -> str: ...
231
@property
232
def lastVisitedTimeInterval(self) -> float: ...
233
@property
234
def icon(self) -> NSImage: ...
235
@property
236
def isTargetItem(self) -> bool: ...
237
@property
238
def visitCount(self) -> int: ...
239
@property
240
def children(self) -> list: ...
241
@property
242
def target(self) -> str: ...
243
@property
244
def alternateTitle(self) -> str: ...
245
@property
246
def scrollPoint(self) -> NSPoint: ...
247
```
248
249
#### WebBackForwardList
250
251
Legacy browser history list.
252
253
```python { .api }
254
class WebBackForwardList:
255
def addItem_(self, item: WebHistoryItem): ...
256
def goBack(self): ...
257
def goForward(self): ...
258
def goToItem_(self, item: WebHistoryItem): ...
259
@property
260
def currentItem(self) -> WebHistoryItem: ...
261
@property
262
def backItem(self) -> WebHistoryItem: ...
263
@property
264
def forwardItem(self) -> WebHistoryItem: ...
265
@property
266
def backListWithLimit_(self, limit: int) -> list: ...
267
@property
268
def forwardListWithLimit_(self, limit: int) -> list: ...
269
@property
270
def capacity(self) -> int: ...
271
@property
272
def backListCount(self) -> int: ...
273
@property
274
def forwardListCount(self) -> int: ...
275
def containsItem_(self, item: WebHistoryItem) -> bool: ...
276
def itemAtIndex_(self, index: int) -> WebHistoryItem: ...
277
```
278
279
### Data Sources and Resources
280
281
#### WebDataSource
282
283
Data source for web content.
284
285
```python { .api }
286
class WebDataSource:
287
@property
288
def data(self) -> NSData: ...
289
@property
290
def representation(self) -> WebDocumentRepresentation: ...
291
@property
292
def webFrame(self) -> WebFrame: ...
293
@property
294
def initialRequest(self) -> NSURLRequest: ...
295
@property
296
def request(self) -> NSMutableURLRequest: ...
297
@property
298
def response(self) -> NSURLResponse: ...
299
@property
300
def textEncodingName(self) -> str: ...
301
@property
302
def isLoading(self) -> bool: ...
303
@property
304
def pageTitle(self) -> str: ...
305
@property
306
def unreachableURL(self) -> NSURL: ...
307
@property
308
def webArchive(self) -> WebArchive: ...
309
@property
310
def mainResource(self) -> WebResource: ...
311
@property
312
def subresources(self) -> list: ...
313
314
def subresourceForURL_(self, URL: NSURL) -> WebResource: ...
315
def addSubresource_(self, subresource: WebResource): ...
316
```
317
318
#### WebResource
319
320
Represents a web resource (file, image, etc.).
321
322
```python { .api }
323
class WebResource:
324
def initWithData_URL_MIMEType_textEncodingName_frameName_(self, data: NSData, URL: NSURL, MIMEType: str, textEncodingName: str, frameName: str) -> WebResource: ...
325
326
@property
327
def data(self) -> NSData: ...
328
@property
329
def URL(self) -> NSURL: ...
330
@property
331
def MIMEType(self) -> str: ...
332
@property
333
def textEncodingName(self) -> str: ...
334
@property
335
def frameName(self) -> str: ...
336
```
337
338
### URL Scheme Handling
339
340
#### WKURLSchemeHandler
341
342
Custom URL scheme handling for WKWebView.
343
344
```python { .api }
345
# WKURLSchemeHandler is a protocol - implement these methods in your handler class
346
def webView_startURLSchemeTask_(self, webView: WKWebView, urlSchemeTask: WKURLSchemeTask): ...
347
def webView_stopURLSchemeTask_(self, webView: WKWebView, urlSchemeTask: WKURLSchemeTask): ...
348
```
349
350
#### WKURLSchemeTask
351
352
Represents a URL scheme task.
353
354
```python { .api }
355
class WKURLSchemeTask:
356
@property
357
def request(self) -> NSURLRequest: ...
358
359
def didReceiveResponse_(self, response: NSURLResponse): ...
360
def didReceiveData_(self, data: NSData): ...
361
def didFinish(self): ...
362
def didFailWithError_(self, error: NSError): ...
363
```
364
365
### Navigation Constants
366
367
#### Navigation Types
368
369
```python { .api }
370
# WKNavigationType values
371
WKNavigationTypeLinkActivated = 0
372
WKNavigationTypeFormSubmitted = 1
373
WKNavigationTypeBackForward = 2
374
WKNavigationTypeReload = 3
375
WKNavigationTypeFormResubmitted = 4
376
WKNavigationTypeOther = -1
377
378
# Legacy WebNavigationType values
379
WebNavigationTypeLinkClicked = 0
380
WebNavigationTypeFormSubmitted = 1
381
WebNavigationTypeBackForward = 2
382
WebNavigationTypeReload = 3
383
WebNavigationTypeFormResubmitted = 4
384
WebNavigationTypeOther = 5
385
```
386
387
#### Navigation Policies
388
389
```python { .api }
390
# WKNavigationActionPolicy values
391
WKNavigationActionPolicyCancel = 0
392
WKNavigationActionPolicyAllow = 1
393
WKNavigationActionPolicyDownload = 2
394
395
# WKNavigationResponsePolicy values
396
WKNavigationResponsePolicyCancel = 0
397
WKNavigationResponsePolicyAllow = 1
398
WKNavigationResponsePolicyDownload = 2
399
400
# WKDownloadRedirectPolicy values
401
WKDownloadRedirectPolicyCancel = 0
402
WKDownloadRedirectPolicyAllow = 1
403
```
404
405
### Delegate Protocols
406
407
#### WKNavigationDelegate Methods
408
409
```python { .api }
410
# Implement these methods in your navigation delegate class
411
def webView_decidePolicyForNavigationAction_decisionHandler_(self, webView: WKWebView, navigationAction: WKNavigationAction, decisionHandler: callable): ...
412
def webView_decidePolicyForNavigationAction_preferences_decisionHandler_(self, webView: WKWebView, navigationAction: WKNavigationAction, preferences: WKWebpagePreferences, decisionHandler: callable): ...
413
def webView_decidePolicyForNavigationResponse_decisionHandler_(self, webView: WKWebView, navigationResponse: WKNavigationResponse, decisionHandler: callable): ...
414
def webView_didStartProvisionalNavigation_(self, webView: WKWebView, navigation: WKNavigation): ...
415
def webView_didReceiveServerRedirectForProvisionalNavigation_(self, webView: WKWebView, navigation: WKNavigation): ...
416
def webView_didFailProvisionalNavigation_withError_(self, webView: WKWebView, navigation: WKNavigation, error: NSError): ...
417
def webView_didCommitNavigation_(self, webView: WKWebView, navigation: WKNavigation): ...
418
def webView_didFinishNavigation_(self, webView: WKWebView, navigation: WKNavigation): ...
419
def webView_didFailNavigation_withError_(self, webView: WKWebView, navigation: WKNavigation, error: NSError): ...
420
def webView_didReceiveAuthenticationChallenge_completionHandler_(self, webView: WKWebView, challenge: NSURLAuthenticationChallenge, completionHandler: callable): ...
421
def webViewWebContentProcessDidTerminate_(self, webView: WKWebView): ...
422
def webView_authenticationChallenge_shouldAllowDeprecatedTLS_(self, webView: WKWebView, challenge: NSURLAuthenticationChallenge, decisionHandler: callable): ...
423
def webView_navigationAction_didBecomeDownload_(self, webView: WKWebView, navigationAction: WKNavigationAction, download: WKDownload): ...
424
def webView_navigationResponse_didBecomeDownload_(self, webView: WKWebView, navigationResponse: WKNavigationResponse, download: WKDownload): ...
425
```
426
427
#### WKDownloadDelegate Methods
428
429
```python { .api }
430
# Implement these methods in your download delegate class
431
def download_decideDestinationUsingResponse_suggestedFilename_completionHandler_(self, download: WKDownload, response: NSURLResponse, suggestedFilename: str, completionHandler: callable): ...
432
def download_willPerformHTTPRedirection_newRequest_decisionHandler_(self, download: WKDownload, response: NSHTTPURLResponse, request: NSURLRequest, decisionHandler: callable): ...
433
def download_didReceiveAuthenticationChallenge_completionHandler_(self, download: WKDownload, challenge: NSURLAuthenticationChallenge, completionHandler: callable): ...
434
def download_didWriteData_totalBytesWritten_totalBytesExpectedToWrite_(self, download: WKDownload, bytesWritten: int, totalBytesWritten: int, totalBytesExpectedToWrite: int): ...
435
def downloadDidFinish_(self, download: WKDownload): ...
436
def download_didFailWithError_resumeData_(self, download: WKDownload, error: NSError, resumeData: NSData): ...
437
```
438
439
### Usage Examples
440
441
#### Basic Navigation Setup
442
443
```python
444
import WebKit
445
from Foundation import NSURL, NSURLRequest
446
447
class NavigationDelegate:
448
def webView_decidePolicyForNavigationAction_decisionHandler_(self, web_view, navigation_action, decision_handler):
449
# Log navigation attempts
450
url = navigation_action.request().URL()
451
nav_type = navigation_action.navigationType()
452
print(f"Navigating to: {url.absoluteString()}, type: {nav_type}")
453
454
# Allow all navigation
455
decision_handler(WebKit.WKNavigationActionPolicyAllow)
456
457
def webView_didFinishNavigation_(self, web_view, navigation):
458
print(f"Finished loading: {web_view.title()}")
459
460
def webView_didFailNavigation_withError_(self, web_view, navigation, error):
461
print(f"Navigation failed: {error.localizedDescription()}")
462
463
# Create web view and set delegate
464
config = WebKit.WKWebViewConfiguration.alloc().init()
465
web_view = WebKit.WKWebView.alloc().initWithFrame_configuration_(
466
((0, 0), (800, 600)), config
467
)
468
469
nav_delegate = NavigationDelegate()
470
web_view.setNavigationDelegate_(nav_delegate)
471
472
# Navigate to URL
473
url = NSURL.URLWithString_("https://www.apple.com")
474
request = NSURLRequest.requestWithURL_(url)
475
web_view.loadRequest_(request)
476
```
477
478
#### Working with History
479
480
```python
481
import WebKit
482
483
# Get back/forward list
484
back_forward_list = web_view.backForwardList()
485
486
# Check navigation availability
487
can_go_back = web_view.canGoBack()
488
can_go_forward = web_view.canGoForward()
489
490
print(f"Can go back: {can_go_back}")
491
print(f"Can go forward: {can_go_forward}")
492
493
# Get current item
494
current_item = back_forward_list.currentItem()
495
if current_item:
496
print(f"Current page: {current_item.title()}")
497
print(f"Current URL: {current_item.URL().absoluteString()}")
498
499
# Navigate history
500
if can_go_back:
501
web_view.goBack()
502
503
# Get history items
504
back_list = back_forward_list.backList()
505
for item in back_list:
506
print(f"Back item: {item.title()} - {item.URL().absoluteString()}")
507
```
508
509
#### Custom URL Scheme Handler
510
511
```python
512
import WebKit
513
from Foundation import NSURLResponse, NSData, NSURL
514
515
class CustomSchemeHandler:
516
def webView_startURLSchemeTask_(self, web_view, url_scheme_task):
517
request = url_scheme_task.request()
518
url = request.URL()
519
520
# Handle custom:// URLs
521
if url.scheme() == "custom":
522
path = url.path()
523
524
if path == "/hello":
525
# Create response
526
response = NSURLResponse.alloc().initWithURL_MIMEType_expectedContentLength_textEncodingName_(
527
url, "text/html", -1, "utf-8"
528
)
529
url_scheme_task.didReceiveResponse_(response)
530
531
# Send HTML content
532
html = "<html><body><h1>Hello from custom scheme!</h1></body></html>"
533
data = html.encode('utf-8')
534
url_scheme_task.didReceiveData_(NSData.dataWithBytes_length_(data, len(data)))
535
url_scheme_task.didFinish()
536
else:
537
# Handle 404
538
error = NSError.errorWithDomain_code_userInfo_(
539
"CustomSchemeError", 404, {"description": "Not Found"}
540
)
541
url_scheme_task.didFailWithError_(error)
542
543
def webView_stopURLSchemeTask_(self, web_view, url_scheme_task):
544
# Clean up if needed
545
pass
546
547
# Register custom scheme handler
548
config = WebKit.WKWebViewConfiguration.alloc().init()
549
scheme_handler = CustomSchemeHandler()
550
config.setURLSchemeHandler_forURLScheme_(scheme_handler, "custom")
551
552
# Create web view with custom scheme support
553
web_view = WebKit.WKWebView.alloc().initWithFrame_configuration_(
554
((0, 0), (800, 600)), config
555
)
556
557
# Navigate to custom URL
558
custom_url = NSURL.URLWithString_("custom://hello")
559
request = NSURLRequest.requestWithURL_(custom_url)
560
web_view.loadRequest_(request)
561
```
562
563
#### Download Handling
564
565
```python
566
import WebKit
567
568
class DownloadDelegate:
569
def download_decideDestinationUsingResponse_suggestedFilename_completionHandler_(self, download, response, suggested_filename, completion_handler):
570
# Choose download location
571
downloads_dir = "~/Downloads"
572
file_path = f"{downloads_dir}/{suggested_filename}"
573
completion_handler(NSURL.fileURLWithPath_(file_path))
574
575
def download_didWriteData_totalBytesWritten_totalBytesExpectedToWrite_(self, download, bytes_written, total_written, total_expected):
576
# Update download progress
577
if total_expected > 0:
578
progress = (total_written / total_expected) * 100
579
print(f"Download progress: {progress:.1f}%")
580
581
def downloadDidFinish_(self, download):
582
print("Download completed successfully")
583
584
def download_didFailWithError_resumeData_(self, download, error, resume_data):
585
print(f"Download failed: {error.localizedDescription()}")
586
587
# Set up download delegate in your navigation delegate
588
class NavigationDelegate:
589
def webView_navigationResponse_didBecomeDownload_(self, web_view, navigation_response, download):
590
download_delegate = DownloadDelegate()
591
download.setDelegate_(download_delegate)
592
print("Download started")
593
```