There are many solutions for cross-domain and cross-window communication. Today we will talk about how to use Post Messge

MND document

The basic use

Send a message

otherWindow.postMessage(message, targetOrigin, [transfer]);
Copy the code

OtherWindow is a reference to another window. For example:

  1. iframecontentWindowattribute
  2. performwindow.openThe window object returned
  3. Is named or numerically indexedwindow.frames

The key is that otherWindow or targetWindow is more accurate, which is the window object of the target page that you’re sending the message to, the window object of the current window that you’re calling window.postMessage() directly, which is basically saying to yourself, Of course, the target page could not be received. The acquisition of targetWindow is divided into two kinds according to the different pop-up methods

  1. The pop-upiframeusewindow.toporwindow.parentParent returns the immediate parent object of the current window, while window.top returns the top-level window object
  2. window.open()Open a new window to usewindow.openerTo obtain

Receives the message

window.addEventListener('message'.function (e) {
    console.log(e.data);
}, false)
Copy the code

Application scenarios

Suppose we have a requirement like this:

There is A login button on page A. Click it to open A new window B(A, different source on page B). After entering the account secret authentication in the new window B, the user will be notified that window A has logged in successfully.

// A page // 1. Click the button to open the window<body>
    <button id='login'>To log in</button>
    <script>
        let newWindow
        login.onclick=function(){
            newWindow = window.open('./b.html'.'Login Page'.'height=400,width=400,top=20,left=20')}window.addEventListener('message'.function (e) {
            if(e.data==='login success') {console.log('Login successful') newWindow? .close()// Close the new window}},false)
    </script>
</body>/ / B page<body>
    <button id="loginSuccess">Click login</button>
    <script>
        let targetWindow = window.opener; // Gets the window object that opens the page
        
        loginSuccess.onclick=function(){
             targetWindow.postMessage('login success'.The '*') // The second argument can specify the destination URL to send,* stands for all
        }
    </script>
</body>
Copy the code

If B opens the window by opening Iframe inside A, then the targetWindow is window.parent instead of window.opener