SoFunction
Updated on 2025-04-03

iOS11 WKWebView content filtering rules detailed explanation

A new feature has been added to WKWebView, which can add some custom filtering rules to the content of the WebView. This feature was originally introduced in Safari Extension and is also applicable to WKWebView starting from 11.

How to use

In principle, it is to provide a JSON to WebKit, which includes the triggering rules (triggers) of the content and the corresponding handling methods (actions). for example:

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

WebKit compiles interception rules into efficient binary code. How to use it is as follows:

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

Can be used for processing: Action

The corresponding Actions are as follows:

  1. block: Abandon loading the resource, and ignore the cache if the resource has been cached.
  2. block-cookies: All requested requests are filtered out in the header
  3. css-display-none: Hide page elements using CSS selector, and also associated selectors:
    "action": {
       "type": "css-display-none",
       "selector": "#newsletter, :matches(.main-page, .article) .news-overlay"
    }

  4. ignore-previous-rules: The rule triggered before is not executed
  5. make-https: Change the http request in the web page to https request

Rule trigger: trigger

The trigger must have a url-filter. The optional keys are: resource-type, if-domain, unless-domain

  1. url-filter regex matching URL
  2. if-domain or unless-domain if-domain: The rule only works under these domains. unless-domain: Except for these domain names.
  3. The type of resource-type resource, the corresponding value is:
    1. document
    2. image
    3. style-sheet
    4. script
    5. font
    6. raw (Any untyped load, such as XMLHttpRequest)
    7. svg-document
    8. media
    9. popup
  4. load-type The attribution of the resource. By default, all resources are all. If you receive a two value:
    1. first-party triggers only when the resource and the page's scheme, domain name, and port are the same.
    2. third-party triggers only if the domain name of the resource and the page are inconsistent

For example, a trigger is:

"trigger": {
    "url-filter": ".*",
    "resource-type": ["image", "style-sheet"],
    "unless-domain": ["", ""]
}

Summarize

You can block resource requests in the page, hide specified elements in the page, and convert http requests into https through configuration rules.

refer to

Content Blocking Rules

WWDC 17:customized_loading_in_wkwebview

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.