Swift中如何在WKWebView内点击特定文本执行自定义操作
Got it, let's walk through how to make those text clicks trigger your custom native code in WKWebView. Here's a step-by-step solution tailored to your setup:
1. Update Your HTML String with Clickable Elements
First, we need to turn "here" and "there" into interactive elements that can send signals to your native code. We'll wrap them in <span> tags (you could also use <a> if preferred) with an onclick handler that calls a tiny JavaScript function. We'll add basic styling too, so users can tell they're clickable:
let htmlString = """ Click <span style="color: #007AFF; cursor: pointer;" onclick="sendAction('here')">here</span> or <span style="color: #007AFF; cursor: pointer;" onclick="sendAction('there')">there</span> for different actions <script> function sendAction(action) { // Send the action identifier to native code window.webkit.messageHandlers.actionHandler.postMessage(action); } </script> """ webkit.loadHTMLString(htmlString, baseURL: nil)
2. Configure WKWebView to Listen for JavaScript Messages
Your ViewController needs to conform to the WKScriptMessageHandler protocol to receive messages from the web view. We'll add a message handler to the web view's user content controller so it can pick up messages labeled "actionHandler".
Add this to your viewDidLoad() method:
override func viewDidLoad() { super.viewDidLoad() // Register the message handler to listen for "actionHandler" signals webkit.configuration.userContentController.add(self, name: "actionHandler") // Load your updated HTML string let htmlString = """ Click <span style="color: #007AFF; cursor: pointer;" onclick="sendAction('here')">here</span> or <span style="color: #007AFF; cursor: pointer;" onclick="sendAction('there')">there</span> for different actions <script> function sendAction(action) { window.webkit.messageHandlers.actionHandler.postMessage(action); } </script> """ webkit.loadHTMLString(htmlString, baseURL: nil) }
3. Handle Messages & Run Custom Native Code
Implement the WKScriptMessageHandler method to catch incoming messages and execute your code based on which text was clicked. Add this extension to your ViewController:
extension ViewController: WKScriptMessageHandler { func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { // Ensure the message body is a usable string guard let action = message.body as? String else { return } // Run your custom logic based on the action switch action { case "here": // Replace this with your code for "here" clicks print("User clicked 'here' — running custom action!") let alert = UIAlertController(title: "Action Triggered", message: "You clicked 'here'", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default)) present(alert, animated: true) case "there": // Replace this with your code for "there" clicks print("User clicked 'there' — running another action!") let alert = UIAlertController(title: "Action Triggered", message: "You clicked 'there'", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default)) present(alert, animated: true) default: // Handle unexpected actions if needed break } } }
4. Clean Up to Prevent Memory Leaks
Don't forget to remove the message handler when your ViewController is deinitialized to avoid memory leaks:
deinit { webkit.configuration.userContentController.removeScriptMessageHandler(forName: "actionHandler") }
How This Works
- The JavaScript function
sendAction()sends a string identifier ("here" or "there") to your native code usingwindow.webkit.messageHandlers. - Your WKWebView is set up to listen for messages tagged "actionHandler".
- When a message arrives, the
userContentController(_:didReceive:)method checks the message content and runs the corresponding native code.
内容的提问来源于stack exchange,提问作者Adam S.

