Search code examples
javascripthtmlurlweb-applicationsstore

Javascript Storing Information in URL


I was wondering how (if it's possible) to store information in the URL of a webpage? I've noticed in websites like Youtube there is information stored in the URL (for example which video in a playlist) and I would like to know how to do this for a website I'm working on.


Solution

  • Usually, the query string of the URL is used for extra data and parameters.

    http://example.com/some-page.html?a=something&b=something%20else
    

    Everything after the question mark ? is the query string. This can be formatted however you want, but the most common way is the format of key=value, with ampersands & separating each variable.

    Now, you might be wondering... what if you actually want an ampersand & or some other non-alpha-numeric character? For that, you must use URL-encoding.

    To access the query string in JavaScript, use window.location.search. To actually parse the query string, see this: https://stackoverflow.com/a/901144/362536

    You can set the query string in JavaScript if you want, by setting window.location.search... just know that you're reloading the page if you do. Unless, you use push/pop state which is a common way to do this.