How to force reloading a page when using browser back button? Ask Question

How to force reloading a page when using browser back button? Ask Question

I need to somehow detect that the user has pressed a browsers back button and reload the page with refresh (reloading the content and CSS) using jquery.

How to detect such action via jquery?

Because right now some elements are not reloaded if I use the back button in a browser. But if I use links in the website everything is refreshed and showed correctly.

IMPORTANT!

Some people have probably misunderstood what I want. I don't want to refresh the current page. I want to refresh the page that is loaded after I press the back button. here is what I mean in a more detailed way:

  1. user is visiting page1.
  2. while on page1 - he clicks on a link to page2.
  3. he is redirected to the page2
  4. now (Important part!) he clicks on the back button in browser because he wants to go back to page1
  5. he is back on the page1 - and now the page1 is being reloaded and something is alerted like "You are back!"

ベストアンサー1

pageshowブラウザが履歴をたどってページに移動する状況を処理するためにイベントを使用できます。

window.addEventListener( "pageshow", function ( event ) {
  var historyTraversal = event.persisted || 
                         ( typeof window.performance != "undefined" && 
                              window.performance.navigation.type === 2 );
  if ( historyTraversal ) {
    // Handle page restore.
    window.location.reload();
  }
});

HTTP キャッシュも関係している可能性があることに注意してください。キャッシュする必要のあるリソースのみをキャッシュするには、サーバー上で適切なキャッシュ関連の HTTP ヘッダーを設定する必要があります。強制リロードを実行して、ブラウザに HTTP キャッシュを無視するように指示することもできます。window.location.reload( true )ただし、これが最善の解決策だとは思いません。

詳細については以下をご確認ください:

おすすめ記事