Access-Control-Allow-Origin和document.domain无法正常工作

时间:2017-04-04 07:08:01

标签: javascript php iframe cross-domain access-control

我在PHP页面中有一个iframe,我试图从iframe中访问父元素,但总是在控制台中出现此错误:

  

未捕获的DOMException:使用origin阻止了一个帧   https://subdomain.domain.com访问跨域框架。

我已经在Google <?php session_start(); // remove all session variables session_unset(); // destroy the session session_destroy(); //redirect user header("Location:index.php"); Same Origin policy的第一页上阅读了每一个搜索结果,但这似乎并没有解决我的问题。我仍然遇到同样的错误。

这是我到目前为止所做的:

  1. 在我的iframe内容中添加了Access-Control-Allow-Origin
  2. 在我的iframe内容中添加了Access-Control-Allow-Origin
  3. 还有其他人有类似的问题吗?我该怎么做才能解决它?

    这是我的代码:

    document.domain

    b.example.com中的脚本

    <?php
    header('Access-Control-Allow-Origin: https://b.example.com');
    ?>
    
    <script>
        function receiveMessage(event) {
            if (event.origin !== "https://a.example.com")
                return;
        }
        window.addEventListener("message", receiveMessage, false);
    </script>
    
    
    <div>
        <button title="Close (Esc)" type="button" class="close">×</button>
    </div>
    
    <iframe name="myIframe" class="myIframe"
            src="https://b.example.com" width="100%" height="600px"
            frameborder="0" allowfullscreen="" webkitallowfullscreen="" mozallowfullscreen="">
    </iframe>
    
    </div>
    

1 个答案:

答案 0 :(得分:0)

无论https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage如何,您都可以在文档和iframe之间实现通信。

在这种情况下,您必须指定父窗口上可用的所有操作。这是一个例子:

父窗口:

<html>
<head>
    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
</head>
<body>
<script>
    function receiveMessage(event) {
        console.log(event);
        if (event.data.message === 'Hello world') {
            $('#openFeedback').click();
        }
    }
    window.addEventListener("message", receiveMessage, false);
</script>


<div>
    <button title="Close (Esc)" type="button" class="close">×</button>
</div>

<iframe name="myIframe" class="myIframe"
        src="http://b.test.dev" width="100%" height="600px"
        frameborder="0" allowfullscreen="" webkitallowfullscreen="" mozallowfullscreen="">
</iframe>

</body>
</html>

iframe中的子域名:

<html>
<head>
    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
</head>
<body>
<script>
    window.parent.postMessage({message: 'Hello world'}, 'http://test.dev');
</script>
</body>
</html>

此外,您应该为您在示例中添加的iframe身份提供一些安全检查。在这种情况下,您不需要添加跨源标题

相关问题