Home >Web Front-end >JS Tutorial >How to Overcome 'SecurityError: Blocked Cross-Origin Access' When Using Iframes?
When attempting to integrate an iframe into your HTML page and access its elements using JavaScript, you may encounter the following error:
SecurityError: Blocked a frame with origin "http://www.example.com" from accessing a cross-origin frame.
This error stems from the browser's adherence to the same-origin policy, a security measure that prevents scripts from accessing frames with different origins. An origin encompasses the protocol, hostname, and port.
While direct cross-origin script access is prohibited, you can utilize window.postMessage and its corresponding message event to establish communication between the frames:
Main Page:
const frame = document.getElementById('your-frame-id'); frame.contentWindow.postMessage(/*any variable or object here*/, 'https://your-second-site.example');
Iframe:
window.addEventListener('message', event => { // Verify the origin to ensure it's your site if (event.origin === 'https://your-first-site.example') { // Retrieve data from event.data console.log(event.data); } });
This approach allows bidirectional communication between the frames. Cross-origin message passing can also be applied to pop-ups and other new windows generated from the main page.
The above is the detailed content of How to Overcome 'SecurityError: Blocked Cross-Origin Access' When Using Iframes?. For more information, please follow other related articles on the PHP Chinese website!