Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to goBack to startpoint in a WKWebView History

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];
        }
    }
}
like image 420
blub Avatar asked Jun 06 '16 07:06

blub


3 Answers

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!)
like image 58
Ariel Vardi Avatar answered Oct 17 '22 00:10

Ariel Vardi


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.

like image 26
Mitz Pettel Avatar answered Oct 17 '22 00:10

Mitz Pettel


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)
        }
    }
}
like image 41
Joe Masilotti Avatar answered Oct 16 '22 23:10

Joe Masilotti