如何在同一站点的不同页面上绑定到localStorage更改事件?

时间:2016-05-09 08:40:01

标签: jquery html5 google-chrome

我知道如果在两个标签(this topic)中打开相同的页面,如何将更改事件绑定到localStorage,我需要类似的效果,但是如果我在不同的标签中打开了一个网站的两个页面。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

为你做一个例子,检查它是你想要的吗?

<强> http://www.yoursite.com/page1.html

<html>
<head>
    <title>Page 1</title>
</head>
<body>
    <input type="text" id="value"/>
    <button id="save">Save</button>
</body>
<script>

    function $ID(id){
        return document.getElementById(id);
    }
    function addHandler(ele,trigger,handler){
        if(window.addEventListener){
            ele.addEventListener(trigger,handler,false);
            return false;
        }
        window.attachEvent(trigger,handler);
    }

    function saveToStorage(){
        var value = $ID('value').value;
        window.localStorage.setItem('key',value);
    }

    addHandler($ID('save'),"click",saveToStorage);
</script>
</html>

<强> http://www.yoursite.com/page2.html

<html>
<head></head>
<body>
    value:
    <span id="value"></span>
</body>
<script>

    function addHandler(ele,trigger,handler){
        if(window.addEventListener){
            ele.addEventListener(trigger,handler,false);
            return false;
        }
        window.attachEvent(trigger,handler);
    }

    function onStoargeEvent(e) {
        var value = localStorage.getItem('key');
        console.log('Successfully communicate with other tab');
        console.log('Received data: ' + value);
        document.getElementById('value').innerText = value;
    }

    addHandler(window,"storage",onStoargeEvent);

</script>
</html>