Aniket Tiwari
Aniket Tiwari

Reputation: 3998

Append paramater in the url on click of refresh

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/

Upvotes: 0

Views: 578

Answers (2)

Aniket Tiwari
Aniket Tiwari

Reputation: 3998

Solution

$(window).on('beforeunload', function() {
   var refresh = window.location.protocol + "//" + window.location.host + 
   window.location.pathname + '?arg=1';    
   window.history.pushState({ path: refresh }, '', refresh);
});

Upvotes: 0

mrid
mrid

Reputation: 5796

Something like this should work:

$(window).on('beforeunload', function() {
   window.location.href = window.location.href + '&str=123';
});

Upvotes: 1

Related Questions