我想在我的WKWebView中屏蔽广告。 我有一个用于规则列表的 JSON 文件,其中添加了所有广告域,但它没有醒来。
我用来屏蔽广告的代码:
let jsonString =
"""
[{
"trigger": {
"url-filter": ".*",
"if-domain":["googleads.g.doubleclick.net","pagead.googlesyndication.com","pagead1.googlesyndication.com","pagead2.googlesyndication.com"]
},
"action": {
"type": "block"
}
}]
"""
WKContentRuleListStore.default().compileContentRuleList(forIdentifier: ruleId1, encodedContentRuleList: jsonString) { [weak self] (contentRuleList: WKContentRuleList?, error: Error?) in
if let error = error {
self?.printRuleListError(error, text: "compile json string literal")
return
}
if let list = contentRuleList {
self?.webview.configuration.userContentController.add(list)
UserDefaults.standard.set(true, forKey: ruleId1)
completion?()
}
}
}
如果我使用此规则,那么它会阻止 webView 中的图像:
let jsonString =
"""
[{
"trigger": {
"url-filter": ".*",
"resource-type": ["image", "style-sheet"]
},
"action": {
"type": "block"
}
}]
"""
试试这个:
let contentToBlock = """
{
"trigger": {
"url-filter": "googleads.g.doubleclick.net*"
},
"action": {
"type": "block"
}
},
{
"trigger": {
"url-filter": "pagead.googlesyndication.com*"
},
"action": {
"type": "block"
}
},
{
"trigger": {
"url-filter": "pagead1.googlesyndication.com*"
},
"action": {
"type": "block"
}
},
{
"trigger": {
"url-filter": "pagead2.googlesyndication.com*"
},
"action": {
"type": "block"
}
}
"""
如果您添加此项:googleads.g.doubleclick.net
请求特定域
GitHub上有一个名为WKJSON的框架。
只需复制此代码
import WKJSON
//...
let BlockerString = """
{
"trigger": {
"url-filter": "googleads.g.doubleclick.net*"
},
"action": {
"type": "block"
}
},
{
"trigger": {
"url-filter": "pagead.googlesyndication.com*"
},
"action": {
"type": "block"
}
},
{
"trigger": {
"url-filter": "pagead1.googlesyndication.com*"
},
"action": {
"type": "block"
}
},
{
"trigger": {
"url-filter": "pagead2.googlesyndication.com*"
},
"action": {
"type": "block"
}
}
"""
webView.JSONString(JSONString: BlockerString, webView: WKWebView)
如果要加载 JSON 文件,请使用此代码
webView.JSONFile(filePath: "blockerList", webView: WKWebView)
我强烈建议你使用这个 JSON