简体   繁体   English

Swift / WebKit:使用Javascript更新WKWebView中的HTML

[英]Swift/WebKit: Updating HTML in WKWebView with Javascript

I'm using a WKWebView with a Javascript to add items to the page. 我正在使用带有Javascript的WKWebView将项目添加到页面。 A simplified version would be: 简化版本为:

test.html: 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: 在ViewController中,页面加载完成后,我正在调用addLogItem函数:

  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. 但是,WebView仍显示应用程序中的原始页面,没有“ New log item”行,好像innerHTML从未更改。

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. 如果我从HTML文件的内调用相同的Javascript函数(如下所示),则WebView将使用新的“新日志项”行进行更新,这表明JavaScript代码有效,并且问题与WKWebView处理代码的方式有关EvaluationJavaScript方法。

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? 为什么webView不更新其内容,为什么不显示JavaScript函数添加的新行?

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. 我设法在视图控制器中有了第二个不可见的Web视图,并在不可见的视图中调用了javascript方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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