3

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)")
        }



    }


}

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

have you had issues passing a JSON string as a parameter? evaluteJavaScript breaks when a JSON string is passed as a parameter. would appreciate your thoughts if you get a sec: stackoverflow.com/questions/40292348/…
This will create an error like "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=SyntaxError: Unexpected token ';'. Expected ')' to end an argument list.," it should be like webView.evaluateJavaScript("addTwoNumbers((num1), (num2))")
This worked when I tested it. why would each parameter need brackets around it and javascript uses semicolons to end its lines, so not sure why that would throw an error
0

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

1 Comment

have you had issues passing a JSON string as a parameter? evaluteJavaScript breaks when a JSON string is passed as a parameter. would appreciate your thoughts if you get a sec: stackoverflow.com/questions/40292348/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.