You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何在WKWebView内点击特定文本执行自定义操作

Solution for Triggering Native Code on Text Clicks in 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 using window.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.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:25:29