> For the complete documentation index, see [llms.txt](https://philm.gitbook.io/philm-ios-wiki/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://philm.gitbook.io/philm-ios-wiki/mei-zhou-yue-du/ios-11wkwebview-nei-rong-guo-lv-gui-ze-xiang-jie.md).

# iOS 11：WKWebView内容过滤规则详解

WKWebView中新增了一个功能，可以对WebView的内容添加一些自定义的过滤规则。这个功能原来在 Safari Extension 中被引入，从 11 开始同样适用于WKWebView。

## 使用方法

原理上就是提供一个 JSON 给 WebKit，这个 JSON 包括内容的触发规则（trigger）和对应的处理方式（action）。比如：

```
[{
"trigger": {
"url-filter": ".*" },
"action": {
"type": "make-https"} 
}]
```

WebKit 会把拦截规则编译成高效的二进制码。使用方法如下：

```
WKContentRuleListStore.default().compileContentRuleList(
   forIdentifier: "ContentBlockingRules",
  encodedContentRuleList: jsonString) { (contentRuleList, error) in
    if let error = error {
         return
    }
  let configuration = WKWebViewConfiguration()          
  configuration.userContentController.add(ruleList!)  
}
```

## 可使用的处理方式：Action

对应的 Action 有以下几种：

* block

放弃加载资源，如果该资源已经缓存也忽略缓存

* block-cookies

所有发送的请求的header中都会过滤掉cookie

* css-display-none

隐藏使用 CSS selector 的页面元素，同时还有关联的selector：

```
"action": {
        "type": "css-display-none",
        "selector": "#newsletter, :matches(.main-page, .article) .news-overlay"
}
```

* ignore-previous-rules

前面触发的规则不执行

* make-https

把网页里的 http 请求改为 https 请求

## 规则触发器：trigger

触发器必须有`url-filter`，可选的键有：`resource-type`、`if-domain`、`unless-domain`

* url-filter

匹配 URL 的正则表达式

* if-domain 或者 unless-domain

if-domain：规则只在这些域名下起作用。unless-domain：这些域名除外。

* resource-type

资源的类型，对应的 value 有：

* document
* image
* style-sheet
* script
* font
* raw (Any untyped \*   load, such as XMLHttpRequest)
* svg-document
* media
* popup
* load-type

资源的归属。默认是全部的资源。如果收到填有两种 value：

* first-party

  只有当资源和页面的scheme、域名、端口一致时才触发
* third-party

  只有当资源和页面的域名不一致时才触发

举个 trigger 的示例就是：

```
"trigger": {
        "url-filter": ".*",
        "resource-type": ["image", "style-sheet"],
        "unless-domain": ["your-content-server.com", "trusted-content-server.com"]
}
```

## 总结

可以通过配置规则拦截页面里的资源请求、隐藏页面里的指定元素、将http请求转换成https。

## 参考

[Content Blocking Rules](https://developer.apple.com/library/content/documentation/Extensions/Conceptual/ContentBlockingRules/CreatingRules/CreatingRules.html)

[WWDC 17：customized\_loading\_in\_wkwebview](https://developer.apple.com/videos/play/wwdc2017/220/)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://philm.gitbook.io/philm-ios-wiki/mei-zhou-yue-du/ios-11wkwebview-nei-rong-guo-lv-gui-ze-xiang-jie.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
