在iOS中使用WWebView检测Javascript方法

问题描述

我正在尝试实现WKWebView来检测我的应用程序中的javascript事件,并基于该事件在应用程序内部执行下一步操作。

所以我有以下html页面:

    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html charset=UTF-8" />
        <!-- <meta name="viewport" content="width=device-width,initial-scale=1.0"> -->
        <title></title>

    </head>

    <body style="background-color: #f8f8f8;font-family: 'Helvetica';margin: 0; overflow: auto;  float: left; width: 100%">

        <div style="max-width:500px;display: block;margin: 30px auto;width: 100%;  padding: 60px 40px; color: #76838f;  font-size: 14px; background-color: #000;border-radius: 6px; ">
            
            <!-- title -->
            <div style="font-size: 24px;font-weight: 600;color: #9d1f2b; text-align: left;font-weight: bold;display: table;border-bottom: 2px solid rgb(255 255 255 / 34%);margin-bottom: 10px;padding-bottom: 20px;width: 100%;">
                <span style="display: table-cell;    vertical-align: middle;font-size: 28px;">Card Successfully Added</span>
            </div>
            <!-- title End-->


            <!-- content-->

            <div style="margin-bottom: 40px;margin-top: 40px;border-bottom: 1px solid #ccc;padding-bottom: 20px;">
                {{-- <p style="color: #eee;line-height: 23px;font-size: 18px;margin-bottom: 0">
                    Payment Token
                </p>
                <h5 style="color: #fff;font-size: 18px;margin-top: 8px">XYZ</h5> --}}
                <p style="color: #eee;line-height: 23px;font-size: 18px;">
                    Card Number
                </p>
                <h5 style="color: #fff;font-size: 18px;margin-top: 8px">123</h5>
                {{-- <p style="color: #eee;line-height: 23px;font-size: 18px;margin-bottom: 0">
                    Reference
                </p>
                <h5 style="color: #fff;font-size: 18px;margin-top: 8px">00000000003</h5> --}}

            </div>

            <!-- content End-->
            <form method="post" name="refer_now_form">
                <div class="refer-now-button" style="cursor: pointer">
                    <a href="{{route('create.successfull')}}" onclick="refer_now.performClick();" id="refernow" style="background: #9d1f2b;color: #fff;display: block;text-align: center;font-weight: bold;text-transform: uppercase;text-decoration: none;height: 50px;line-height: 50px;font-size: 18px;">Back To App</a>
                </div>
            </form>

        </div> <!-- end -->

    </body>
    <script>
        $(document).ready(function() {

        function performClick() {
                try {
                    webkit.messageHandlers.callbackHandler.postMessage("Card Successfully Added");
                } catch (err) {
                    console.log('Card failed');
                }
            }
        });

    </script>
    </html>

我也在使用解决方案来从此处检测javascript事件: How do I use jQuery for click event in iPhone web application ,但这对我不起作用。

这是我已实现的iOS代码。

import UIKit
import WebKit

class ViewController: UIViewController,WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate {
   
    var webView: WKWebView!
    
    var webConfig:WKWebViewConfiguration {
        
        get {
            
            // Create WKWebViewConfiguration instance
            let webCfg:WKWebViewConfiguration = WKWebViewConfiguration()
            
            // Setup WKUserContentController instance for injecting user script
            let userController:WKUserContentController = WKUserContentController()
            
            // Add a script message handler for receiving  "buttonClicked" event notifications posted from the JS document using window.webkit.messageHandlers.buttonClicked.postMessage script message
            userController.add(self,name: "callbackHandler")
            
            if let filePath = Bundle.main.path(forResource: "Test",ofType: "html") {
                let script = String(format: filePath,locale: Locale.current)
                let userScript =  WKUserScript(source: script,injectionTime: .atDocumentEnd,forMainFrameOnly: false)
                userController.addUserScript(userScript)
            }
            
            // Configure the WKWebViewConfiguration instance with the WKUserContentController
            webCfg.userContentController = userController;
            
            return webCfg;
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Create a WKWebView instance
        webView = WKWebView (frame: self.view.frame,configuration: webConfig)
        
        // Delegate to handle navigation of web content
        webView.navigationDelegate = self
        webView.frame = self.view.frame
        webView.uiDelegate = self
        
        if #available(iOS 10.0,*) {
            webView.configuration.dataDetectorTypes = .all
        }
        view.addSubview(webView)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        loadBundlHtml()
    }
    
    // File Loading
    func loadBundlHtml() {
        guard let fileUrl = Bundle.main.url(forResource: "Test",withExtension: "html") else { return }
        webView.loadFileURL(fileUrl,allowingReadAccessTo: fileUrl)
    }
    
    // WKNavigationDelegate
    private func webView(webView: WKWebView,didFinishNavigation navigation: WKNavigation!) {
        NSLog("%s",#function)
    }
    
    private func webView(webView: WKWebView,didFailNavigation navigation: WKNavigation!,withError error: NSError) {
        NSLog("%s. With Error %@",#function,error)
    }
    
    // WKScriptMessageHandler Delegate
    func userContentController(_ userContentController: WKUserContentController,didReceive message: WKScriptMessage) {
        if let messageBody = message.body as? [String: Any] {
            print(messageBody)
        }
    }
}

请帮助我解决此问题。

解决方法

尝试使用此代码将值发布到WKWeb视图

function performClick() {
     try {
           var messageBody = {type: "ClickType",value: "performClick"}
           window.webkit.messageHandlers.ports.postMessage(messageBody);
          } catch (err) {
           console.log('Card failed');
          }
    }
}

快捷代码

WKWebview设置以下设置

webView.configuration.userContentController.add(self,name: "ports")

要接收端口消息,请使用以下委托方法

public func userContentController(_ userContentController: WKUserContentController,didReceive message: WKScriptMessage) {
        guard message.name == "ports" else{
            return
        }
        if let body = message.body as? NSDictionary {
            if let messageType = body["type"] as? String,messageType == "ClickType"{
                if let messages = body["value"] as? String {
                    print("messages : ",messages)
                }
            }
        }
    }

ClickType是类型,值是您要发送的消息

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...