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



    }


}
Scriptable
  • 19,402
  • 5
  • 56
  • 72
lynn
  • 65
  • 1
  • 6

2 Answers2

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.

Scriptable
  • 19,402
  • 5
  • 56
  • 72
  • 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: http://stackoverflow.com/questions/40292348/ios-evaluatejavascript-invokes-function-when-normal-string-passed-as-parameter – Crashalot Oct 27 '16 at 19:21
  • 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))") – Ruchira More Aug 19 '19 at 08:36
  • 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 – Scriptable Aug 19 '19 at 08:45
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)\")")!
Mudith Chathuranga Silva
  • 7,253
  • 2
  • 50
  • 58
  • 1
    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: http://stackoverflow.com/questions/40292348/ios-evaluatejavascript-invokes-function-when-normal-string-passed-as-parameter – Crashalot Oct 27 '16 at 19:21