Open iframe page in parent frame (javascript)

2019-08-18 19:11发布

问题:

I'm sure someone in the know has a solution to this problem I'm facing? I have a site with Index.html which contains an Iframe. In this iframe, all pages of the site are shown...Home.html..Info.html...Contact.html..etc.

I'd like a javascript function so that when you open Home.html via the google sitemap for example, it shows up in the parent frame in Index.html. The function I currently have in the head section of each child page is:

<script> if (parent.location.href == self.location.href){ window.location.href = 'index.html' } </script>

Although this works, it doesn't remember the child page and opens the Index page with the default iframe page...Home.html as the iframe is coded like this:

<iframe id="iframe" src="home.html" allowTransparency="true" id="iframeID" name="iframeID" width="100" height="100" scrolling="no" frameborder="no"> </iframe>

Has anybody a solution to this problem, as I've searched everywhere? Thanks.

回答1:

Try to set location.href with a query string, i.e.:

// .getAttribute so we don't get the absolute URL
var src = document.getElementById("iframe").getAttribute("src");
if (parent.location.href === self.location.href)
    location.href = "index.html?" + escape(src);

In index.html create a check for query strings and set the iframe source accordingly:

if (location.search)
    document.getElementById("iframe").src =
            unescape(location.search.substring(1));