跨域 iframe 获取 src 页面方法
由于安全限制,您不能直接从一个跨域的 iframe 访问它的文档内容。但是,您可以使用 postMessage API 来在 iframe 和主页面之间进行通信,以获取跨域的 iframe 的 src 页面。
在 iframe 中,您可以使用以下代码将消息发送到主页面:
window.parent.postMessage('getSrc', '*');
这将向包含 iframe 的父页面发送 'getSrc' 消息。 '*' 参数表示消息可以发送到任何源。
在主页面中,您可以使用以下代码接收消息:
window.addEventListener('message', receiveMessage, false);
function receiveMessage(event) {
if (event.data === 'getSrc') {
var src = document.getElementById('iframe').src;
// do something with the src
}
}
这将监听 'message' 事件,并在接收到 'getSrc' 消息时获取 iframe 的 src。请注意,您需要将 'iframe' 替换为实际的 iframe 元素的 ID。
请注意,使用 postMessage API 时需要注意安全性,以防止跨站点脚本攻击。建议只接受来自已知来源的消息。
原文地址: https://www.cveoy.top/t/topic/omMQ 著作权归作者所有。请勿转载和采集!