19

This is the code of login.html:

<ul>
  <li class="introduction">
    <a href="introduction.html">
      <span class="icon"></span>
      Introduction
    </a>
  </li>
  <li class="login active">
    <a href="#">
      <span class="login"></span>
      Login
    </a>
  </li>
</ul>

An external link will first take to the current page (login) with some query parameters I want to keep. If the user clicks the first link introduction, the introduction.html will be loaded. However, all the query parameter of the previous page (login) are lost.

Is there anyway I can do this page load while keeping the query parameters? Either using HTML or Javascript.

Many thanks.

morels
  • 2,095
  • 17
  • 24

3 Answers3

30

The part of the URL you're interested into is called search.

You may link to another page with the same parameters using

<a onclick="window.location='someotherpage'+window.location.search;">Login</a>
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
9

Automatically append your current params to any links you deem worthy via a rel="" attribute on <a> tags (using jQuery):

<a href="introduction.html" rel="keep-params">Link</a>
// all <a> tags containing a certain rel=""
$("a[rel~='keep-params']").click(function(e) {
    e.preventDefault();

    var params = window.location.search,
        dest = $(this).attr('href') + params;

    // in my experience, a short timeout has helped overcome browser bugs
    window.setTimeout(function() {
        window.location.href = dest;
    }, 100);
});
Matt Stone
  • 3,705
  • 4
  • 23
  • 40
  • What is with the set timeout? What bugs have you encountered? – awbergs Mar 22 '13 at 20:22
  • I've experienced issues where the browser processes the location change without other function statements being completed and resulting in weird behaviour. This is going back a few years now, but I like to keep it just to be safe. This is the same method Google Analytics uses for external links. – Matt Stone Mar 22 '13 at 20:29
4

Modify all a tags client side to include query params

[...document.querySelectorAll('a')].forEach(e=>{
//add window url params to to the href's params
  const url = new URL(e.href)
  for (let [k,v] of new URLSearchParams(window.location.search).entries()){
    url.searchParams.set(k,v)
  }
  e.href = url.toString();
})

Note: if you add a new a tag programatically after this script ran, it will not update it, so it won't work for SPA's for example

Meir
  • 516
  • 4
  • 19
  • 1
    This should be the accepted answer since it a) doesn't mess up URLs that already have query parameters, and b) doesn't require modifying each tag – bomberjackets May 24 '22 at 16:29