DEV Community

Paboda Hettiarachchi
Paboda Hettiarachchi

Posted on

1

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);
});

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay