Swift WKWebView 禁用 Javascript

Swift WKWebView disable Javascript

我正在使用 WKWebView 在我的应用程序中加载一些链接。我想禁用几乎所有网页上出现的所有烦人的 JavaScript 横幅。有没有简单的函数可以做到这一点?

WKWebView 有禁用 JavaScript 的配置,检查 Apple reference

var javaScriptEnabled: Bool

更新

let preferences = WKPreferences()
preferences.javaScriptEnabled = false

// Create a configuration for the preferences
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences

 // Instantiate the web view
webView = WKWebView(frame: view.bounds, configuration: configuration)

// Load page
if let theWebView = webView{
   let url = NSURL(string: "http://www.apple.com")
   let urlRequest = NSURLRequest(URL: url!)
   theWebView.loadRequest(urlRequest)
   theWebView.navigationDelegate = self
   view.addSubview(theWebView)
}

对于还在使用Objective-C的我们来说,解决方法如下:

WKPreferences *prefs = [[WKPreferences alloc]init];
prefs.javaScriptEnabled = NO;

// Create a configuration for the preferences
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
config.preferences = prefs;

// Instantiate the web view
_webView = [[WKWebView alloc]initWithFrame:[[UIScreen mainScreen]bounds] configuration:config];