0

I have a site that pass discount codes in URL with Query Strings, I want to know how to pass this queries dynamically through navigation when a user clicks in an

<a href='mysite.com/page2'>

So I want to pass all the current queries to all linked pages dynamically. It don't necessarily need to be passed through as string queries, if there is a better way to do this...

Sinto
  • 3,915
  • 11
  • 36
  • 70
Luis Grappi
  • 87
  • 2
  • 8
  • If you're just interested in passing data between pages any client side storage would be fine (Session storage, Local Storage, Web SQL, etc) – George Sep 17 '18 at 13:00
  • Persisting data between pages is more often done using sessions on the server side or local storage in the browser. – Matt S Sep 17 '18 at 13:01

1 Answers1

0

You could do this much better using client side storage. localStorage has good browser support and is easy to implement. Saving a value:

localStorage.setItem( "key", "some value" );

Retrieving key:

var retrievedString = localStorage.getItem( "key" );

The saved values will persist between page navigations, and even after the session ends. More info here


But as far as passing current querys through links, you can override the default behaviour of all <a> tags, and instead run a function that gets the href of the link and the query section of the current page's url, merges them together into a new url and then navigates there. (modified from here)

document.onclick = function (e) {
    e = e ||  window.event;
    var element = e.target || e.srcElement;
    if (element.tagName == 'A') {
        var q = location.href; 
        window.location.href = element.href + q.substring( q.indexOf( "?" ) );
        return false;
    }
};
jla
  • 4,191
  • 3
  • 27
  • 44
  • 1
    This is a good way to do this! But for my problem I saw that window.sessionStorage is better than localStorage. Thank you! – Luis Grappi Sep 17 '18 at 14:32