Home >Web Front-end >JS Tutorial >How to Overcome 'SecurityError: Blocked Cross-Origin Access' When Using Iframes?

How to Overcome 'SecurityError: Blocked Cross-Origin Access' When Using Iframes?

Barbara Streisand
Barbara StreisandOriginal
2025-01-01 03:33:09762browse

How to Overcome

Security Error: Blocked Cross-Origin Access

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.

Workaround

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn