问题
I noticed that YouTube doesn't actually reload when you click a link/video on their website. If you define a variable in the console you'll see it will persist.
But neither popstate nor beforeunload get fired. So how is Youtube accomplishing that? And how can I detect that URL change without making a timer constantly check the URL bar.
window.onpopstate = function(event) {
console.log('popstate test!')
return "test"
}
window.onbeforeunload = function(event) {
console.log('beforeunload test!')
return "test"
}
I'm not just looking for a YouTube-solution, I'm looking for a general solution that covers the technology YouTube is using.
回答1:
They're using onpopstate. Paste your JavaScript into the JavaScript console, click on a video, and then click the Back button. You should now see "popstate test!" in the console.
The real problem here is that there's no onpushstate event, but this person seems to have implemented it. There was also a previous StackOverflow question about it. However, this don't seem to work for YouTube, perhaps because they are trying to edit the pushState property of history, but YouTube actually stored history.pushState in a separate variable and is thus unaffected by this code.
However, this transitionend event on the #progress element just for YouTube seems to work.
回答2:
This can actually be implemented in a really simple way. Suppose you have a link in your webpage
<a id="mylink" href="/new-url">My link</a>
You can override its behavior by returning false from an event handler:
document.getElementById("mylink").onclick = function (event) {
window.history.pushState({urlPath:'/new-url'}, "", "/new-url");
// use ajax to reload parts of the page here
return false;
}
Using this technique you can make only part of the page reload when clicking the link.
Edit
I believe youtube does not listen in any way for location changes. This is because if you actually call
window.location = '/watch?v=notrelevant'
The webpage is still refreshed.
来源:https://stackoverflow.com/questions/41773388/what-do-websites-like-youtube-use-to-change-the-url-without-fireing-popstate-or