当我单击按钮时,控制台中出现安全错误:
<iframe src="http://www.example.com/" id="iframe"></iframe>
<input type="button" value="Color it!" id="button">
<script>
var iframe = document.getElementById('iframe'),
button = document.getElementById('button');
button.onclick = function () {
iframe.src = 'linked-frame.html';
iframe.contentDocument.body.style.background = 'red';
};
</script>
当我更改函数中的 iframe
源时,它不应该抛出此类错误。
最佳答案
您的问题是,您需要等到 iframe 在更改 src 后加载,然后才能触发函数。
尝试
var iframe = document.getElementById('iframe'),
button = document.getElementById('button');
button.onclick = function () {
iframe.src = 'linked-frame.html';
iframe.onload = function() {
iframe.contentDocument.body.style.background = 'red';
};
};
关于javascript - 尽管 iframe 位于同一域,但出现跨源安全错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23951945/