重新加载IFRAME而不添加历史记录

Rob*_*cks 65 html javascript iframe

我正在更改IFRAME src以重新加载它,它正常工作并onload在HTML加载时触发事件.

但它增加了历史的一个条目,我不想要.有没有办法重新加载IFRAME但不影响历史?

gre*_*del 69

使用replace()只是您自己的域iframe的选项.它无法在远程站点上工作(例如:一个推特按钮),并且需要一些特定于浏览器的知识才能可靠地访问子窗口.

相反,只需删除iframe元素并在同一位置构建一个新元素.只有src在DOM中的属性修改后才会创建历史记录项,因此请确保在追加之前设置它.

编辑:JDandChips正确地提到您可以从DOM中删除,修改和重新附加.不需要构建新鲜的.

  • 虽然此答案比接受的答案新2年,但这是更改iframe URL/src而不添加浏览器历史记录的正确方法.出于安全原因,window.frames [frameName] .location和/或history.replaceState的任何其他组合在iframe中都不起作用.即使在同一个域(就像我刚刚发现的那样). (6认同)

Gre*_*reg 30

你可以使用javascript location.replace:

window.location.replace('...html');
Run Code Online (Sandbox Code Playgroud)

将当前文档替换为提供的URL处的文档.与assign()方法的不同之处在于,在使用replace()之后,当前页面将不会保存在会话历史记录中,这意味着用户将无法使用"后退"按钮导航到该页面.

  • 你也可以使用`iframe.contentWindow.location.replace(href);` (14认同)
  • 只需将"window"替换为对iframe的引用即可. (6认同)
  • 为什么不那么简单?var ifr = document.getElementById("iframeId"); ifr.location.replace(ifr.src); (3认同)
  • 这不会针对页面本身吗?我只想重新加载IFRAME,我无法控制在加载的文档中运行的脚本. (2认同)
  • 尝试使用`window.frames ['frame_name'].location` (2认同)

Sta*_*Gun 20

就像Greg上面说的那样,.replace()函数是如何做到的.我似乎无法弄清楚如何回复他的答案*,但诀窍是引用iFrames contentWindow属性.

var ifr = document.getElementById("iframeId");
ifr.contentWindow.location.replace("newLocation.html"); 
Run Code Online (Sandbox Code Playgroud)

*刚学会我需要更多的声誉来评论答案.


JDa*_*ips 13

重新创建iframe的另一种方法是从DOM中删除iframe,更改src然后重新添加它.

在很多方面,这与replace()建议相似,但是当我尝试使用History.js并手动管理状态时,我遇到了一些问题.

var container = iframe.parent();

iframe.remove();
iframe.attr('src', 'about:blank');

container.append(iframe);
Run Code Online (Sandbox Code Playgroud)


JBE*_*JBE 9

一种解决方案是使用object标签而不是iframe标签.

替换这个:

<iframe src="http://yourpage"/>
Run Code Online (Sandbox Code Playgroud)

这样:

<object type="text/html" data="http://yourpage"/>
Run Code Online (Sandbox Code Playgroud)

将允许您更新data属性而不影响历史记录.如果您使用声明性框架(例如React.js,您不应该执行任何命令性命令来更新DOM),这将非常有用.

有关iframe和之间差异的更多详细信息object:使用Iframe或Object标记将网页嵌入到另一个网页中


Min*_*yen 5

尝试使用此函数将旧的iframe替换为从旧的iframe复制的新iframe:

function setIFrameSrc(idFrame, url) {
    var originalFrame = document.getElementById(idFrame);
    var newFrame = document.createElement("iframe");
    newFrame.id = originalFrame.getAttribute("id");
    newFrame.width = originalFrame.getAttribute("width");
    newFrame.height = originalFrame.getAttribute("height");
    newFrame.src = url;    
    var parent = originalFrame.parentNode;
    parent.replaceChild(newFrame, originalFrame);
}
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

setIFrameSrc("idframe", "test.html");
Run Code Online (Sandbox Code Playgroud)

这种方式不会将iframe的URL添加到浏览器历史记录中.