Abhineet.in

unlearning the learnt

Menu
  • Home
  • About
  • CAT Preparation
Menu

How to persist state through query string in url

Posted on November 10, 2021April 5, 2023 by Abhineet Mittal

In some cases when you do not have the option of cookies to manage state, query string can be a good option.

In this article, I am going to use some Javascript to persist state through a query string in the url. The Javascript code is added to head section of html when the desired query string is present in the url and then that Javascript will add that query string to all the internal urls on that page.

Here is the code-

const elements = document.querySelectorAll("a");
var url ='';
var theURL = '';
elements.forEach(function (element) {
    url = element.getAttribute('href');
    if ( url.startsWith('https://example.com') ) {
        try {
            theURL = new URL(url);
            if ( theURL ) {
                let params = new URLSearchParams(theURL.search);
                params.set( 'key', 'value' );
                theURL.search = params;
                element.setAttribute('href', theURL);
            }
        } catch(e) {
        }
    }
});

Now you can persist the query string throughout the user session. You can use the query string to identify the session details on the server.

Hope this helps.

Category: Coding

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • Business
  • CAT Preparation
  • Coding
  • Fiction
  • Finance
  • How-To-Life
  • Javascript
  • Life
  • Life at Infosys
  • Photoshop
  • Productivity
  • Publishing
  • Social Awareness
  • Startup
  • Technology
  • Uncategorized
  • Utilities
  • Visual Studio Code
  • Web Development
  • WordPress
  • Work Culture

Recent Posts

  • The Ultimate Guide to CAT Preparation: Tips and Tricks
  • Self-Publishing vs. Traditional Publishing: Which Is Right for You?
  • 7 Effective Strategies to Overcome Procrastination and Achieve Your Goals
  • How to detect English/ASCII string in PHP
  • The state of automobile dealerships in India

Recent Comments

  • Rohan George on Intermediate, Stream & Location: Luck by Chance
  • Ashika on Intermediate, Stream & Location: Luck by Chance
  • Steve on My first job, Infosys
  • SAKTHI on Finally, its Mysore…
  • Akash dhyani Akash on Training Begins…
© 2023 Abhineet.in | Powered by Minimalist Blog WordPress Theme