How to use js to communicate between two HTML windows

Time:2022-6-20

Scenario: when page a opens page B, and page a needs to synchronize the changed data after the operation of page B

Page a, http://127.0.0.1:10001/A.html


var domain = 'http://127.0.0.1:10001';

window.open('http://127.0.0.1:10001/B.html');
window.addEventListener('message', function (event) {
    if (event.origin !== domain) return;
    console.log('message received:  ' + event.data, event);
}, false);

Page B, http://127.0.0.1:10001/B.html , opener is the opener reference of the current window


var domain = 'http://127.0.0.1:10001';
window.opener.postMessage("success", domain);
window.close();

If a needs to open B and send data to B

//Send data from
var domain = 'http://127.0.0.1:10001';
var myPopup = window.open('http://127.0.0.1:10001/B.html');
myPopup. PostMessage ('data ', domain);

//Receiving data party
window.addEventListener('message', function(event) {
    if(event.origin !== 'http://127.0.0.1:10001') return;
    console.log('message received:  ' + event.data,event);
},false);

The above is the details of how to use js to communicate between two HTML windows. For more information about JS communicating between two HTML windows, please pay attention to other developeppaer related articles!