【问题标题】:Modify iframe.src without entry to history object修改 iframe.src 而不进入历史对象
【发布时间】:2013-01-22 03:22:49
【问题描述】:

我的网页中有一个 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() 更改 url。

因此,如何在不登录历史记录的情况下修改 iframe.src?

相关 这实际上是我正在探索的解决主要问题的解决方案之一,我在这里发布了 History object back button with iframes

【问题讨论】:

标签: iframe history back vimeo


【解决方案1】:

不要改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 />

没有历史状态。相同的功能。每个人都赢了。

【讨论】:

  • 如果您愿意,可以将此答案发布到我提到的其他问题。那我就接受了。
【解决方案2】:

你可以这样做:

var iframe = $('#iframe')[0];  
iframe.contentWindow.location.replace(newUrl);

【讨论】:

  • 问题明确指出,由于 Vimeo 要求,此解决方案不可行。
猜你喜欢
  • 1970-01-01
  • 2015-01-18
  • 1970-01-01
  • 1970-01-01
  • 2020-02-20
  • 2013-10-07
  • 2021-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多