lynn
lynn

Reputation: 65

How to pass data from swift to javascript?

I know how to pass data from javascript to swift, but don't know how to pass data from swift to javascript.

The method i use to pass data from javascript to swift is below:

<head>

    <title>Test</title>
    <meta charset="UTF-8">
</head>
<body>
    <h1>WebView Test 3</h1>
    <script>
        function callNativeApp () {
            try {
                webkit.messageHandlers.callbackHandler.postMessage("Here");
            } catch(err) {
                console.log('The native context does not exist yet');
            }
        }
    callNativeApp();
        </script>
</body>

import UIKit

import WebKit

class ThirdViewController: UIViewController,WKScriptMessageHandler{


    override func viewDidLoad() {

        super.viewDidLoad()

        let configuration=WKWebViewConfiguration()

        let controller=WKUserContentController()


        controller.addScriptMessageHandler(self, name: "callbackHandler")


        configuration.userContentController=controller

        let webView=WKWebView(frame: self.view.frame, configuration: configuration)

        let url=NSBundle.mainBundle().URLForResource("test3", withExtension: "html")

        let request=NSURLRequest(URL: url!)

        self.view=webView

        webView.loadRequest(request)
    }

    func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {

        if(message.name == "callbackHandler"){
            print("callbackHandler: \(message.body)")
        }



    }


}

Upvotes: 3

Views: 8021

Answers (2)

Scriptable
Scriptable

Reputation: 19750

As you know, you pass information to Swift by calling postMessage.

To pass information to the browser from Swift you just call evaluateJavascript like so:

let num1 = 4
let num2 = 8

webView.evaluateJavaScript("addTwoNumbers(\(num1), \(num2);")  { (result, error) in
                guard error == nil else {
                    print("there was an error")
                    return
                }

                print(Int(result))
            }

For this particular code to do anything you would need a addTwoNumbers function in the Javascript that handled the function and done something.

Upvotes: 5

Mudith Chathuranga Silva
Mudith Chathuranga Silva

Reputation: 7434

As an example I'll take a JS function like this :-

      function send_message(val01, val02) {
           // you JS CODE
      }

Then to run the function you should call :-

 self.webView.stringByEvaluatingJavaScriptFromString("send_message(\"\(self.value1)\", \"\(self.value2)\")")!

Upvotes: 0

Related Questions