title: Swift/WebKit: Updating HTML in WKWebView with Javascript
body: <p>I'm using a WKWebView with a Javascript to add items to the page. A simplified version would be:</p>
  
  <p>test.html:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!doctype&gt;
  &lt;html&gt;
      &lt;head&gt;
          &lt;script type="text/javascript"&gt;
              function addLogItem() {                
                  document.getElementById("logItems").innerHTML += "New log item&lt;br&gt;"                   
                  return document.documentElement.innerHTML.toString()
              }
          &lt;/script&gt;
      &lt;/head&gt;
      &lt;body&gt;
          &lt;div id = "logItems"&gt;
          Log items:&lt;br&gt;
          &lt;/div&gt;
      &lt;/body&gt;
  &lt;/html&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>In a ViewController, I'm calling the addLogItem function after the page has finished loading:</p>
  
  <pre><code>  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!)
        }
    }
  </code></pre>
  
  <p>The console will print the correct result, with a new "New log item<br>" line added:</p>
  
  <pre><code>...
  &lt;div id="logItems"&gt;
      Log items:&lt;br&gt;
      New log item&lt;br&gt;
  &lt;/div&gt;
  ...
  </code></pre>
  
  <p>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.</p>
  
  <p>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. </p>
  
  <pre><code>setTimeout(addLogItem,1000);
  </code></pre>
  
  <p>Why doesn't webView update its contents and why doesn't it show the new line that was added by the JavaScript function?</p>