LoginSignup
13
11

More than 5 years have passed since last update.

WebView内のJavaScript から Swiftの関数を呼ぶ

Posted at

JavaScript から Swiftの関数を呼ぶ

Cocoa WebViewの話です。
iOSの話じゃないと思います。

ViewController.swift

import Cocoa
import WebKit

class ViewController: NSViewController {

     // cocoa WebViewをアウトレットしておく
    @IBOutlet weak var toWeb: WebView!

     // 同じパスにあるindex.htmlをロード
    var targetURL = NSBundle.mainBundle().pathForResource("index", ofType: "html");

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = NSURL(string: targetURL!)
        let request = NSURLRequest(URL: url!)
        self.toWeb.mainFrame.loadRequest(request)

        var win = toWeb.windowScriptObject
        win.setValue(self, forKey: "ViewController")
    }

    // Sample function with multiple parameters
    func multiplyTwoFloat(x: Float, y: Float) -> Float {
        return x * y
    }

    // Sample function with single parameters
    func printFloat(f: Float) -> Void{
        print("\(f)")
    }

    // JSからアクセス可能にする関数を定義する
    override class func isSelectorExcludedFromWebScript(aSelector: Selector) -> Bool {
        switch aSelector {
        case Selector("multiplyTwoFloat:y:"):
            return false
        case Selector("printFloat:"):
            return false
        default:
            return true
        }
    }
}

index.html

<!DOCTYPE html>
<html>
<body>
<script>
    var swift = window.ViewController;
    var num = swift.multiplyTwoFloat_y_(2,2);
    swift.printFloat_(num); // -> 4.0 とログに表示される
</script>
</body>
</html>
13
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
11