Cognition 1: Only addresses opened through window.open() can be used for bidirectional cross-domain communication
You can open any address with window.open, and the two addresses can postMessage each other even from different sources
If an iframe is nested within a page, the parent element sends a message to the iframe element only if the address of the iframe is the same as the page address
Have the article says, can through the iframe. ContentWindow access to nested iframe page window, use the iframe. ContentWindow. PostMessage sends a message to the iframe elements. However, because of the same origin policy, JS can only get documents from the same source. Therefore, js cannot manipulate the iframe element and cannot get iframe.contentWindow
If an iframe is nested within a page, the nested page can send a message to the parent page, even if the source is different, but only if the url of the parent element is clear
If be nested iframe. The page is HTML, Windows can be used. The parent. PostMessage (‘ XXX ‘parent address); The parent element address should be explicit and have a port number; Such as http://xx.xxptcs.com:8080 parent can through the window. The addEventListener (‘ message ‘, (data) = > {}) to receive the message;
If you want to use the iframe element, it is best to write it in uselayout
Pits encountered using postMessage
Problem description: When a parent element receives a message event using addEventListener, the parent element receives a much higher number of events than the iframe element
The first time iframe sends a SUCCESS event, the window receives two, the second time it fires four, and the third time it receives six
To solve the process
There is a problem listening for message events on Windows. So use the Click event test
window.addEventListener('click', () => { alert('click'); });
Clicking on a normal element works fine, but clicking on a button element increases the alert. Click on the normal element, and the number of alerts becomes the latest.
Consider: since we are using the Window object, all elements that trigger the click event will be bound to the window. If you look at the code above, there are many times that the message event will be triggered. These events will be registered in the task queue, so try to remove the other types of postMessage
Result: Fewer messages are received, but the increments are still 1 each time
Consider: every render time, the window will run, will each time add a listener function? The test results are as follows
window.addEventListener('click', () => { alert('click'); }); window.addEventListener('click', () => { alert('click'); }); window.addEventListener('click', () => { alert('click'); });
The addEventListener feature allows you to bind multiple event handlers to an event, but the event handler specified by onMessage is considered the element’s method. A property can only correspond to one method
So the solution to the above problem is to replace addEventListener with onMessage