Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift WKWebView disable Javascript

I am using WKWebView to load some links in my application. I want to disable all the annoying JavaScript banners that appear on almost all web pages. Is there a simple function that can do that?

like image 492
Swift1 Avatar asked Dec 21 '15 21:12

Swift1


2 Answers

WKWebView has a configuration to disable JavaScript, check the Apple reference.

var javaScriptEnabled: Bool

Update

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)
}
like image 194
Rashwan L Avatar answered Oct 13 '22 05:10

Rashwan L


For us who still use Objective-C, here is the solution:

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];
like image 1
turingtested Avatar answered Oct 13 '22 03:10

turingtested