iframe 修改内部样式跨域了 如何修改 iframe 修改内部样式
如果 iframe 的源与父页面不同源,即跨域了,那么父页面是无法直接修改 iframe 内部样式的。这是由于浏览器的同源策略限制导致的安全性问题。
你可以通过以下方法来修改 iframe 内部样式:
- 使用 postMessage:在父页面中使用
postMessage方法向 iframe 发送消息,然后在 iframe 页面中监听message事件,接收到消息后修改样式。 父页面中的代码:
var iframe = document.getElementById('myFrame');
iframe.contentWindow.postMessage('changeStyle', '*');
iframe 页面中的代码:
window.addEventListener('message', function(event) {
if (event.data === 'changeStyle') {
// 修改内部样式
}
});
- 修改 iframe 页面:在 iframe 页面中添加一个用于修改样式的函数,并在父页面中调用该函数。
父页面中的代码:
var iframe = document.getElementById('myFrame');
iframe.contentWindow.changeStyle();
iframe 页面中的代码:
function changeStyle() {
// 修改内部样式
}
需要注意的是,这些方法都依赖于在 iframe 页面中添加一些代码来实现样式的修改。如果 iframe 的源不受你的控制,那么你可能无法直接修改其样式
原文地址: https://www.cveoy.top/t/topic/iN4R 著作权归作者所有。请勿转载和采集!