WKWebView中新增了一個(gè)功能,可以對(duì)WebView的內(nèi)容添加一些自定義的過濾規(guī)則。這個(gè)功能原來在 Safari Extension 中被引入,從 11 開始同樣適用于WKWebView。
使用方法
原理上就是提供一個(gè) JSON 給 WebKit,這個(gè) JSON 包括內(nèi)容的觸發(fā)規(guī)則(trigger)和對(duì)應(yīng)的處理方式(action)。比如:
1
2
3
4
5
6
|
[{ "trigger" : { "url-filter" : ".*" }, "action" : { "type" : "make-https" } }] |
WebKit 會(huì)把攔截規(guī)則編譯成高效的二進(jìn)制碼。使用方法如下:
1
2
3
4
5
6
7
8
9
|
WKContentRuleListStore. default ().compileContentRuleList( forIdentifier: "ContentBlockingRules" , encodedContentRuleList: jsonString) { (contentRuleList, error) in if let error = error { return } let configuration = WKWebViewConfiguration() configuration.userContentController.add(ruleList!) } |
可使用的處理方式:Action
對(duì)應(yīng)的 Action 有以下幾種:
- block:放棄加載資源,如果該資源已經(jīng)緩存也忽略緩存
- block-cookies:所有發(fā)送的請(qǐng)求的header中都會(huì)過濾掉cookie
-
css-display-none:隱藏使用 CSS selector 的頁面元素,同時(shí)還有關(guān)聯(lián)的selector:
1234
"action"
: {
"type"
:
"css-display-none"
,
"selector"
:
"#newsletter, :matches(.main-page, .article) .news-overlay"
}
- ignore-previous-rules:前面觸發(fā)的規(guī)則不執(zhí)行
- make-https:把網(wǎng)頁里的 http 請(qǐng)求改為 https 請(qǐng)求
規(guī)則觸發(fā)器:trigger
觸發(fā)器必須有url-filter,可選的鍵有:resource-type、if-domain、unless-domain
- url-filter 匹配 URL 的正則表達(dá)式
- if-domain 或者 unless-domain if-domain:規(guī)則只在這些域名下起作用。unless-domain:這些域名除外。
-
resource-type 資源的類型,對(duì)應(yīng)的 value 有:
- document
- image
- style-sheet
- script
- font
- raw (Any untyped load, such as XMLHttpRequest)
- svg-document
- media
- popup
-
load-type 資源的歸屬。默認(rèn)是全部的資源。如果收到填有兩種 value:
- first-party 只有當(dāng)資源和頁面的scheme、域名、端口一致時(shí)才觸發(fā)
- third-party 只有當(dāng)資源和頁面的域名不一致時(shí)才觸發(fā)
舉個(gè) trigger 的示例就是:
1
2
3
4
5
|
"trigger" : { "url-filter" : ".*" , "resource-type" : [ "image" , "style-sheet" ], "unless-domain" : [ "your-content-server.com" , "trusted-content-server.com" ] } |
總結(jié)
可以通過配置規(guī)則攔截頁面里的資源請(qǐng)求、隱藏頁面里的指定元素、將http請(qǐng)求轉(zhuǎn)換成https。
參考
WWDC 17:customized_loading_in_wkwebview
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.jianshu.com/p/8af24e9dc82e