简体   繁体   中英

Swift/WebKit: Updating HTML in WKWebView with Javascript

I'm using a WKWebView with a Javascript to add items to the page. A simplified version would be:

test.html:

 <!doctype> <html> <head> <script type="text/javascript"> function addLogItem() { document.getElementById("logItems").innerHTML += "New log item<br>" return document.documentElement.innerHTML.toString() } </script> </head> <body> <div id = "logItems"> Log items:<br> </div> </body> </html> 

In a ViewController, I'm calling the addLogItem function after the page has finished loading:

  func viewDidLoad() {
      webView.navigationDelegate = self
      let url = Bundle.main.url(forResource: "test", withExtension: "html")!
      webView.load(URLRequest(url: url))
  }

  func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
      webView.evaluateJavaScript("addLogItem()") { result, error in            
          print(result!)
      }
  }

The console will print the correct result, with a new "New log item
" line added:

...
<div id="logItems">
    Log items:<br>
    New log item<br>
</div>
...

The WebView in the however, still shows the original page in the application, without the "New log item" line as if the innerHTML never changed.

If I call the same Javascript function from within the of the HTML file, like below, the WebView will get updated with the new "New log item" line, suggesting that the JavaScript code works and the issue is related to the way WKWebView handles the evaluateJavaScript method.

setTimeout(addLogItem,1000);

Why doesn't webView update its contents and why doesn't it show the new line that was added by the JavaScript function?

Mystery solved. I somehow managed to have a second invisible web view in the view controller and called the javascript methods in the invisible one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM