javascript - 在 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');
}
}
}
SWIFT代码
设置以下设置为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
是类型,值是您要发送的消息
推荐阅读
- r - 由于无法定位数据框,无法在 Shinyapps.io 中部署本地运行的闪亮应用
- python - 如何在 Python 应用程序中订阅 Salesforce 平台事件?
- spring-boot - spring data couchbase 不会抛出 OptimisticLockingFailureException
- javascript - 如何制作背景模糊的弹出窗口
- category-theory - 等价关系对组,正如偏序关系对...?
- powershell - 使用计算机名将正在运行的服务输出到 csv
- javascript - 带有单击和锚标记的 div 会同时运行两次单击,而不是仅在单击时运行锚点
- swift - swift xcode iOS:我可以重复使用加载的模态全屏视图控制器吗?
- ios - 如何在 Swift 中创建内容大小的弹出框
- azure-devops-rest-api - 如何通过 AzureDevOps REST API 获取给定包名称的包 ID