Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active April 10, 2019 03:24
Show Gist options
  • Save KentarouKanno/75ae10ed6f0d581cf455506a36977702 to your computer and use it in GitHub Desktop.
Save KentarouKanno/75ae10ed6f0d581cf455506a36977702 to your computer and use it in GitHub Desktop.
import UIKit
import WebKit

final class ViewController: UIViewController {
    
    @IBOutlet weak var webView: WKWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let userController = webView.configuration.userContentController
        for handlerName in ["callbackHandler1", "callbackHandler2", "callbackHandler3"] {
            userController.add(self, name: handlerName)
        }
        
        let path: String = Bundle.main.path(forResource: "index", ofType: "html")!
        let localHtmlUrl: URL = URL(fileURLWithPath: path, isDirectory: false)
        webView.loadFileURL(localHtmlUrl, allowingReadAccessTo: localHtmlUrl)
    }

    @IBAction func button1(_ sender: Any) {
        // Javascriptに渡す値
        let param: String = "jsCallTest1"
        // Javascript側で実行する関数
        let execJsFunc: String = "test1(\"\(param)\");"
        webView.evaluateJavaScript(execJsFunc, completionHandler: { (object, error) -> Void in
            // jsの関数実行結果
        })
    }
    
    @IBAction func button2(_ sender: Any) {
        let param: String = "jsCallTest2"
        let execJsFunc: String = "test2(\"\(param)\");"
        webView.evaluateJavaScript(execJsFunc, completionHandler: { (object, error) -> Void in })
    }
    
    @IBAction func button3(_ sender: Any) {
        let param: String = "jsCallTest3"
        let execJsFunc: String = "test3(\"\(param)\");"
        webView.evaluateJavaScript(execJsFunc, completionHandler: { (object, error) -> Void in })
    }
}

extension ViewController: WKScriptMessageHandler {
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if(message.name == "callbackHandler1") {
            print("callbackHandler1 - \(message.body)")
        }
        
        if(message.name == "callbackHandler2") {
            print("callbackHandler2 - \(message.body)")
        }
        
        if(message.name == "callbackHandler3") {
            print("callbackHandler3 - \(message.body)")
        }
    }
}
  • HTML(index.html)
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <link rel="stylesheet" type="text/css" href="style.css">
        <title>ページタイトル</title>
    </head>
    <body>
        <h1 id="title">タイトル</h1>
        
        <script type="text/javascript" src="js.js"></script>
    </body>
</html>
  • css(style.css)
#title {
    color: orange
}
  • Javascript(js.js)
function test1(val) {
    
    var h1 = document.getElementById("title");
    h1.textContent = val;
    
    webkit.messageHandlers.callbackHandler1.postMessage(val);
}

function test2(val) {
    
    var h1 = document.getElementById("title");
    h1.textContent = val;
    
    webkit.messageHandlers.callbackHandler2.postMessage(val);
}

function test3(val) {
    
    var h1 = document.getElementById("title");
    h1.textContent = val;
    
    webkit.messageHandlers.callbackHandler3.postMessage(val);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment