InterviewHubPRO
Section Overview
Q330

Question 330 of 521

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

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

Is PostMessage secure

Yes, postMessages can be considered very secure as long as the programmer/developer is careful about checking the origin and source of an arriving message. But if you try to send/receive a message without verifying its source will create cross-site scripting attacks.

Practical Code Example

javascript
// PostMessage is only secure if you explicitly validate event.origin:
// Vulnerable:
// window.addEventListener('message', e => eval(e.data));

// Secure:
window.addEventListener('message', (event) => {
  if (event.origin !== 'https://trusted-domain.com') return; // Enforce origin check!
  console.log('Secure data:', event.data);
});