0

I need a way to append some parameters in the URL as soon as the user clicks on refresh or he does hard refresh. For example, if the website URL is http://localhost:3000/search/friends?action=friends&controller=users&abc=true&user_type=All

I need to append a string &str="123" just after the user clicks on refresh.

beforeunload event will fire as soon as I click on the refresh. When I am trying to append parameter in the URL it isn't working for me

$(window).on('beforeunload', function() {
   //append &str="123" on refresh
});

I went through few posts on SO but none of it worked for me

How to add or append new stateObject to history

https://www.reddit.com/r/javascript/comments/5t8uzw/javascript_add_dynamic_query_parameter_to_current/

Aniket Tiwari
  • 3,561
  • 4
  • 21
  • 61
  • Does this answer your question? [How do I modify the URL without reloading the page?](https://stackoverflow.com/questions/824349/how-do-i-modify-the-url-without-reloading-the-page) – freedomn-m Aug 31 '20 at 10:20
  • What do you mean by "clicks on refresh" - do you mean the browser F5/refresh button or a button on your page with caption "refresh"? Also what do you mean by "does a hard refresh"? Refreshing via the browser is like copying the url to clipboard, closing the window, opening a new browser window then pasting the url - do you think you can run some js that will affect that new window *before* it opens? – freedomn-m Aug 31 '20 at 10:21
  • What I mean by refresh either by click on F5 or Hold down Ctrl and click the Reload button(Hard Refresh). – Aniket Tiwari Aug 31 '20 at 10:29

2 Answers2

1

Something like this should work:

$(window).on('beforeunload', function() {
   window.location.href = window.location.href + '&str=123';
});
mrid
  • 5,782
  • 5
  • 28
  • 71
0

Solution

$(window).on('beforeunload', function() {
   var refresh = window.location.protocol + "//" + window.location.host + 
   window.location.pathname + '?arg=1';    
   window.history.pushState({ path: refresh }, '', refresh);
});
Aniket Tiwari
  • 3,561
  • 4
  • 21
  • 61