storage event listener

In an internal sharing meeting of the company, I happened to know this new event of H5 and solved a bug I had before.

The thing is like this, the sum of the quantity displayed on the A page, click to go to the B page, you can manage, add or delete, when the user makes additions and deletions, the quantity will not be updated when returning to the A page, this problem troubled for a long time

I finally waited for the storage event. It is said that Taobao's shopping cart is like this.

Therefore, the localStorage example requires the following conditions to run

  • The same browser opens two web pages of the same origin
  • One of the web pages modifies localStorage
  • Another webpage registers for the storage event

example

A web page listens to the storage event

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>a</title>
</head>
<body>
<script type="text/javascript">
    window.addEventListener('storage', function(e) {
        console.log('storage', e.newValue);
    })
</script>
</body>
</html>

B webpage modified localStorage

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>B</title>
</head>
<body>
<button id="btn">点击</button>
</body>
<script type="text/javascript">
    var btn = document.getElementById(''btn);
    btn.onclick = function() {
        localStorage.clear();
        localStorage.setItem('foo', 'bar');
    }
</script>
</html>

Run: Put the above two webpages on the same server, open the two pages on the same browser, click the button in the B webpage, and you will see the console print content in the A webpage

expand

What if you have to listen in the same web page, you can override the localStorage method and throw a custom event

<!DOCTYPE html>
<html>
<head lang="en">
    <title>A</title>
</head>
<body>
<script>
    var orignalSetItem = localStorage.setItem;
    localStorage.setItem = function(key,newValue){
        var setItemEvent = new Event("setItemEvent");
        setItemEvent.newValue = newValue;
        window.dispatchEvent(setItemEvent);
        orignalSetItem.apply(this,arguments);
    }
    window.addEventListener("setItemEvent", function (e) {
        alert(e.newValue);
    });
    localStorage.setItem("nm","1234");
</script>
</body>
</html>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324912362&siteId=291194637