How to #3 – How to communicate across browser tabs/windows using Html5 local storage

In this How to #3, we are going to see how to communicate or transfer data across the browser tabs/windows using Html5 local storage and JQuery.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>How to #3</title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#sender").keyup(function () {
                //Setting the new value to the storage variable
                localStorage.setItem('transferdata', this.value);
            });

            //Handling Storage event
            $(window).bind('storage', function (e) {
                //Checking our storage key is modified or not
                if (e.originalEvent.key == 'transferdata') {
                    //Setting the modified storage variable value to the control
                    $("#receiver").html(e.originalEvent.newValue);
                }
            });
        });
    </script>
</head>
<body>
    <p>
        <strong>Enter data to transfer:</strong>
        <input type="text" name="sender" value="" id="sender" />
    </p>
    <p>
        <strong>Receivied data:</strong>
        <p id="receiver">
            Received data will be shown here in the other tab/window.
        </p>
    </p>
</body>
</html>

Now let us see the output of the implementation, open the page in two windows of the same browser as shown below.

1

Let us enter some value in the textbox of first window to see the transfer of data to second tab.

2

Happy Coding.!!

You may also like...