简体   繁体   中英

How to call swift function from javascript web view

I am launching a web-view from my swift app. From the web-view I want to call a swift function on a button click. I found the code sample here .

When I press the button, nothing happens. The URL I am loading in the web-view is https://test-swift-js.github.io

Here is the code :

import Cocoa
import WebKit

class ViewController : NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    var webView:WebView!

    @IBAction func mybutton(_ sender: Any) {
        let url = URL(string: "https://test-swift-js.github.io")
        let request = URLRequest(url: url!)
        webView =  WebView(frame: NSRect(x: 0, y: 0, width: 1000, height: 1000))
        webView.mainFrame.load(request)
        self.view.addSubview(webView)
    }

    func webView(webView: WebView!, didClearWindowObject windowObject: WebScriptObject!, forFrame frame: WebFrame!) {
        windowObject.setValue(self, forKey: "interOp")
    }

    //The name used to represent the Swift function name in Javascript.
    class func webScriptNameForSelector(aSelector: Selector) -> String!
    {
        if aSelector == "callSwift:"
        {
            return "callSwift"
        }
        else
        {
            return nil
        }
    }
    class func isSelectorExcludedFromWebScript(aSelector: Selector) -> Bool
    {
        return false
    }
    func callSwift(message:String)
    {
        var alert = NSAlert()
        alert.messageText = message
        alert.alertStyle = NSAlertStyle.informational
        alert.beginSheetModal(for: self.view.window!, completionHandler: nil)
    }
}

Maybe you forget to set the delegate. 在此处输入图片说明

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