WKWebView中新增了一個(gè)功能,可以對(duì)WebView的內(nèi)容添加一些自定義的過濾規(guī)則。這個(gè)功能原來(lái)在 Safari Extension 中被引入,從 11 開始同樣適用于WKWebView。
使用方法
原理上就是提供一個(gè) JSON 給 WebKit,這個(gè) JSON 包括內(nèi)容的觸發(fā)規(guī)則(trigger)和對(duì)應(yīng)的處理方式(action)。比如:
[{"trigger": {"url-filter": ".*" },"action": {"type": "make-https"} }]WebKit 會(huì)把攔截規(guī)則編譯成高效的二進(jìn)制碼。使用方法如下:
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 有以下幾種:
"action": { "type": "css-display-none", "selector": "#newsletter, :matches(.main-page, .article) .news-overlay"}
規(guī)則觸發(fā)器:trigger
觸發(fā)器必須有url-filter,可選的鍵有:resource-type、if-domain、unless-domain
舉個(gè) trigger 的示例就是:
"trigger": { "url-filter": ".*", "resource-type": ["image", "style-sheet"], "unless-domain": ["your-content-server.com", "trusted-content-server.com"]}總結(jié)
可以通過配置規(guī)則攔截頁(yè)面里的資源請(qǐng)求、隱藏頁(yè)面里的指定元素、將http請(qǐng)求轉(zhuǎn)換成https。
參考
WWDC 17:customized_loading_in_wkwebview
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注