如何基于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 backtrueif the element exists,falseif it doesn't. - In the completion closure, we cast the returned
value(from JavaScript) to a SwiftBool—this is the key link between JS and your Swift variable. - We then assign that boolean to
checkElementto update its value based on the DOM check.
A couple of quick notes to avoid gotchas:
- Make sure your
webViewis 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
checkElementis 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
相关产品推荐
相关产品推荐

