Home  >  Article  >  Web Front-end  >  Detailed explanation of storage event of JavaScript inter-page communication method

Detailed explanation of storage event of JavaScript inter-page communication method

黄舟
黄舟Original
2017-10-26 09:43:241426browse

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 source. For example:


1  
2 //这个网址,协议是 
3 
4 //对比URL:
5 http://www.wszdaodao.cn/demo2/other.html     //同源
6 http://www.wszdaodao.cn:81/demo/index.html   //不同源
7 http://sxh.wszdaodao.cn/demo/index.html      //不同源
8 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 Detailed explanation of storage event of JavaScript inter-page communication method. 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