0
# Content Management
1
2
This document covers user scripts, content rules, cookie management, and website data handling in WebKit. These features provide control over web content behavior, security policies, and data storage for both security and functionality purposes.
3
4
## User Content Controller
5
6
Central management point for user scripts and message handlers.
7
8
```python { .api }
9
class WKUserContentController:
10
def init(self):
11
"""Initialize a new user content controller."""
12
13
def addUserScript_(self, userScript):
14
"""Add a user script to be injected into web pages.
15
16
Args:
17
userScript: WKUserScript instance to add
18
"""
19
20
def removeAllUserScripts(self):
21
"""Remove all user scripts from the controller."""
22
23
def addScriptMessageHandler_name_(self, scriptMessageHandler, name):
24
"""Add a script message handler for JavaScript-to-native communication.
25
26
Args:
27
scriptMessageHandler: Object implementing WKScriptMessageHandler protocol
28
name: String name that JavaScript will use to send messages
29
"""
30
31
def removeScriptMessageHandlerForName_(self, name):
32
"""Remove a script message handler by name.
33
34
Args:
35
name: String name of the handler to remove
36
"""
37
38
def addContentRuleList_(self, contentRuleList):
39
"""Add a content rule list for content blocking.
40
41
Args:
42
contentRuleList: WKContentRuleList instance
43
"""
44
45
def removeContentRuleList_(self, contentRuleList):
46
"""Remove a content rule list.
47
48
Args:
49
contentRuleList: WKContentRuleList instance to remove
50
"""
51
52
def removeAllContentRuleLists(self):
53
"""Remove all content rule lists."""
54
55
@property
56
def userScripts(self):
57
"""Get array of all user scripts."""
58
```
59
60
## User Scripts
61
62
JavaScript code injection into web pages.
63
64
```python { .api }
65
class WKUserScript:
66
def initWithSource_injectionTime_forMainFrameOnly_(self, source, injectionTime, forMainFrameOnly):
67
"""Initialize a user script with source code and injection settings.
68
69
Args:
70
source: String containing JavaScript source code
71
injectionTime: WKUserScriptInjectionTime constant
72
forMainFrameOnly: Boolean - True to inject only in main frame, False for all frames
73
"""
74
75
@property
76
def source(self):
77
"""Get the JavaScript source code."""
78
79
@property
80
def injectionTime(self):
81
"""Get the injection time (document start or end)."""
82
83
@property
84
def isForMainFrameOnly(self):
85
"""Check if script is only for main frame."""
86
87
# User Script Injection Times
88
WKUserScriptInjectionTimeAtDocumentStart = 0
89
WKUserScriptInjectionTimeAtDocumentEnd = 1
90
```
91
92
## Script Messages
93
94
Communication from JavaScript to native code.
95
96
```python { .api }
97
class WKScriptMessage:
98
@property
99
def body(self):
100
"""Get the message body (can be string, number, boolean, array, or dictionary)."""
101
102
@property
103
def webView(self):
104
"""Get the web view that sent the message."""
105
106
@property
107
def frameInfo(self):
108
"""Get information about the frame that sent the message."""
109
110
@property
111
def name(self):
112
"""Get the name of the message handler."""
113
114
class WKScriptMessageHandler:
115
def userContentController_didReceiveScriptMessage_(self, userContentController, message):
116
"""Handle script messages from JavaScript.
117
118
Args:
119
userContentController: The WKUserContentController
120
message: WKScriptMessage containing the message data
121
"""
122
```
123
124
## Content Rule Lists
125
126
Content blocking and modification rules.
127
128
```python { .api }
129
class WKContentRuleList:
130
@property
131
def identifier(self):
132
"""Get the unique identifier for this rule list."""
133
134
class WKContentRuleListStore:
135
@classmethod
136
def defaultStore(cls):
137
"""Get the default content rule list store."""
138
139
def compileContentRuleList_forIdentifier_completionHandler_(self, ruleList, identifier, completionHandler):
140
"""Compile content rules from JSON.
141
142
Args:
143
ruleList: String containing JSON content rules
144
identifier: Unique identifier for the rule list
145
completionHandler: Block called with (WKContentRuleList, NSError)
146
"""
147
148
def lookUpContentRuleListForIdentifier_completionHandler_(self, identifier, completionHandler):
149
"""Look up an existing content rule list.
150
151
Args:
152
identifier: String identifier of the rule list
153
completionHandler: Block called with (WKContentRuleList, NSError)
154
"""
155
156
def removeContentRuleListForIdentifier_completionHandler_(self, identifier, completionHandler):
157
"""Remove a content rule list from storage.
158
159
Args:
160
identifier: String identifier of the rule list to remove
161
completionHandler: Block called with (NSError,)
162
"""
163
164
def getAvailableContentRuleListIdentifiers_(self, completionHandler):
165
"""Get identifiers of available content rule lists.
166
167
Args:
168
completionHandler: Block called with (NSArray,)
169
"""
170
```
171
172
## Website Data Store
173
174
Management of website data including cookies, cache, and local storage.
175
176
```python { .api }
177
class WKWebsiteDataStore:
178
@classmethod
179
def defaultDataStore(cls):
180
"""Get the default website data store."""
181
182
@classmethod
183
def nonPersistentDataStore(cls):
184
"""Create a non-persistent (private) data store."""
185
186
def fetchDataRecordsOfTypes_completionHandler_(self, dataTypes, completionHandler):
187
"""Fetch website data records of specified types.
188
189
Args:
190
dataTypes: Set of WKWebsiteDataType constants
191
completionHandler: Block called with (NSArray,) of WKWebsiteDataRecord
192
"""
193
194
def removeDataOfTypes_forDataRecords_completionHandler_(self, dataTypes, dataRecords, completionHandler):
195
"""Remove website data for specific records.
196
197
Args:
198
dataTypes: Set of data types to remove
199
dataRecords: Array of WKWebsiteDataRecord instances
200
completionHandler: Block called when removal completes
201
"""
202
203
def removeDataOfTypes_modifiedSince_completionHandler_(self, dataTypes, date, completionHandler):
204
"""Remove website data modified since a date.
205
206
Args:
207
dataTypes: Set of data types to remove
208
date: NSDate - remove data modified since this date
209
completionHandler: Block called when removal completes
210
"""
211
212
@property
213
def isPersistent(self):
214
"""Check if the data store is persistent."""
215
216
@property
217
def httpCookieStore(self):
218
"""Get the HTTP cookie store for this data store."""
219
220
# Website Data Types
221
WKWebsiteDataTypeCookies = "WKWebsiteDataTypeCookies"
222
WKWebsiteDataTypeDiskCache = "WKWebsiteDataTypeDiskCache"
223
WKWebsiteDataTypeMemoryCache = "WKWebsiteDataTypeMemoryCache"
224
WKWebsiteDataTypeOfflineWebApplicationCache = "WKWebsiteDataTypeOfflineWebApplicationCache"
225
WKWebsiteDataTypeSessionStorage = "WKWebsiteDataTypeSessionStorage"
226
WKWebsiteDataTypeLocalStorage = "WKWebsiteDataTypeLocalStorage"
227
WKWebsiteDataTypeWebSQLDatabases = "WKWebsiteDataTypeWebSQLDatabases"
228
WKWebsiteDataTypeIndexedDBDatabases = "WKWebsiteDataTypeIndexedDBDatabases"
229
```
230
231
## Cookie Management
232
233
HTTP cookie handling and storage.
234
235
```python { .api }
236
class WKHTTPCookieStore:
237
def getAllCookies_(self, completionHandler):
238
"""Get all HTTP cookies.
239
240
Args:
241
completionHandler: Block called with (NSArray,) of NSHTTPCookie
242
"""
243
244
def setCookie_completionHandler_(self, cookie, completionHandler):
245
"""Set an HTTP cookie.
246
247
Args:
248
cookie: NSHTTPCookie instance to set
249
completionHandler: Optional block called when cookie is set
250
"""
251
252
def deleteCookie_completionHandler_(self, cookie, completionHandler):
253
"""Delete an HTTP cookie.
254
255
Args:
256
cookie: NSHTTPCookie instance to delete
257
completionHandler: Optional block called when cookie is deleted
258
"""
259
260
def addObserver_(self, observer):
261
"""Add a cookie change observer.
262
263
Args:
264
observer: Object implementing WKHTTPCookieStoreObserver protocol
265
"""
266
267
def removeObserver_(self, observer):
268
"""Remove a cookie change observer.
269
270
Args:
271
observer: Observer object to remove
272
"""
273
274
class WKHTTPCookieStoreObserver:
275
def cookiesDidChangeInCookieStore_(self, cookieStore):
276
"""Called when cookies change in the store.
277
278
Args:
279
cookieStore: The WKHTTPCookieStore that changed
280
"""
281
```
282
283
## Website Data Records
284
285
Information about stored website data.
286
287
```python { .api }
288
class WKWebsiteDataRecord:
289
@property
290
def displayName(self):
291
"""Get the display name for this data record (typically domain name)."""
292
293
@property
294
def dataTypes(self):
295
"""Get the set of data types stored for this record."""
296
```
297
298
## Usage Examples
299
300
### User Script Injection
301
302
```python
303
import WebKit
304
305
# Create user content controller
306
content_controller = WebKit.WKUserContentController.alloc().init()
307
308
# Create user script to inject CSS
309
css_script = """
310
var style = document.createElement('style');
311
style.textContent = 'body { background-color: #f0f0f0; }';
312
document.head.appendChild(style);
313
"""
314
315
user_script = WebKit.WKUserScript.alloc().initWithSource_injectionTime_forMainFrameOnly_(
316
css_script,
317
WebKit.WKUserScriptInjectionTimeAtDocumentEnd,
318
False # Apply to all frames
319
)
320
321
content_controller.addUserScript_(user_script)
322
323
# Configure web view
324
config = WebKit.WKWebViewConfiguration.alloc().init()
325
config.setUserContentController_(content_controller)
326
```
327
328
### JavaScript-to-Python Communication
329
330
```python
331
import WebKit
332
333
class MessageHandler:
334
def userContentController_didReceiveScriptMessage_(self, controller, message):
335
print(f"Received message: {message.body()}")
336
# Handle the message from JavaScript
337
338
# Set up message handler
339
handler = MessageHandler()
340
content_controller = WebKit.WKUserContentController.alloc().init()
341
content_controller.addScriptMessageHandler_name_(handler, "nativeHandler")
342
343
# JavaScript can now call: window.webkit.messageHandlers.nativeHandler.postMessage("Hello Python!");
344
```
345
346
### Content Blocking
347
348
```python
349
import WebKit
350
351
# JSON rule list to block ads
352
content_rules = """
353
[
354
{
355
"trigger": {
356
"url-filter": ".*",
357
"resource-type": ["image"],
358
"if-domain": ["ads.example.com", "tracker.example.com"]
359
},
360
"action": {
361
"type": "block"
362
}
363
}
364
]
365
"""
366
367
store = WebKit.WKContentRuleListStore.defaultStore()
368
store.compileContentRuleList_forIdentifier_completionHandler_(
369
content_rules,
370
"AdBlocker",
371
lambda rule_list, error: print("Content rules compiled" if rule_list else f"Error: {error}")
372
)
373
```
374
375
### Cookie Management
376
377
```python
378
import WebKit
379
from Foundation import NSHTTPCookie
380
381
# Get all cookies
382
cookie_store = data_store.httpCookieStore()
383
cookie_store.getAllCookies_(lambda cookies: print(f"Found {len(cookies)} cookies"))
384
385
# Create and set a cookie
386
cookie = NSHTTPCookie.cookieWithProperties_({
387
"NSHTTPCookieName": "session_id",
388
"NSHTTPCookieValue": "abc123",
389
"NSHTTPCookieDomain": "example.com",
390
"NSHTTPCookiePath": "/"
391
})
392
393
cookie_store.setCookie_completionHandler_(cookie, lambda: print("Cookie set"))
394
```
395
396
These content management features provide powerful control over web content behavior, security policies, and data storage, enabling sophisticated web application development with fine-grained control over the browsing experience.