简体   繁体   中英

Using Localstorage to store and retrieve javascript variables from one html page to another (DOM)

I have one html page 1.html and i want to get some text content and store it to a js.js file using jquery to get the text by id.

This code only works in 1.html page, where the text I want to copy from is but not in 2.html file.

Here is my code. Note that it works if I store text inside localstorage setter second parameter.

 $( document ).ready(function() {
         var c1Title= $('#r1c1Title').text();

//changing c1Title to any String content like "test" will work

    localStorage.setItem("t1",c1Title);
        var result = localStorage.getItem("t1");

        $("#title1").html(result);
        alert(result);
    });

Here is the complete demo I am working on Github :

You need to use either localStorage or cookies .

With localStorage

On the first page, use the following code:

localStorage.setItem("variableName", "variableContent")

That sets a localStorage variable of variableName for the domain, with the content variableContent . You can change these names and values to whatever you want, they are just used as an example

On the second page, get the value using the following code:

localStorage.getItem("variableName")

That will return the value stored in variableName , which is variableContent .

Notes

  • There is a 5MB limit on the amount of data you can store in localStorage.
  • You can remove items using localStorage.removeItem("variableName") .
  • Depending on where you are, you may need to take a look at the cookie policy (this effects all forms of websites storing data on a computer, not just cookies). This is important, as otherwise using any of these solutions may be illegal.
  • If you only want to store data until the user closes their browser, you can use sessionStorage instead (just change localStorage to sessionStorage in all instances of your code)
  • If you want to be able to use the variable value on the server as well, use cookies instead - check out cookies on MDN
  • For more information on localStorage, check out this article on MDN , or this one on W3Schools

Please try to use this code. It's better to use local storage .

Here you need to make sure that you are setting this local storage value in parent html page or parent js file.

create local storage

localStorage.setItem("{itemlable}", {itemvalue});

localStorage.setItem("variable1", $('#r1c1Title').text());
localStorage.setItem("variable2", $('#r1c2Title').text());

Get local storage value

localStorage.getItem("{itemlable}")

alert(localStorage.getItem("variable1") + ' Second variable ::: '+ localStorage.getItem("variable2"));

For more information follow this link https://www.w3schools.com/html/html5_webstorage.asp

If you wanted to store in div then follow this code.

Html Code

<div class="div_data"></div>

Js code:

$(document).ready(function () {
            localStorage.setItem("variable1", "Value 1");
            localStorage.setItem("variable2", "Value 2");
                $(".div_data").html(' First variable ::: '+localStorage.getItem("variable1") + ' Second variable ::: '+ localStorage.getItem("variable2"));
        });

Hope this helps.

You can use local storage as mentioned in above comments. Please find below how to write in javascript.

Local Storage Pros and Cons

Pros:

  1. Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity.
  2. 5120KB (5MB which equals 2.5 Million chars on Chrome) is the default storage size for an entire domain.
  3. This gives you considerably more space to work with than a typical 4KB cookie.
  4. The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.
  5. The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

Cons:

It works on same-origin policy. So, data stored will only be available on the same origin. // Store value in local storage localStorage.setItem("c1Title", $('#r1c1Title').text());

// Retrieve value in local storage
localStorage.getItem("c1Title");

Your html div

<div id="output"></div>

Add Javascript Code

$('#output').html(localStorage.getItem("c1Title"));

Let me know if it not works

Create a common.js file and modified this and save.

Session = (function () {
    var instance;
    function init() {
        var sessionIdKey = "UserLoggedIn";
        return {
            // Public methods and variables.
            set: function (sessionData) {
                window.localStorage.setItem(sessionIdKey, JSON.stringify(sessionData));
                return true;
            },
            get: function () {
                var result = null;
                try {
                    result = JSON.parse(window.localStorage.getItem(sessionIdKey));
                } catch (e) { }
                return result;
            }
        };
    };
    return {
        getInstance: function () {
            if (!instance) {
                instance = init();
            }
            return instance;
        }
    };
}());


function isSessionActive() {
    var session = Session.getInstance().get();
    if (session != null) {
        return true;
    }
    else {
        return false;
    }
}


function clearSession() {
    window.localStorage.clear();
    window.localStorage.removeItem("CampolUserLoggedIn");
    window.location.assign("/Account/Login.aspx");
}

Insert like this.

$(function () {
    if (!isSessionActive()) {
        var obj = {};
        obj.ID = 1;
        obj.Name = "Neeraj Pathak";
        obj.OrganizationID = 1;
        obj.Email = "npathak56@gmail.com";
        Session.getInstance().set(obj);
    }

    ///clearSession();
});

get like this way

  LoggedinUserDetails = Session.getInstance().get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM