My UIWebview
loads a local html file using loadHtmlString. The loaded page has links to other local html files as well as real links that use the internet.
I have added a back button with:
if ([self.webView canGoBack]) [self.webView goBack];
This works fine except it does not recognise the original page loaded with loadHtmlString.
For example, if I navigate:
local -> local -> web
local X local <- web (The first back works, the next does nothing.)
How can I get the webview to recognise the original page so the back button also works for it? Can I add it to the webview's history somehow?
Thanks in advance!
as Cloud Xu said you just need to preload dummy html, like this:
webView.load(URLRequest(url: URL(string: "about:blank")!))
webView.loadHTMLString("<html><body><b>Your page data</b></body></html>", baseURL: nil)
just it and nothing else! Swift3
I had a same problem. I tried manage the history, but it is error prone. Now I have discovered a better solution of this.
What you want to do is simply add a loadRequest to about:blank and make that as a placeholder for you before you call loadHTMLString/loadData. Then you are totally free from monitoring the history. The webview.canGoBack and canGoForward will just work. Of course, you will need a hack to handle go back to the placeholder about:blank. You can do that in webViewDidFinishLoad. Here is the code highlight:
In the function when you call loadHTMLString:
[weakSelf.fbWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
[weakSelf.fbWebView loadHTMLString:stringResponse baseURL:url];
Code to handle goBack:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
if ([webView.request.URL.absoluteString isEqualToString:@"about:blank"]
&& ![webView canGoBack] && [webView canGoForward]) {
[weakSelf.fbWebView loadHTMLString:stringResponse baseURL:url];
}
}
I think it is also possible expand this solution to handle those loadHTMLString that is not the first load. Just by having a Stack to record all the string response and insert an about:blank on each loadHTMLString. And pop the stack when each time go back to about:blank.
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