1

I need my swift class to interact with the html and javascript in a wkwebview that it references, in particular, feed it a variable.

I thought I would start simply by trying to get the webview to fire an alert:

Here is the code:

let webView = WKWebView()

    override func viewDidLoad() {
      
        super.viewDidLoad()
         webView.uiDelegate = self
        webView.navigationDelegate = self as? WKNavigationDelegate
        if let url = Bundle.main.url(forResource: "tradingview", withExtension: "html") {
            webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
           
        }
       // Try one way in viewdidload. Compiles but doesn't do anything
         webView.evaluateJavaScript("alert('hello from the webview');");
    }
   
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
//try another way. Also doesn't do anything
        webView.evaluateJavaScript("alert('hello from webview')"), completionHandler: nil)
    }
    override func loadView() {
        
        self.view = webView
    }

However, the webview is not firing an alert. What is wrong with the code or is there anything else you need to do to get Swift to run some javascript on a webview.

Thanks for any suggestions.

user6631314
  • 1,751
  • 1
  • 13
  • 44

1 Answers1

2

You need to convert info in javascript alert into native UIAlert.

Add alert handler delegate described in WKUIDelegate.

func webView(_ webView: WKWebView,
             runJavaScriptAlertPanelWithMessage message: String,
             initiatedByFrame frame: WKFrameInfo,
             completionHandler: @escaping () -> Void) {

    let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
    let title = NSLocalizedString("OK", comment: "OK Button")
    let ok = UIAlertAction(title: title, style: .default) { (action: UIAlertAction) -> Void in
        alert.dismiss(animated: true, completion: nil)
    }
    alert.addAction(ok)
    present(alert, animated: true)
    completionHandler()
}

And call like below (there is a type in your code);

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webView.evaluateJavaScript("alert('hello from the webview')")
}

enter image description here


In Addition

There is a sample project that simulates two way communication between native and web in both way.

Omer Faruk Ozturk
  • 1,722
  • 13
  • 25
  • OK. You have answered the question so going to mark it correct. I didn't know about that delegate method. But my real goal is to pass a variable to webview from Swift and run a script on the webview. Can you suggest how to do that? – user6631314 Jul 18 '20 at 14:58
  • The issue you asked is about showing an alert. So, first of all, if the answer is worked for you as you state, please don't forget to mark as *accepted*. This [post](https://medium.com/@JillevdWeerd/creating-links-between-wkwebview-and-native-code-8e998889b503) may help you to build communication between webview and native. – Omer Faruk Ozturk Jul 18 '20 at 15:17
  • Could not get example in link to work. Can you provide a simple example of calling evaluateJavaScript() from swift to run javascript in webview? I can ask separate question if you would like – user6631314 Jul 18 '20 at 16:37
  • There is a sample [project](https://github.com/omerfarukozturk/SampleHybridApp) that simulates two way communication in both way. – Omer Faruk Ozturk Jul 18 '20 at 21:07