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:
- block: Abandon loading the resource, and ignore the cache if the resource has been cached.
- block-cookies: All requested requests are filtered out in the header
- 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" }
- ignore-previous-rules: The rule triggered before is not executed
- 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
- url-filter regex matching URL
- if-domain or unless-domain if-domain: The rule only works under these domains. unless-domain: Except for these domain names.
- The type of resource-type resource, the corresponding value is:
- document
- image
- style-sheet
- script
- font
- raw (Any untyped load, such as XMLHttpRequest)
- svg-document
- media
- popup
- load-type The attribution of the resource. By default, all resources are all. If you receive a two value:
- first-party triggers only when the resource and the page's scheme, domain name, and port are the same.
- 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.