问题
I'm building an application in an environment where I'm restricted to using the local file system and a browser (i.e. running a server isn't an option). I have a generic 'go back' link on numerous pages that mainly just calls history.back()
. It looks something like the following:
function goBack(evt) {
// Check to see if override is needed here
// If no override needed, call history.back()
history.back();
}
$('#my-back-button').click(goBack);
This code works fine in Firefox and IE6 (don't ask), but fails in Chrome. Any suggestions as to why and/or possible workarounds?
I've also tried history.go(-1);
which does not work either.
回答1:
For some reason in chrome, you have to add return false after calling history.go(-1)
Change your function to:
function goBack(evt) {
// Check to see if override is needed here
// If no override needed, call history.back()
history.go(-1);
return false;
}
回答2:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
function goBack(evt) {
// Check to see if override is needed here
// If no override needed, call history.back()
history.back();
$('#my-back-button').forwardEvent('click');
}
$('#my-back-button').click(goBack);
/**
* chrome workaround for triggering click events
* @param {event} event event
* @return {undefined} Returns undefined
*/
$.fn.forwardEvent = function(event) {
this.each(function() {
if (this.dispatchEvent) {
if (event.originalEvent) {
event = event.originalEvent
}
try {
this.dispatchEvent(event);
} catch(error) {
$(this).trigger(event);
}
}
else {
$(this).trigger(event);
}
});
return this;
};
});
</script>
<input type="button" value="<<<<" id="my-back-button">
</body>
</html>
回答3:
var referrer = document.referrer; window.location.replace(referrer);
Use this it will work
回答4:
For Chrome use below code:
<a href="#" onclick="javascript:history.go(-1);return false;" style="text-decoration:underline;">Back</a>
Only this code will work..
I hope it will help... Happy coding.. :)
回答5:
late to the party... here is another solution: you can close the window following the window.history.go(-1). this will work because chrome will keep the window open so it will read the next line. other browsers will simply go back.
<script>
alert("Success!");
window.history.go(-1);
window.close();
</script>
来源:https://stackoverflow.com/questions/9423439/can-i-get-the-history-back-function-to-work-in-chrome-when-using-the-file-p