I'm trying to find a way to jump backwards to the startpoint in a WKWebView History.
Let's say i have a Main/Start-Page (WKWebView init) with a Link to google.com. 
So i'm clicking at the Link and next at google.com i click another link maps.google.com. So i'm 2 steps away from my start-page.
How can i jump back directly to the Main/Startpage without reload or reinit the WKWebView ? 
I have tried the following implementation but with no success:
-(void)backNavigationToStart{
    if([vuMain canGoBack]){
        WKBackForwardList *list = [vuMain backForwardList];
        if(list && list.backList){
            WKBackForwardListItem *item = [list itemAtIndex:0];
            [vuMain goToBackForwardListItem:item];
        }
    }
}
Pure swift solution:
    // find first item in history
    let historySize = webView.backForwardList.backList.count
    let firstItem = webView.backForwardList.item(at: -historySize)
    // go to it!
    webView.go(to: firstItem!)
Note the meaning of the index argument to -itemAtIndex:
“Index of the desired list item relative to the current item: 0 for the current item, -1 for the immediately preceding item, 1 for the immediately following item, and so on.” https://developer.apple.com/library/ios/documentation/WebKit/Reference/WKBackForwardList_Ref/index.html#//apple_ref/occ/instm/WKBackForwardList/itemAtIndex:
Use an appropriate negative index, or use the first item in backList.
You can use JavaScript to navigate to the first item in the browser's history.
extension WKWebView {
    func goBackToFirstItemInHistory() {
        let script = "window.history.go(-(window.history.length - 1));"
        evaluateJavaScript(script) { (_, error) in
            print(error)
        }
    }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With