我的网页中有一个 iframe。我通过 javascript 修改 src 属性,如下所示:
document.getElementById('myiframe').src = 'http://vimeo.com/videoid1';
document.getElementById('myiframe').src = 'http://vimeo.com/videoid2';
document.getElementById('myiframe').src = 'http://vimeo.com/videoid3';
但是,每次我执行此操作时,它都会记录到浏览器的历史记录中。因此,每次我在浏览器窗口中按回键时,iframe 内容都会从 videoid3 转到 videoid2 再到 videoid1。如果我再次按返回,整个页面都会返回。
我想使用 javascript 修改 iframe src,而不将条目记录到浏览器的历史记录中。因此,如果我单击浏览器后退按钮,整个页面都会返回而不更新 iframe。
我尝试做类似的事情:
document.getElementById('myiframe').contentWindow.location.replace('http://vimeo.com/videoid1');
document.getElementById('myiframe').contentWindow.location.replace('http://vimeo.com/videoid2');
document.getElementById('myiframe').contentWindow.location.replace('http://vimeo.com/videoid3');
虽然这使浏览器后退按钮的行为符合我想要的方式,但它破坏了 vimeo 视频中的某些内容。 Vimeo 要求您通过 iframe.src 而不是 contentWindow.location.replace() 更改网址。
因此,如何在不登录历史记录的情况下修改 iframe.src?
相关 这实际上是我正在探索解决主要问题的解决方案之一,我将其发布在这里History object back button with iframes
最佳答案
不更改src,只需用新的iframe替换旧的iframe吗?
const urls = [
"http://bing.com",
"http://google.com",
"http://duckduckgo.com"
];
function next() {
if(urls.length==0) return;
const original = document.getElementsByTagName("iframe")[0];
const newFrame = document.createElement("iframe");
newFrame.src = urls.pop();
original.parentNode.replaceChild(newFrame, original);
}
nextbtn.addEventListener("click", () => next());
iframe {
width: 300px;
height:300px;
}
<p>let's test some iframes</p>
<button id="nextbtn">next</button>
<iframe />
没有历史记录。相同的功能。每个人都赢了。
关于iframe - 修改 iframe.src 而不进入历史对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14737365/