Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS WKWebView Swift javascript enable

I'm trying to develop a simple app to browse my website. However my website contains some javascript and it doesn't successfully show my website.

In the past develop with android the same app and had to activate like this:

webSettings.setJavaScriptEnabled(true);

This currently my code I just have missing the option to enable javascript if somebody can help will really appreciate

import WebKit

class ViewController: UIViewController {

  @IBOutlet weak var webView: WKWebView!

  override func viewDidLoad() {
    super.viewDidLoad()
    let url = URL(string: "http://132.148.136.31:8082")
    let urlRequest = URLRequest(url: url!)

    webView.load(urlRequest)
  }
}
like image 710
lusito92 Avatar asked Oct 31 '17 13:10

lusito92


People also ask

Is JavaScript enabled by default WKWebView?

JavaScript is disabled in a WebView by default. You can enable it through the WebSettings attached to your WebView . You can retrieve WebSettings with getSettings() , then enable JavaScript with setJavaScriptEnabled() .

Is WKWebView deprecated?

Since then, we've recommended that you adopt WKWebView instead of UIWebView and WebView — both of which were formally deprecated. New apps containing these frameworks are no longer accepted by the App Store.

What is the difference between UIWebView and WKWebView?

Unlike UIWebView, which does not support server authentication challenges, WKWebView does. In practical terms, this means that when using WKWebView, you can enter site credentials for password-protected websites.


2 Answers

Working with WKWebView is better to create it from code. And you can set javaScriptEnabled to configuration:

let preferences = WKPreferences()
preferences.javaScriptEnabled = true
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
let webview = WKWebView(frame: .zero, configuration: configuration)

Update. This is WKWebView in view controller class:

import UIKit
import WebKit

class ViewController: UIViewController {

    private var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let preferences = WKPreferences()
        preferences.javaScriptEnabled = true
        let configuration = WKWebViewConfiguration()
        configuration.preferences = preferences
        webView = WKWebView(frame: view.bounds, configuration: configuration)
        view.addSubview(webView)
    }
}
like image 86
Andrew Bogaevskyi Avatar answered Oct 11 '22 13:10

Andrew Bogaevskyi


For those who are building for iOS 14 with Swift 5 and Xcode 12, it has changed to the following ...

webView.configuration.defaultWebpagePreferences.allowsContentJavaScript = true
like image 26
Martin M Avatar answered Oct 11 '22 13:10

Martin M