Js method to achieve inter-page communication

  When writing a page often encounter such a demand: the need to transfer data between two events or open the page.

  For example: the list of existing pages A, B open for editing details by A; A wish to automatically refresh the page after editing save. This time you can use the "storage" event. Usage of localStorage can be found elsewhere.

  Conditions may trigger "storage" events is as follows:

  The same browser to open multiple pages homologous (URL from the protocol, domain name, port and path composed of two agreements if the URL, domain name and the same port, said they homology);

  A web page modify localStorage ;

  Another website registered storage event .

HTTP: // www.cnblogs.cn/demo/index.html 

// URL, protocol is HTTP: // domain name is www.cnblogs.cn, port 80 (default port can be omitted) 


// compare the URL of: 

HTTP: // www.cnblogs.cn/demo2/other.html      // homologous 

HTTP: // www.cnblogs.cn:81/demo/index.html    // different source 

HTTP: // sxh.cnblogs.cn/demo/ index.html       // different source 

HTTP: // www.pudn.cn/demo/index.html          // different sources

  During the test, make sure that is homologous to the page.

  Here is the interaction between the page code to achieve communication between very simple, pageA and pageB.

pageA: Add "storage" monitor

<!DOCTYPE html>

<html>

<head>

    <title>page A</title>

</head>

<body>

<script>

    window.addEventListener("storage", function (e) {

        console.log(e)

        console.log(e.newValue)

    });

</script>

</body>

</html>

pageB: Set localStorage

<! DOCTYPE HTML > 

< HTML > 

< head > 

< title > Page B </ title > 

</ head > 

< body > 

< Button > the Click < Button > 

</ body > 

< Script > 

      document.querySelector ( ' Button ' ). onclick =  function () { 
        // attention random, if the value of the Refresh without making changes, it will not trigger the "storage" event a page 
              localStorage.setItem ( 'Refresh', Math.random()*10);

      }

</script>

</html>

 

  

Guess you like

Origin www.cnblogs.com/zran/p/11428158.html