views:

277

answers:

1

My site has an iframe which is dynamically populated with html content. The html often contains named anchors, which work fine in IE/Chrome but in Firefox it reopens the entire page within the iframe.

Here's an example: load the page in firefox, scroll to the bottom of the iframe, click the "back to top" link, and you will see what I am talking about.

<html><head></head><body onload="setFrameContent();"><script>

var htmlBody = '<html> <head></head> <body>' +
'<a name="top"><h1>top</h1></a>' +
'<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>' +
'<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>' +
'<a href="#top">back to top</a></body> </html> ';

function setFrameContent(){
    if (frames.length > 0) {
        var d = frames[0].document;
        d.open();
        d.write(htmlBody);
        d.close();
    }
}

</script>
<h1>Here's an iframe:</h1>
<iframe id="htmlIframe" style="height: 400px; width: 100%"><p>Your browser does not support iframes.</p></iframe>
</body></html>

Any ideas?

A: 

I had the same problem and found this workaround.

<html>
<head>
<script>
var htmlBody = '<html> <head></head> <body>' +
'<a id="top"><h1>top</h1></a>' +
'<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>' +
'<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>' +
'<a href="javascript:parent.gotoAnchor(\'top\')">back to top</a></body> </html> ';

function setFrameContent(){
    if (frames.length > 0) {
        var d = frames[0].document;
        d.open();
        d.write(htmlBody);
        d.close();
    }
}

function gotoAnchor(id)
{
    var el = null;
    el = window.frames['myiframe'].document.getElementById(id);
    window.frames['myiframe'].scrollTo(0,el.offsetTop);
}
</script>
</head>
<body onload="setFrameContent();">
<h1>Here's an iframe:</h1>
<iframe name="myiframe" id="htmlIframe" style="height: 400px; width: 100%"><p>Your browser does not support iframes.</p></iframe>
</body>
</html>

Hope this helps.

Asela
Nice! I've already reworked the page so I can't use your solution, but hopefully this will help someone else.
masty