OYPS
OYPS

Reputation: 81

Swift and Javascript Integration

i was following along this article about integrating Swift (WKWebView) and Javascript. Everything from the article works fine but i am trying to pass some variable from Swift to Javascript.

This is my ViewController in Swift:

import UIKit
import WebKit

class ViewController: UIViewController, WKScriptMessageHandler {

    @IBOutlet var containerView : UIView! = nil
    var webView: WKWebView?

    override func loadView() {
        super.loadView()

        let contentController = WKUserContentController();
        let userScript = WKUserScript(
            source: "redHeader()",
            injectionTime: WKUserScriptInjectionTime.AtDocumentEnd,
            forMainFrameOnly: true
        )
        contentController.addUserScript(userScript)
        contentController.addScriptMessageHandler(
            self,
            name: "callbackHandler"
        )

        let config = WKWebViewConfiguration()
        config.userContentController = contentController

        self.webView = WKWebView(
            frame: self.view.frame,
            configuration: config
        )
        self.view = self.webView!
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = NSURL(string:"https://example.com")
        let req = NSURLRequest(URL:url!)
        self.webView!.loadRequest(req)

        let simpleInt = 123

        self.webView?.evaluateJavaScript("redHeader(\(simpleInt)", completionHandler: nil);
    }

    func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
        if(message.name == "callbackHandler") {
            print("JavaScript is sending a message \(message.body)")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

and thats the HTML and JS residing on an server:

function callNativeApp () {
    try {
        webkit.messageHandlers.callbackHandler.postMessage("Hello from JavaScript");
    } catch(err) {
        console.log('The native context does not exist yet');
    }
}

setTimeout(function () {
    callNativeApp();
}, 50000);

function redHeader(int) {
	console.log(int);
}
<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">
            body {
                padding-top: 40px; 
            }
        </style>
        <title>WKWebView Demo</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <h1>WKWebView Test</h1>
        <script type="text/javascript" src="main.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    </body>
</html>

It's still just the code from the above article but i am not able to pass the variable simpleInt to the JS.

Despite that the Javascript call

webkit.messageHandlers.callbackHandler.postMessage("Hello from JavaScript");

does not work as well.

I think I am passing the variable wrong. Any suggestions?

Upvotes: 0

Views: 1206

Answers (1)

Sachin
Sachin

Reputation: 105

There are a few things you can try out

  1. window is missing from your method call

    webkit.messageHandlers.callbackHandler.postMessage("Hello from JavaScript");
    

    should be

    window.webkit.messageHandlers.callbackHandler.postMessage("Hello from JavaScript");

  2. Check if you are able to access message handler from browser open debug menu for this Check for enabling debug mode

    window.webkit.messageHandlers.callbackHandler

Result

  1. One more issue might be using timeout with native call. Remove timeout and add a button to call messageHandler.

Upvotes: 1

Related Questions