Modify iframe.src without entry to history object

故事扮演 提交于 2019-12-21 05:00:07

问题


I have an iframe in my web page. I modify the src property via javascript like so:

document.getElementById('myiframe').src = 'http://vimeo.com/videoid1';
document.getElementById('myiframe').src = 'http://vimeo.com/videoid2';
document.getElementById('myiframe').src = 'http://vimeo.com/videoid3';

However, everytime I do this, it's logged into the browser's history. So everytime I press back in the browser window, the iframe content goes from videoid3 to videoid2 to videoid1. If I press back again, the entire page goes back.

I would like to modify the iframe src with javascript WITHOUT logging an entry into the browser's history. So if i click the browser back button, the entire page goes back without updating the iframe.

I tried doing something like:

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');

Although this made the browser back button behave the way I wanted to, it broke certain things in the vimeo video. Vimeo REQUIRES you to change urls via the iframe.src instead of contentWindow.location.replace().

As such, how do I modify the iframe.src WITHOUT logging into history?

Related This is actually one of the solutions I'm exploring to solve the main problem, which I posted here History object back button with iframes


回答1:


don't change the src, just replace the old iframe with a new one?

<!doctype html>

<style>
iframe {
    width: 300px;
    height:300px;
}
</style>

<script>
var urls = ["http://bing.com", "http://google.com", "http://duckduckgo.com"];

function next() {
    if(urls.length==0) return;
    var original = document.getElementsByTagName("iframe")[0];
    var newFrame = document.createElement("iframe");
    newFrame.src = urls.pop();
    var parent = original.parentNode;
    parent.replaceChild(newFrame, original);
}
</script>

<p>let's test some iframes</p>
<button onclick="next()">next</button>
<iframe />

No history states. Same functionality. Everyone wins.




回答2:


You can do something like this:

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


来源:https://stackoverflow.com/questions/14737365/modify-iframe-src-without-entry-to-history-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!