I have a ajax search-form like:
url: /search/
=> User enters a search-term and clicks a button
=> search is done and shows the results via ajax in a div on the page
But: I also want the user to be able to copy&paste the URL to friends and navigate through the previous searches. So when triggering the search, I change the url in the browsers addressbar from
/search/
to
/search/?q=yourkeyword
using:
window.history.pushState("", "Search for "+keyword, "/search/?q="+keyword);
This changes the url in the browsers addressbar to /search/?q=yourkeywords and works fine.
Now, hitting the back-button, the browsers addressbar is showing again /search/, which is fine. But the page-content is not reloaded, it still shows the results from /search/?q=yourkeyword.
So I added:
window.addEventListener("popstate", function(e)
{ location.reload();
});
Is this the correct way? It works fine in desktop-browsers like FF and Chrome, but for example in iOS, the popstate-event is fired on the very first loading of searchform on /search/, resulting in a neverending reloading of that page.
Whats the right way to do it?
The simplest solution is to set a global variable when you use pushState
. Then, in your onpopstate handler just check if that is set. Eg:
window.historyInitiated = true;
window.history.pushState("", "Search for "+keyword, "/search/?q="+keyword);
...
window.addEventListener("popstate", function(e) {
if (window.historyInitiated) {
window.location.reload();
}
});
My suggestion:
window.location.href = window.location.href;
I haven't tested it, but I think it will do what you want.
当所有主要浏览器开始在页面加载时不发出 popstate 事件时,此问题已解决。所以现在简单地做应该是相对安全的:
window.addEventListener("popstate", function(e){ location.reload(); });<\/code><\/pre>现在所有主流浏览器
- 当用户导航(例如通过后退和前进按钮)到通过
pushState()<\/code>添加的历史条目时,总是<\/strong>触发popstate<\/code>事件<\/li>
加载网页时从不<\/strong>触发popstate<\/code>状态(例如通过刷新按钮)<\/li><\/ul>引用自https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/PopStateEvent<\/a> :
<\/blockquote>"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.