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)
}
}
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() .
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.
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.
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)
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With