How does postMessage receive data?

postMessage is a method in the Web API used to send messages between different browsing contexts, such as windows, iframes, workers, etc. There are two ways to receive the data.

  1. Receive data using a message event listener.
window.addEventListener('message', function(event) {
  // event.data中存储了传递的数据
  console.log('接收到的数据:', event.data);
});
  1. Use the onmessage event handler in the context of receiving data.
self.onmessage = function(event) {
  // event.data中存储了传递的数据
  console.log('接收到的数据:', event.data);
};

Both ways can receive the data passed when the postMessage method is called.

bannerAds