Home  >  Article  >  Web Front-end  >  Introduction to storage events, communication methods between js pages

Introduction to storage events, communication methods between js pages

一个新手
一个新手Original
2017-10-26 09:45:411538browse

When writing a page, you sometimes encounter such a requirement, which requires the transmission of data or an event between two pages. At this time, you need to use the storage event I am going to talk about today. Before learning this event, you need to understand the usage of localStorage. For specific usage, please see other documents. The conditions for triggering a storage event are as follows:

  1. The same browser opens two pages with the same origin

  2. Modified in one web page localStorage

  3. Another web page registered the storage event

 storage event, It only works if the page is from the same source. It has no effect if it is from a different source. So what is homology?

URL consists of protocol, domain name, port and path. If the protocol, domain name and port of two URLs are the same, it means that they have the same origin. For example:


http://www.wszdaodao.cn/demo/index.html
//这个网址,协议是http://域名是www.wszdaodao.cn,端口是80(默认端口可以省略)

//对比URL:
http://www.wszdaodao.cn/demo2/other.html     //同源
http://www.wszdaodao.cn:81/demo/index.html   //不同源
http://sxh.wszdaodao.cn/demo/index.html      //不同源
http://www.mamama.cn/demo/index.html         //不同源

Therefore, when testing, be sure to ensure that it is a page from the same origin.

The following is the interaction code between the two pages. The implementation is very simple, communication between pageA and pageB.

page A: Set localStorage


<!DOCTYPE html>
<html>
<head>
<title>page A</title>
</head>
<body>
<button>click<button>
</body>
<script>
      document.querySelector(&#39;button&#39;).onclick = function(){
              localStorage.setItem(&#39;Num&#39;, Math.random()*10);
      }
</script>
</html>

page B: Listen for storage events


<!DOCTYPE html>
<html>
<head>
    <title>page B</title>
</head>
<body>
<script>
    window.addEventListener("storage", function (e) {
        console.log(e)
        console.log(e.newValue)
    });
</script>
</body>
</html>

The above is the detailed content of Introduction to storage events, communication methods between js pages. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn