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

WKWebView注入JS处理关闭按钮仅初始页生效,页面导航后失效求助

问题:注入的JavaScript关闭按钮逻辑仅在初始页面生效,页面导航后失效

我需要注入JavaScript处理网页中的关闭按钮,但该逻辑仅在初始页面生效。当导航至网站内其他页面后,逻辑失效;即使返回初始页面,也无法正常工作。

以下是我的具体操作:

1. 配置WebView

let preferences = WKPreferences()
preferences.javaScriptEnabled = true

let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
let userContentController = WKUserContentController()

let source = """
    if (document.getElementById('closeWebApp')) {
        document.getElementById('closeWebApp').addEventListener('click', function() { window.webkit.messageHandlers.ios.postMessage('closeWebApp'); });
    }
"""
let script = WKUserScript(source: source, injectionTime: .atDocumentStart, forMainFrameOnly: false)

userContentController.addUserScript(script)
userContentController.add(self, name: "ios")

configuration.userContentController = userContentController

webView = WKWebView(frame: view.bounds, configuration: configuration)
webView.navigationDelegate = self

2. 加载网站

if let url = URL(string: "https://example.com/new") {
    webView.load(URLRequest(url: url))
}

3. 在代理方法中处理closeWebApp元素的点击事件

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webView.evaluateJavaScript("""
    
    document.getElementById('closeWebApp').addEventListener('click', function() {
                window.webkit.messageHandlers.ios.postMessage('Close button clicked');
            });
    """)
}

4. 在didStartProvisionalNavigation中添加逻辑

func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    webView.evaluateJavaScript("""
        if (document.getElementById('closeWebApp')) {
            document.getElementById('closeWebApp').addEventListener('click', function() { window.webkit.messageHandlers.ios.postMessage('closeWebApp'); });
        }
    """) { (result, error) in
        if let error = error {
            print("JavaScript evaluation error: \(error.localizedDescription)")
        } else {
            print("JS evaluated successfull")
        }
    }
}

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    if navigationAction.navigationType == .backForward {
        onBackPassed = true
    }
    decisionHandler(.allow)
}

5. 处理消息回调

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    
    guard let buttonId = message.name as? String else {
        return
    }
    
    if buttonId == "ios" {
        onBackPassed = true
        DispatchQueue.main.async {
            self.onBackPressed()
        }
    }
}

内容的提问来源于stack exchange,提问作者Farrukh Makhmudov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 04:32:13