gpt4 book ai didi

javascript - 在不更改当前 URL 的情况下从 iframe 替换顶级文档

转载 作者:行者123 更新时间:2023-11-30 18:10:02 25 4
gpt4 key购买 nike

我需要从 iframe(同源)替换顶部文档的全部内容。以下由 iframe 执行的 JavaScript 完成了这项工作:

var doc = window.top.document.open("text/html", "replace");
doc.write('hello');
doc.close();

但是,在 Firefox 中,该操作会将当前文档的 URL 更改为 iframe 的 URL。在 Chrome 中,URL 不会更改。是否可以从 iframe 中替换文档,但以在所有合理的浏览器中都能工作的方式保留其原始 URL? (我尝试删除“替换”参数,但没有帮助)。

最佳答案

如果您必须替换完整的内容(包括标题部分等),您可以尝试:

var html = 'YOUR HTML' /* your html string*/,
url = "javascript:(function(){var c = '" +html +
"';document.open();document.write(c);document.close();})();";
// replacing the original location with the dynamically generated one
window.top.location.replace(url);

在这种情况下,url 将与以前相同。如果您不需要更改整个文件,只需更改内容,您可以使用:

window.top.document.documentElement.innerHTML = 'YOUR HTML';

这将使顶级文档的头部保持不变,但会在不更改 url 的情况下替换所有内容。

关于javascript - 在不更改当前 URL 的情况下从 iframe 替换顶级文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14831232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com