Calling Swift function from JavaScript and JS function from Swift

When we develop a web app for iOS devices, we need to know how to call JavaScript function from Swift and also how to call Swift function from JavaScript.

Here let me bring you full codes for ViewController.swift and the html file that I loaded it locally.


//  ViewController.swift
//  Kitten Faces
//  Created by Macbook Pro on 12/22/17.
//  Copyright © 2017 Zofia Kreasi. All rights reserved.

import UIKit

class ViewController: UIViewController, UIWebViewDelegate {

    @IBOutlet weak var webView: UIWebView!
    @IBOutlet weak var button: UIButton!
    override func viewDidLoad() {
        // Do any additional setup after loading the view, typically from a nib.
        self.webView.delegate = self
    func loadHTMLFromBundle(){
        let url = Bundle.main.url(forResource: "index", withExtension: "html")
        let urlRequest:URLRequest = URLRequest(url:url!)

    override func didReceiveMemoryWarning() {
        // Dispose of any resources that can be recreated.

    @IBAction func changeP(_ sender: Any) {
        self.webView.stringByEvaluatingJavaScript(from: "changeP()")
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if request.url?.scheme == "wakwak" {
            self.webView.stringByEvaluatingJavaScript(from: "changeP()")
        return true


And here is the html file

<!DOCTYPE html>
            function changeP(){
                document.getElementById("p").innerHTML = "Josss pak!"
        function sendmsg(){
            window.location = "wakwak://kukkuukukuku";
        <p id="p">Halo bibol!</p>
        <button onclick="sendmsg()">Change</P>

URL Schemes

Another thing that you must configure is URL Schemes. Look what I’ve set here:


Leave a Reply

Your email address will not be published. Required fields are marked *