DEV Community

Paboda Hettiarachchi
Paboda Hettiarachchi

Posted on

Save value to localstorage - Magento 2

Recently came across a requirement where url parameter value should be saved in localstorage

Let's say the url is test.com/abc=123 and the localstorage name is 'abc_local'.

Path: app/code/Vendor/Module/view/frontend/web/js/tracking.js

The following will check all the parameters availabe in the URL and select only the required via getUrlParams() method.

require([
    'jquery'
], function($){
    var page_url = window.location.href;
    var abc_val;

    var getUrlParams = function getUrlParameter(page_url) {
        var url = window.location.search.substring(1),
            params = page_url.split('&'),
            param_name,
            i;
        for (i = 0; i < page_url.length; i++) {
            param_name = page_url[i].split('=');

            if (param_name[0] === page_url) {
                return param_name[1] === undefined ? true : decodeURIComponent(param_name[1]);
            }
        }
    };

    abc_val = getUrlParams('abc');
    localStorage.setItem('abc_local', abc_val);
});

The newest way to save this seems to be the following

require([
    'jquery'
], function($){
    var searchParams = new URLSearchParams(window.location.search)
    var abc_val = searchParams.get('abc');
    localStorage.setItem('abc_local', abc_val);
});

Top comments (0)