iOS WKWebView Swift javascript enable
Asked Answered
S

7

20

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 development with Android, the same app was enabling it like this:

webSettings.setJavaScriptEnabled(true);

This is my code now and I am missing the option to enable javascript:

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)
    }
}
Secondary answered 31/10, 2017 at 13:47 Comment(0)
I
27

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
Infamy answered 3/12, 2020 at 6:30 Comment(1)
this did not work for me, it still shows that js is disabled in my browser (webview)Merissameristem
S
17

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)
    }
}
Situs answered 31/10, 2017 at 14:51 Comment(5)
how do you implement this? I get so many errors If I do it in the view controller classSecondary
@Secondary I've updated my answer. It works well for me (Xcode 9.0.1, Swift 4). What errors do you have?Situs
I updated but still not working javascript look on the top the update please let me know really appreciateSecondary
@Secondary I've double checked it with google.com. It works! with .javaScriptEnabled = true I can open side bar, and if false - I cant. Are you sure that JavaScript works on your page by URl 132.148.136.31:8082 ? Did you try it in Safari? You also could debug you webview with a connected device in Safari on mac.Situs
It doesn't work for me. there is a function to show an auto fill drop down when clicking a button/ textfield in a webview. and which is working fine on android after enabling the javascript. but it doesn't work for me even if i enable the javascript as per your code above. Any solution..? would be appreciated. Thanks..!Tybie
A
9

You are using WKWebView storyboard view so you can directly access the configuration. So use preferences under your WKWebView configuration.

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!)

    // enable JS
    webView.configuration.preferences.javaScriptEnabled = true
    webView.load(urlRequest)
  }
}
Adorno answered 28/4, 2019 at 14:23 Comment(5)
Much cleaner syntax!Garett
@Md Imran Choudhury how I can check that my JS is loaded successfully.Siberia
You can set any JS action to your website to check.Adorno
Yes I have written JS function to display and evaluated in my swift class it is working. But in my case javascript is not calling is this because of script path which we are setting in HTML ? Is it because of JS interface not calling?Siberia
@MdImranChoudhury when I injected my script into my WKWebview then only I am able to display "JS Alert" after loading HTML. Resolved issue!Siberia
A
3

The above answer is right you need to set this value as true to enable JavaScript.

webView.configuration.preferences.javaScriptEnabled = true

But if the JS scripts are from a non-HTTPS source then you need to allow "App Transport Security's Arbitrary Loads".

Here is how to fix that:

  1. Navigate to Project Settings/Target/[your app's target]/Info.
  2. Check whether there is a dictionary called App Transport Security Settings. If not, create it.
  3. Inside it, create a boolean value called Allow Arbitrary Loads (if it's not there yet) and set it to YES.

enter image description here

Adorno answered 23/6, 2020 at 14:30 Comment(1)
'javaScriptEnabled' was deprecated in iOS 14.0: Use WKWebPagePreferences.allowsContentJavaScript to disable content JavaScript on a per-navigation basisMurton
A
3

If you check the official documentation of javaScriptEnabled or allowsContentJavaScript, it says:

The default value of this property is true.

So, you don't even need to write this if you don't disable it somewhere else.

However, if you need to enable javascript for WKWebView, here is how to do it:

iOS 14 and above:

webView.configuration.defaultWebpagePreferences.allowsContentJavaScript = true

iOS 13 and below:

webView.configuration.preferences.javaScriptEnabled = true
Abaddon answered 14/12, 2023 at 8:24 Comment(0)
F
2

IOS 15.5

add this

webView.configuration.defaultWebpagePreferences.allowsContentJavaScript = true
Forethoughtful answered 7/6, 2022 at 5:51 Comment(0)
B
-1

try this code :

 override func viewDidLoad() {
    super.viewDidLoad()
    configureWebView()
    currentWebView.load(requestURL)
}

private func configureWebView() {
    webView.navigationDelegate = self
    webView.uiDelegate = self
    webView.allowsBackForwardNavigationGestures = true
    /// javaScript 사용 여부
    if #available(iOS 14, *) {
        let preferences = WKWebpagePreferences()
        preferences.allowsContentJavaScript = true
        webView.configuration.defaultWebpagePreferences = preferences
    }
    else {
        webView.configuration.preferences.javaScriptEnabled = true
        /// user interaction없이 윈도우 창을 열 수 있는지 여부를 나타냄. iOS에서는 기본값이 false이다.
        webView.configuration.preferences.javaScriptCanOpenWindowsAutomatically = true
    }
}

func createNewWebView(_ config: WKWebViewConfiguration) -> WKWebView {
    /// autoLayout 되어 있는 webView와 frame을 같게 한다.
    let newWebView = WKWebView(frame: webView.frame,
                               configuration: config)
    newWebView.navigationDelegate = self
    newWebView.uiDelegate = self
    newWebView.allowsBackForwardNavigationGestures = true
    view.addSubview(newWebView)
    popupWebViews.append(newWebView)
    return newWebView
}
Brawl answered 4/4, 2022 at 20:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.