How to clear back forward list in UIWebview on iPhone?

Disclaimer
As with anything like this, bear in mind that the results may not make it through app store approval and may not work at-all with future revisions of the SDK.


There is no official method for doing this in the SDK. However if you really want to clear the back/forward history of a UIWebView it can be done with a little delve into the private frameworks.

A quick and dirty way to do it (complete with a bunch of ugly compiler warnings) is as follows:

Given that myUIWebViewInstance is a perfectly normal instance of UIWebView:

id internalWebView=[[myUIWebViewInstance _documentView] webView];       
[internalWebView setMaintainsBackForwardList:NO];
[internalWebView setMaintainsBackForwardList:YES];

There is also the rather tempting _clearBackForwardCache method in the framework, however it didn't seem to do much when tickled. Just flipping the boolian worked a treat for me.


If you're trying to "reuse" an existing UIWebView, and disable the ability to go back to whatever previous page it was in before, you can:

  1. When loading the new request (the one that user shouldn't go back from), save the URL of the new request, say like:

    self.curURL = [NSURL urlWithString:@"http://www.bla.com"];
    [webview loadRequest:[NSURLRequest requestWithURL:curURL]];

  2. I'm guessing you have your own back button, so on your webViewDidFinishLoad delegate method, add:

    backbttn.enabled = webView.canGoBack && ![[webView.request URL] isEqual: curURL];

This way, the user won't even know that the UIWebView can go back to the page before.