从 WKWebView 调用一个 swift 函数

Invoke a swift function from WKWebView

我正在 WKWebView 中呈现一个网页,在那个网页中,我需要用网页中的原生 swift code.Like 覆盖一个按钮操作,点击一个按钮导航到另一个页面,但在移动设备中,我需要显示故事板。我没有得到任何直接链接来实现这个。下面是我试过的代码示例:

let webConfiguration = WKWebViewConfiguration()
let userController = WKUserContentController()

    userController.add(self, name: "performClick")

    webConfiguration.userContentController = userController

    webView = WKWebView(frame: .zero, configuration: webConfiguration)

    webView.uiDelegate = self

    webView.navigationDelegate = self

    view = webView

你可以覆盖decidePolicyFor,它是WKNavigationDelegate的委托方法:

override func webView(_ webView: WKWebView, 
    decidePolicyFor navigationAction: WKNavigationAction, 
    decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    if <navigationAction is the button press> {
        decisionHandler(.cancel)
         // go to the new storyboard
    } else {
        decisionHandler(.allow)
    }
}

要判断navigationAction是否是按键按下,可以查看其request属性,即URLRequest。您应该知道 URLRequest 按钮发送的内容。

您遗漏了某些部分,要从网页中收听消息,您还需要对网页进行一些更改。下面是从网页上监听一些动作的步骤,我的代码片段在objective c,你可以翻译成swift

  1. 使用 addScriptMessageHandler 函数添加您的脚本消息,它需要参数 WKScriptMessageHandler 和消息名称,测试使用消息名称,如“test”

  2. 实施didReceiveScriptMessage委托。

    - (void)didReceiveScriptMessage:(WKScriptMessage*)message {
         if ([message.name isEqualToString: @"test"]) {
            //Do here whatever you want.
         }
    }
    
  3. 只要按下该按钮,就会在您的服务器页面上调用此行。

webkit.messageHandlers.test

经过大量的搜索,我终于找到了答案。如果这对某人有帮助,请发布。

var webView: WKWebView?
var webConfig:WKWebViewConfiguration {
    get {

        let webCfg:WKWebViewConfiguration = WKWebViewConfiguration()
        let userController:WKUserContentController = WKUserContentController()
        userController.add(self, name: "submit")
        let js:String = buttonClickEventTriggered()
        let userScript:WKUserScript =  WKUserScript(source: js, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: false)
        userController.addUserScript(userScript)
        webCfg.userContentController = userController;
        return webCfg;
    }
}
  override func viewDidLoad() {
    super.viewDidLoad()
    self.webView = WKWebView(frame: self.view.frame, configuration: webConfig)
    self.webView!.navigationDelegate = self
    self.view = webView!
    let url = URL(string:"your URL here")
    let req = NSURLRequest(url:url! as URL)
    self.webView!.load(req as URLRequest)
 }
func buttonClickEventTriggered() ->String{
    
    let script:String = "document.getElementById('your button id here').addEventListener('click', function () {window.webkit.messageHandlers.submit.postMessage('submited');});"//Make sure you have mapped the name correctly under userController.add
    return script;
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    print("Sucessss")
    if(message.name == "submit") {
        print("It does ! \(message.body)")
        // Your code goes here
    }
}