0

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?

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

Comments

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.