Mobile Safari Back Button

Mobile Safari back button

This is caused by back-forward cache. It is supposed to save complete state of page when user navigates away. When user navigates back with back button page can be loaded from cache very quickly. This is different from normal cache which only caches HTML code.

When page is loaded for bfcache onload event wont be triggered. Instead you can check the persisted property of the onpageshow event. It is set to false on initial page load. When page is loaded from bfcache it is set to true.

window.onpageshow = function(event) {
if (event.persisted) {
alert("From back / forward cache.");
}
};

For some reason jQuery does not have this property in the event. You can find it from original event though.

$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
alert("From back / forward cache.");
}
});

Quick solution to these problem is to reload the page when back button is pressed. This however nullifies any positive effect back / forward cache would give.

window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload()
}
};

As a sidenote, you can see lot of pages offering using empty onunload handler as solution. This has not worked since iOS5.

$(window).bind("unload", function() { });

Safari-style back button

If you are targeting iOS13 and above, you can use the built-in SF Symbols library provided by Apple.

The chevron.left image is used for the Safari back button.

let chevronLeft = UIImage(systemName: "chevron.left")
let backButton = UIBarButtonItem(image: chevronLeft, style: .plain, target: webView, action: #selector(webView!.goBack))

These icons also come in nine weights from ultralight to black, which can be applied like this.

let chevronLeft = UIImage(systemName: "chevron.left", withConfiguration: UIImage.SymbolConfiguration(weight: .thin))

More information is available from Apple here: SF Symbols

Prevent safari loading from cache when back button is clicked

Your problem is caused by back-forward cache. It is supposed to save complete state of page when user navigates away. When user navigates back with back button page can be loaded from cache very quickly. This is different from normal cache which only caches HTML code.

When page is loaded for bfcache onload event wont be triggered. Instead you can check the persisted property of the onpageshow event. It is set to false on initial page load. When page is loaded from bfcache it is set to true.

Kludgish solution is to force a reload when page is loaded from bfcache.

window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload()
}
};

If you are using jQuery then do:

$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
window.location.reload()
}
});


Related Topics



Leave a reply



Submit