![](/img/trans.png)
[英]JS - How to reload iframe on a page when returning back from a link in the iframe
[英]Reload Page From Iframe in JS
我有一个 iframe,我想通过它刷新主页。 我已经尝试过诸如window.location.reload()
等功能。但它似乎不起作用。 我需要将重新加载功能放在 iframe 上,而不是放在主页上。 我可以获得尽可能多的document.referrer
来获取主页。
iframe 代码和框 看到这个
主页代码和框看这个
<div class="iframe-container">
<iframe class="iframe-layout" src="https://zqdqmn.csb.app/"></iframe>
</div>
iframe 部分
<script>
function redirectToGoogle() {
const mainUrl = document?.referrer
window.location.href = `${mainUrl}`
// window.open(mainUrl,"_self")
}
</script>
</body>
要与跨源页面交互,我们需要使用onmessage
或addEventListener("message", ...)
来使用window.postMessage
和MessageEvents 。
Codesandbox 上的示例显示了如何使用特定的来源,而这里的示例显示了如何处理它,如果目标和/或源窗口具有'null'
作为来源。
window.addEventListener("message", async ({ data, origin, source }) => { // another check would be a check for the origin, but since the iframe was created with srcdoc, the origin is null console.log("Origin:",origin); // only react if the source window is the frame if (source == frameToListen.contentWindow) { try { // in case of "data == null" console.log("data", data); // wait for 5 seconds before reload if (data.reload) { await new Promise(r => setTimeout(r,5000)); console.log("reload..?"); window.location.reload(); } } catch (e) { console.error(e); } } }); // Generate dummies in the iframe to send some events // The only way to contact a window with an origin of "null" is by "*" frameToListen.srcdoc = `<script>function send(obj) { window.parent.postMessage(obj, '*'); // avoid unexpected end of input in stacksnippet-parser }</scr${""}ipt><input type="button" value="undefined" onclick="send()"> <input type="button" value="null" onclick="send(null)"> <input type="button" value="{ reload: true }" onclick="send({ reload: true })"> <input type="button" value="{ reload: false }" onclick="send({ reload: false })"> <input type="button" value="[]" onclick="send([])">`;
<iframe id="frameToListen" style="width: 100%;"></iframe>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.