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

如何基于JavaScript变量修改Swift变量?(JS变量传递至Swift)

Solution

Got it, let's get this working for you! The core issue with your current code is that you're only running JavaScript to fetch the element, but not sending back a result that Swift can use to update your checkElement variable. Here's how to fix it:

var checkElement = false

webView.evaluateJavaScript("document.getElementById('element') !== null") { (value, error) in
    if let err = error {
        print("JS evaluation error: \(err)")
        return
    }
    
    // Safely convert the JS result to a Swift boolean and update our variable
    if let elementExists = value as? Bool {
        checkElement = elementExists
        // Optional: Log or act on the updated value right away
        print("Element exists? \(checkElement)")
    }
}

Quick breakdown of what's changed:

  • Instead of just grabbing the element in JS, we directly return a boolean check: "document.getElementById('element') !== null" will send back true if the element exists, false if it doesn't.
  • In the completion closure, we cast the returned value (from JavaScript) to a Swift Bool—this is the key link between JS and your Swift variable.
  • We then assign that boolean to checkElement to update its value based on the DOM check.

A couple of quick notes to avoid gotchas:

  • Make sure your webView is fully loaded (the page has finished rendering) before calling this, otherwise the element might not exist yet even if it's in the HTML.
  • If checkElement is a property on a class, add [weak self] to the closure to prevent retain cycles:
webView.evaluateJavaScript("document.getElementById('element') !== null") { [weak self] (value, error) in
    guard let self = self else { return }
    // ... rest of the code ...
    self.checkElement = elementExists
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 10:01:28