IFrames And The Back Button
Consider the following HTML: (Written for Google Chrome)
<html>
<head>
<script language="javascript">
function AddToIFrame(){
var Frame=document.getElementById("BackTest").contentWindow.document;
Frame.open();
Frame.write(Math.random());
Frame.close();
}
</script>
</head>
<body>
<iframe id="BackTest" name="BackTest" width="100%" height="222"></iframe>
<a href="j开发者_如何学运维avascript:AddToIFrame();">Add To IFrame</a>
<p>How Can I Modify This HTML So That After Clicking The Link Above, I Can Use The Back Button To Go To Previous IFrame Content?</p>
</body>
</html>
Each time you click the link, the content of the iframe will change. This works great - and for my purposes, MUST use document.write to change the iframe content.
My problem is that I want the back button to cycle back though the previous contents of the iframe - like it does on many other pages. What happens in this example though is that the back button will take me to the previous main page.
How can I make it so that the back button will cause the iframe to revert, until the iframe is out of history, and only THEN go "back" from the main page?
Easy-peasy with some new HTML5 features.
<html>
<head>
<script>
var inner;
window.addEventListener('load', function() {
inner = document.getElementById('inner').contentWindow;
inner.document.open();
inner.document.write(
"\x3cscript\x3e" +
"var contents = document.getElementById('contents');" +
"window.addEventListener('load', function() {" +
"contents = document.getElementById('contents');" +
"}, false);" +
"window.addEventListener('message', function(e) {" +
"history.pushState(e.data, '', '');" +
"contents.value = e.data;" +
"}, false);" +
"window.addEventListener('popstate', function(e) {" +
"contents.value = e.state;" +
"}, false);" +
"\x3c/script\x3e" +
'\x3ctextarea id="contents" readonly\x3e\x3c/textarea\x3e'
);
inner.document.close();
}, false);
function messageInner() {
inner.postMessage(Math.random(), '*');
}
</script>
</head>
<body>
<iframe id="inner"></iframe>
<a href="#" onclick="messageInner(); return false">Clickety</a>
</body>
</html>
The document.write
really should't be used, though; just host your own page (with <iframe src="…">
) with that inner script.
Instead of Frame.open();
use Frame.open('text/html', 'replace');
.
i know it's not the answer you're looking for, but i don't think that this is at all possible, as the back button is controlled by the browser and not by javascript.
You could modify your code to when a user clicks the button you could do
window.location.href = 'http://www.youradress.com/yourpage?iframeurl=' + iframeurl;
and on pageload you load the iframe with the url in the querystring
this way, you get a full page load, and the url stays in the history and the back button works as you want
精彩评论