我有一個PHP頁面中的iframe,我試圖從iframe中獲取父元素,但總是在控制檯收到此錯誤:訪問控制允許來源和document.domain的工作不
未捕獲的拋出:DOMException:訪問一個跨來源幀阻止與原籍 https://subdomain.domain.com的幀。
我已閱讀谷歌的周圍Same Origin policy
和Access-Control-Allow-Origin
第一頁上的每一個搜索結果,但似乎並沒有被解決我的問題。我仍然收到同樣的錯誤。
這是我迄今所做的:
- 新增
Access-Control-Allow-Origin
到我的iframe中的內容。 - 增加
document.domain
到我的iframe中的內容。
有其他人有類似的問題?我能做些什麼來解決它?
這裏是我的代碼:
<?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>
腳本在b.example.com
<script>
window.parent.$('.close').click(function() {
var thisObj = this;
if (!feedbackLoaded) {
$('#openFeedback').click();
feedbackLoaded = true;
$('#feedbackForm .close').click(function() {
window.parent.$.magnificPopup.proto.close.call(thisObj);
});
return false;
} else {
window.parent.$.magnificPopup.proto.close.call(thisObj);
}
});
</script>
處理父窗口始終是一個糟糕的做法。即使域相同 –
我理解你,但是當你在一個十來歲的應用與每天數百萬用戶的工作,你知道最輕微的修改是解決辦法,而不是一個妥善的解決辦法:)這是它是什麼,我們必須找到現有系統的解決方案 –
ok :)然後,您必須向父窗口(Access-Control-Allow-Origin)添加說明。然後,你可以通過postMessage的與它通信:https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage –