Reputation: 24083
I have the following HTML:
<a href="./page1.html">page 1</a>
When clicking on the link, a new history entry added as expected.
Now I change this to:
<a href="./page1.html" onclick="func(event)">page 1</a>
<script type="text/javascript">
function func(event) {
window.history.replaceState(null, '', "./page1.html");
}
</script>
Now, when I click on this link, the history doesn't change.
I don't manage to understand why. I didn't prevented the anchor's action (by event.preventDefault()
or returning false) so I expected from the anchor to add new history entry as it should...
What happend first? the link navigation or the history change?
I would love to get an explanation.
Upvotes: 1
Views: 3850
Reputation: 4296
As far as I can tell, testing in both Firefox and Chrome, navigating a link to the current page does not modify the browser history. Both browsers seem to treat it as a "refresh" rather than navigation.
This means that your second example is effectively replacing the current history state twice (once with the javascript, then again with the default navigation).
Here's the code I was using for testing. Comment/uncomment the replaceState
to see the difference (there is none). Note: I found it helpful to turn on Persist in Firebug to keep my console log from getting cleared during the navigation.
<a href="./page1.html" onclick="func(event)">page 1</a>
<script type="text/javascript">
function func(event) {
console.log("before: " + window.history.length);
//window.history.replaceState(null, '', "./page1.html");
console.log("after: " + window.history.length);
}
onload = function() { console.log("load: " + window.history.length);}
</script>
I haven't been able to find any references for why the browsers work this way. It's pretty easy to verify using your first example, though. Click the link 20 times; your back button will stay disabled.
page0.html
<a href="./page1.html" onclick="func(event)">page 1</a>
<script type="text/javascript">
function func(event) {
console.log("before: " + window.history.length);
window.history.replaceState(null, '', "./page1.html");
console.log("after: " + window.history.length);
}
onload = function() { console.log("load: " + window.history.length);}
</script>
page1.html
Page 1
<script type="text/javascript">
onload = function() { console.log("load: " + window.history.length);}
</script>
Here's what I get in the console when clicking the link
load: 1 page0.html (line 8)
before: 1 page0.html (line 4)
after: 1 page0.html (line 6)
load: 1 page1.html (line 3)
load: 1 page1.html (line 3)
What I think is happening:
func
is calledpage1.html
page1.html
, the page it is already on (step 3), but treats it as a refresh since it's the same page.Upvotes: 1