2

我需要从 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?(我尝试删除“替换”参数,但没有帮助)。

4

1 回答 1

2

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

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 的情况下替换所有内容。

于 2013-02-12T12:13:00.943 回答