Skip to main content
InterviewHubPRO
Section Overview
Q332

Question 332 of 536

Part 6: Async Internals, Memory, Microtasks & Web APIs (329 - 403)

62%
JavaScript & V8 Internals (536 Qs)•Part 6: Async Internals, Memory, Microtasks & Web APIs (329 - 403)

How do you avoid receiving postMessages from attackers

senior LevelCode ExampleAsync & PromisesEvent LoopHTTP & REST APIs

Since the listener listens for any message, an attacker can trick the application by sending a message from the attacker’s origin, which gives an impression that the receiver received the message from the actual sender’s window. You can avoid this issue by validating the origin of the message on the receiver's end using the “message.origin” attribute.

For example, let's check the sender's origin http://www.some-sender.com on receiver side www.some-receiver.com,

javascript
  //Listener on http://www.some-receiver.com/
  window.addEventListener("message", function(message){
      if(/^http://www\.some-sender\.com$/.test(message.origin)){
           console.log('You received the data from valid sender', message.data);
     }
  });