简体   繁体   中英

HTML5: Refresh page when popstate is fired

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.

2022 年的新闻<\/h2>

当所有主要浏览器开始在页面加载时不发出 popstate 事件时,此问题已解决。所以现在简单地做应该是相对安全的:

 window.addEventListener("popstate", function(e){ location.reload(); });<\/code><\/pre>

现在所有主流浏览器

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM