Compile your JSON rules with WKContentRuleListStore, load them into a WKWebView pointed at a local test server, and assert that didFailProvisionalNavigation fires for blocked main-frame URLs. Content-blocker JSON compiles whether or not the rules fire: a regex that matches nothing still produces a valid WKContentRuleList, and Safari will happily load the ads you meant to block. The only reliable check is to drive a real WKWebView over a real URL and observe the outcome. This guide builds that check into one XCTest with a local HTTP server and a JSON evidence attachment.
What do the content-blocker JSON fields mean?
A rule list is a JSON array of objects, each with a trigger and an action. The archived Apple Content Blocker Extension guide (developer.apple.com/library/archive/.../ContentBlocker.html) shows the shape:
[
{
"trigger": {
"url-filter": "tracker\\.example\\.com",
"resource-type": ["script", "image"]
},
"action": { "type": "block" }
},
{
"trigger": {
"url-filter": "cdn\\.ads\\.example\\.com/banner",
"resource-type": ["image"]
},
"action": { "type": "block" }
}
]
Fields you will touch most:
| Field | Location | Notes |
|---|---|---|
url-filter | trigger | Required. Regular expression against the full resource URL. Escape literal dots as \\.. |
resource-type | trigger | Optional array. The archive guide confirms script and image; the Safari Content-Blocking Rules Reference lists additional values. Verify against the current reference for your Safari version. |
if-domain / unless-domain | trigger | Optional domain scoping. |
type | action | Required. block is explicitly documented in the archive guide. Other action types are described in the Safari Content-Blocking Rules Reference. |
selector | action | Required when type is a CSS-hiding action. |
The archive guide does not state a rule count cap. Third-party developers often quote a practical ceiling, but do not treat an unspecified number as a published limit. Measure against your own rule set. Both WKContentRuleListStore and WKUserContentController are @MainActor classes, so use them on the main thread.
How do I compile and load the rule list?
Call compileContentRuleList(forIdentifier:encodedContentRuleList:completionHandler:) on the default store. The store also has a matching lookUpContentRuleList(...), and compiled lists persist in it, so repeat runs can reuse the identifier.
// ContentBlockerTestHelper.swift (test target)
import WebKit
import XCTest
@MainActor
enum ContentBlockerTestHelper {
static func compileRules(from jsonURL: URL, identifier: String) async throws -> WKContentRuleList {
let json = try String(contentsOf: jsonURL, encoding: .utf8)
guard let store = WKContentRuleListStore.default() else {
throw NSError(domain: "ContentBlocker", code: -2,
userInfo: [NSLocalizedDescriptionKey: "Default rule list store unavailable"])
}
return try await withCheckedThrowingContinuation { continuation in
store.compileContentRuleList(forIdentifier: identifier,
encodedContentRuleList: json) { list, error in
if let error = error {
continuation.resume(throwing: error)
} else if let list = list {
continuation.resume(returning: list)
} else {
continuation.resume(throwing: NSError(domain: "ContentBlocker", code: -1,
userInfo: [NSLocalizedDescriptionKey: "Compile returned nil without error"]))
}
}
}
}
static func removeRules(identifier: String) async {
guard let store = WKContentRuleListStore.default() else { return }
await withCheckedContinuation { continuation in
store.removeContentRuleList(forIdentifier: identifier) { _ in
continuation.resume()
}
}
}
}
A non-nil error means the JSON was structurally rejected. Both arguments nil means the JSON parsed but produced no rules, usually because of a typo in trigger. The helper is illustrative, so run it in your own test target to confirm behavior on your Xcode and SDK combination.
How do I test blocking with a local server and WKWebView?
Write rules whose url-filter matches the main document URL, so the top-level navigation fails and didFailProvisionalNavigation fires. WKContentRuleList filters sub-resources (scripts, images, stylesheets) inside the network layer, so those blocks do not raise WKNavigationDelegate callbacks. For sub-resource rules, assert against the loaded DOM with evaluateJavaScript.
Start a local HTTP server and keep its files in a unique directory per run so parallel jobs do not collide:
# Setup step before running the XCTest.
TEST_SERVER_DIR="$(mktemp -d -t cb-rule-test)"
cp -R ./Tests/Fixtures/content-blocker/* "$TEST_SERVER_DIR/"
python3 -m http.server 8765 --directory "$TEST_SERVER_DIR" &
TEST_SERVER_PID=$!
trap 'kill "$TEST_SERVER_PID" 2>/dev/null; rm -rf "$TEST_SERVER_DIR"' EXIT
Two stub pages are enough: blocked.html (a block rule points at its URL) and safe.html (no rule points at it). Example rule file loaded from the test bundle:
[
{ "trigger": { "url-filter": "localhost:8765/blocked\\.html" },
"action": { "type": "block" } }
]
The XCTest records every navigation outcome, attaches a JSON summary, and removes the compiled rule list during teardown so the next run starts clean.
// ContentBlockerRuleTests.swift
import XCTest
import WebKit
struct RuleMatchRecord: Codable {
let url: String
let outcome: String // "blocked" | "allowed"
let errorDomain: String?
let errorCode: Int?
}
struct RuleMatchSummary: Codable {
let identifier: String
let records: [RuleMatchRecord]
}
@MainActor
final class RecordingNavigationDelegate: NSObject, WKNavigationDelegate {
var records: [RuleMatchRecord] = []
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
let url = webView.url?.absoluteString ?? "unknown"
records.append(RuleMatchRecord(url: url, outcome: "allowed",
errorDomain: nil, errorCode: nil))
}
func webView(_ webView: WKWebView,
didFailProvisionalNavigation navigation: WKNavigation!,
withError error: Error) {
let ns = error as NSError
let url = webView.url?.absoluteString
?? (ns.userInfo[NSURLErrorFailingURLStringErrorKey] as? String)
?? "unknown"
records.append(RuleMatchRecord(url: url, outcome: "blocked",
errorDomain: ns.domain, errorCode: ns.code))
}
}
@MainActor
final class ContentBlockerRuleTests: XCTestCase {
let identifier = "ci-test-blocker-\(UUID().uuidString)"
let serverBase = "http://localhost:8765"
override func tearDown() async throws {
await ContentBlockerTestHelper.removeRules(identifier: identifier)
}
func testRulesBlockExpectedURLs() async throws {
let rulesURL = try XCTUnwrap(
Bundle(for: type(of: self)).url(forResource: "rules", withExtension: "json"),
"rules.json not found in test bundle"
)
let ruleList = try await ContentBlockerTestHelper.compileRules(
from: rulesURL, identifier: identifier
)
let config = WKWebViewConfiguration()
config.userContentController.add(ruleList)
// Fresh WKWebView per URL so a second load() does not cancel the first
// navigation and get mis-reported as a block.
var allRecords: [RuleMatchRecord] = []
for page in ["blocked.html", "safe.html"] {
let delegate = RecordingNavigationDelegate()
let webView = WKWebView(frame: .zero, configuration: config)
webView.navigationDelegate = delegate
let url = URL(string: "\(serverBase)/\(page)")!
webView.load(URLRequest(url: url))
let deadline = Date().addingTimeInterval(5)
while delegate.records.isEmpty && Date() < deadline {
try await Task.sleep(nanoseconds: 100_000_000)
}
XCTAssertFalse(delegate.records.isEmpty,
"No navigation outcome for \(page). Is the test server running on 8765?")
allRecords.append(contentsOf: delegate.records)
}
let summary = RuleMatchSummary(identifier: identifier, records: allRecords)
attachSummary(summary)
let blocked = allRecords.filter { $0.outcome == "blocked" }.count
let allowed = allRecords.filter { $0.outcome == "allowed" }.count
XCTAssertGreaterThan(blocked, 0,
"Expected at least one blocked navigation; check rules.json patterns match the main-frame URL.")
XCTAssertGreaterThan(allowed, 0,
"Expected at least one allowed navigation; check safe.html loads.")
}
private func attachSummary(_ summary: RuleMatchSummary) {
guard let data = try? JSONEncoder().encode(summary) else { return }
let attachment = XCTAttachment(data: data, uniformTypeIdentifier: "public.json")
attachment.name = "rule-match-summary.json"
attachment.lifetime = .keepAlways
add(attachment)
}
}
What does the JSON evidence look like?
After the run, Xcode's Report Navigator shows rule-match-summary.json on the test. The exact errorDomain and errorCode depend on your WebKit version and are intentionally left unasserted, so the test keeps working across SDKs.
{
"identifier": "ci-test-blocker-<uuid>",
"records": [
{ "url": "http://localhost:8765/blocked.html",
"outcome": "blocked", "errorDomain": "<webkit-domain>", "errorCode": 0 },
{ "url": "http://localhost:8765/safe.html",
"outcome": "allowed", "errorDomain": null, "errorCode": null }
]
}
A zero blocked count when you expected blocking almost always means the url-filter regex did not match the main-frame URL, or the rule targets a sub-resource. For the sub-resource case, replace the navigation assertion with evaluateJavaScript("document.querySelectorAll('script[src*=\\\"tracker\\\"]').length") after the page loads and expect 0. A WKWebView created off-screen still fires navigation delegates, but layout-sensitive JavaScript (sizes, media queries) may not, so keep the assertions focused on network behavior.
Does this test need a Mac?
Yes. WKContentRuleListStore ships only inside Apple's WebKit framework on macOS and iOS, so a Linux CI runner cannot execute this test. WebKit automation stacks such as Playwright-WebKit bundle a separate build of WebKit and do not expose the content-rule-list API.
Can the Intel Mac VM compile and run the content blocker test?
The Intel Mac VM ($25 a month, $2 a day) is enough: it runs macOS Sequoia with Xcode 26.3 or earlier, compiles this XCTest, runs the WebKit framework and produces the JSON attachment. It cannot run Xcode 26.4 or later, arm64-only binaries or visionOS, so choose the Apple Silicon Mac VM ($39 a month, $6 a day) for those. Because a daily plan covers 24 hours from the order, a short project does not need a full month. We have not run this test on any plan. See the Mac hosting plans and check the macOS version shown before purchase.