Sharing a variable between multiple html pages

Here is an example of using window.localStorage to pass data between two html pages being served on the same domain. This will not work accross different domains because of the Same-origin policy.

The example consists of two pages hosted on jsfiddle.net but you could just as easily serve these files from your local file system. Either way there is no server side communication involved in this example.

The first page allows the user to enter some text in a textarea element. There is a save button which when clicked will fire a click event that executes the save handler (the anonymous function specified as the second attribute of addEventListener) that gets the user entered text and saves it in localStorage with the key mySharedData

Page 1 on jsfiddle

HTML

<textarea id="input"></textarea>
<div>
    <button id="save">Save</button>
</div>

Javascript

/*jslint sub: true, maxerr: 50, indent: 4, browser: true */

(function (global) {
    document.getElementById("save").addEventListener("click", function () {
        global.localStorage.setItem("mySharedData", document.getElementById("output").value);
    }, false);
}(window));

The second page recalls the saved text from the key mySharedData that is in localStorage and displays it in the textarea

Page 2 on jsfiddle

HTML

<textarea id="output"></textarea>

Javascript

/*jslint sub: true, maxerr: 50, indent: 4, browser: true */

(function (global) {
    document.getElementById("output").value = global.localStorage.getItem("mySharedData");
}(window));

Both examples are wrapped in an anonymous closure which is executed immediately, and into which we pass the window object which we then reference as the variable named global.

Finally, the first line is a comment, but not any old comment; it is an instruction that is used by jslint; a static code analysis tool used in javascript software development for checking if JavaScript source code complies with coding conventions set out by Douglas Crockford.

Alternatives would be to use:

cookies, once again the Same-origin policy would apply.

or

URL query-strings which would be part of the address used when taking you to the next page, where it can be read in Javascript to obtain data.

Leave a Comment