How to inject JavaScript callback to detect onclick event, using iOS WKWebView?

前端 未结 4 1561
灰色年华
灰色年华 2021-02-01 06:14

I\'m using a WKWebView to show a website which has some HTML that includes three buttons. I want to run some Swift code in the native app when a specific button is

4条回答
  •  情话喂你
    2021-02-01 06:39

    User Scripts are JS that you inject into your web page at either the start of the document load or after the document is done loading. User scripts are extremely powerful because they allow client-side customization of web page, allow injection of event listeners and can even be used to inject scripts that can in turn call back into the Native app. The following code snippet creates a user script that is injected at end of document load. The user script is added to the WKUserContentController instance that is a property on the WKWebViewConfiguration object.

    // Create WKWebViewConfiguration instance
      var webCfg:WKWebViewConfiguration = WKWebViewConfiguration()
    
      // Setup WKUserContentController instance for injecting user script
      var userController:WKUserContentController = WKUserContentController()
    
      // Get script that's to be injected into the document
      let js:String = buttonClickEventTriggeredScriptToAddToDocument()
    
      // Specify when and where and what user script needs to be injected into the web document
      var userScript:WKUserScript =  WKUserScript(source: js, 
                                             injectionTime: WKUserScriptInjectionTime.atDocumentEnd,
                                             forMainFrameOnly: false)
    
      // Add the user script to the WKUserContentController instance
      userController.addUserScript(userScript)
    
      // Configure the WKWebViewConfiguration instance with the WKUserContentController
      webCfg.userContentController = userController;
    

    Your web page can post messages to your native app via the window.webkit.messageHandlers..postMessage () method. Here, “name” is the name of the message being posted back. The JS can post back any JS object as message body and the JS object would be automatically mapped to corresponding Swift native object. The following JS code snippet posts back a message when a button click event occurs on a button with Id “ClickMeButton”.

    var button = document.getElementById("clickMeButton");
    button.addEventListener("click", function() {
                varmessageToPost = {'ButtonId':'clickMeButton'};
                window.webkit.messageHandlers.buttonClicked.postMessage(messageToPost);
            },false);
    

    In order to receive messages posted by your web page, your native app needs to implement the WKScriptMessageHandler protocol. The protocol defines a single required method. The WKScriptMessage instance returned in the callback can be queried for details on the message being posted back.

    func userContentController(userContentController: WKUserContentController,
                               didReceiveScriptMessage message: WKScriptMessage) {
    
            if let messageBody:NSDictionary= message.body as? NSDictionary{
                // Do stuff with messageBody
            }
    
        }
    

    Finally, the native class that implements WKScriptMessageHandler protocol needs to register itself as a message handler with the WKWebView as follows:

    // Add a script message handler for receiving  "buttonClicked" event notifications posted 
    // from the JS document
    userController.addScriptMessageHandler(self, name: "buttonClicked")
    

提交回复
热议问题