javascript act on page events

Viewed 68

I've javascript error page which the user is getting in some uses-cases(which is valid).

The error page tell to the user what to do and have a link where to go , when user finish to activate some service, he get back to the error page, user click on refresh F5 he get an error, the error because he have "?code=…" in the URL and additional parameters...

I think to catch the F5 event and clear url from the parameters, is it possible? if not which options do I have?

The scenario

  1. user click on the app new page it opened
  2. the page says something like "you are not subscribed to the service click on the link below to learn how"
  3. user click on the link and open new tab run the process and make subscription, now everything is ok.
  4. user back to the error page and hit refresh , now he get the error as the page is already contain some url pararmeters,

How can I solve this kind of issue?

Im using nodejs12 with simple js/html files. not using any ui frameworks....

1 Answers

The basic answer is this:

document.addEventListener('keypress',function(e){
    e = e || window.event;
    if (e.keyCode == 116) {
        window.location.href = window.location.pathname;
    }
},false);

You can use the following code instead of the basic redirect:

if(typeof URLSearchParams != undefined){
    var usp = new URLSearchParams(window.location.search);
    if(usp.get("code")!=null){
        usp.delete("code");
    }
    window.location.href = window.location.pathname+"?"+usp.toString();
} else {
    window.location.href = window.location.pathname;
}

Also you can use this: (this won't refresh the page)

if(typeof URLSearchParams != undefined){
    window.url=window.location.pathname+window.location.search;
    var usp = new URLSearchParams(window.location.search);
    if(usp.get("code")!=null){
        usp.delete("code");
        window.url=window.location.pathname+"?"+usp.toString();
    }
    if(window.history.replaceState){window.history.replaceState(null,null,window.location.href);}
    if(window.history.pushState){window.history.pushState(null,document.title,window.url);}
} else {
    window.location.href = window.location.pathname;
}

Both of the above will refresh the page if the URLSearchParams is not supported.


Because you are using F5 key you can use this one:

document.addEventListener('keypress',function(e){
    e = e || window.event;
    if (e.keyCode == 116) {
        if(typeof URLSearchParams != undefined){
            var usp = new URLSearchParams(window.location.search);
            if(usp.get("code")!=null){
                usp.delete("code");
            }
            window.location.href = window.location.pathname+"?"+usp.toString();
        } else {
            window.location.href = window.location.pathname;
        }
    }
},false);
Related