window.history.go(-1)在Safari中无法运行的解决方案咨询
window.history.go(-1) Not Working in Safari Hey there! I’ve dealt with this frustrating Safari quirk plenty of times, so let’s break down the common fixes and why this happens in the first place.
First, Check if There’s a Valid History Entry
Safari is stricter than Chrome/Firefox about what counts as a "valid" history entry. If your page was opened directly (not navigated to from another page), or if the history stack only has one entry, history.go(-1) will do nothing because there’s nowhere to go back to.
Always add a check before running the function:
// Make sure there's a previous page to go back to if (window.history.length > 1) { window.history.go(-1); } else { // Fallback: redirect to a default page if no history exists window.location.href = "/"; }
Try history.back() Instead
While history.go(-1) and history.back() are theoretically identical, Safari sometimes handles back() more reliably, especially with pages that use pushState/replaceState for client-side routing.
Swap it out like this:
if (window.history.length > 1) { window.history.back(); }
Handle Iframe Scenarios
If your code is running inside an iframe, Safari restricts access to the parent window’s history by default. If you need to navigate the parent page back, explicitly target the parent window:
if (window.parent.history.length > 1) { window.parent.history.go(-1); }
Work Around Safari’s Caching Quirks
Sometimes Safari’s aggressive page caching can mess up the history stack. A quick (though slightly hacky) fix is to add a small delay before triggering the back action:
setTimeout(() => { if (window.history.length > 1) { window.history.back(); } }, 100);
Check User Privacy Settings (For Debugging)
In rare cases, Safari’s "Prevent cross-site tracking" setting can interfere with history navigation. If you’re testing locally, have users check if disabling this setting (in Safari > Settings > Privacy) resolves the issue—though this isn’t a fix you can enforce as a developer.
内容的提问来源于stack exchange,提问作者Ankit Sharma

