简体   繁体   中英

Call javascript function from swift 3

how can I call this below method from swift to Javascript

function downloadComplete(status,filename){
        alert ("Send Status and file name "+status +" "+filename);
       $('#status').val (status);
       $('#filename').val(filename);
    }

I'm able to send data by

    self.webView?.stringByEvaluatingJavaScriptFromString
when we get data from Javascript by func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if(message.name == "iMessageNameClicked") {
            print(message)
            debugPrint(message)
            print("iMessageBodyClicked: \(message.body)")
            }
}

Please let me know how to deal it?

Thanks in advance

As per my Knowledge we can achieve javascript calls from swift by following steps. Step1: Declare two variable on OnloadFunction of HTML File like bellow exemple.

var status = %@;
var filename = %@;

Step1: On Swift class get your html content as a string and set your valu by following code:

let localfilePath = Bundle.main.url(forResource: "index", withExtension: "html")
    do {
        var myHTMLString = try NSString(contentsOf: localfilePath!, encoding: String.Encoding.utf8.rawValue)
        myHTMLString = NSString(format: myHTMLString, "'\(**YOURVALUE!**)'" , "'\(**YOURVALUE!**)'") 
        webView.loadHTMLString(myHTMLString as String, baseURL: Bundle.main.url(forResource: "ads", withExtension: "js")) //Add your js file here
    }
    catch let error as NSError
    {
        print("Error: \(error.description)")
    }

Hope this will help you.if any let me know.Thanks

I am using like this in WKWebView

 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {


      let   str = "$('body').attr('data-uid','\(String(uid))');$('body').attr('data-pid','\(String(memberTypeId))');$('body').attr('data-baseurl','\(DataProvider.sharedInstance.baseUrl)');"


        self.webView.evaluateJavaScript(str) { (id, error) in
            print(error)
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM