Search code examples
iosobjective-cuiwebviewwkwebview

How WKWebView runs JS to control window.scrollTo(x,y) when loading document


When I use WKWebView, I hope that ONLoad can load JS. In the previous UIwebView, this method is possible. Now I must monitor whether the HTML is loaded and then execute the ONLoad parameter. JS cannot be executed synchronously, which is slower than before. A lot.

I control window.scrollTo(x,y) through JS to realize that when he enters the document reading, it will automatically restore to the last reading progress. In the previous UIwebView, he was triggered synchronously.

At present, I use WKWebView, he must first determine the completion of loading HTML, and then trigger this JS, I tried to execute when HTML is loaded, but this is invalid, WKWebView control loading JS has become very slow, I hope it can I found a solution, I hope someone can help me, I don’t know much about English, so this is the result of Google Translate.


Solution

  • You can inject a script that should be executed on load like this:

    NSString *scriptString = @"window.scrollTo(0,1000);";
    WKUserScript *script = [[WKUserScript alloc] initWithSource:scriptString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [self.webView.configuration.userContentController addUserScript:script];
    

    Here you can find the documentation of WKUserScript: https://developer.apple.com/documentation/webkit/wkuserscript?language=objc

    If the injection time is still too early you can try to add a WKNavigationDelegate and call your script like below (sorry for the Swift code, maybe someone can edit and convert to objective-c)

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
      self.webView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
        if complete != nil {
          self.webView.evaluateJavaScript("window.scrollTo(0,1000);")
        }
      })
    }