Changing address bar when using iframe

2019-04-11 18:38发布

Is there a way to use an iframe, but still have the address bar change when clicking what's inside the iframe to what the page actually is? I want to have a horizontal bar at the top of the page with a music player that allows music to play while browsing the site. But I also want people to easily be able to bookmark the pages as well.

I've searched, but can't find the answer. Many are just looking to change what URL is loaded in the iframe...that's not what I want. I want the actual address bar displayed in the browser to update.

标签: url iframe
2条回答
戒情不戒烟
2楼-- · 2019-04-11 19:00

Yes, you can, but it's not a straightforward solution and it has some limitations

changing

You can use Web API messages and history API together to get what you want.

Example

Jsfiddle

redirecting

You can use the example above and replace the push history with a window.location.replace

Please consider the snippet as a hint to get what you want. The example above is not well thought for security (i.e. iframe script is sending messages to the parent, irrespective of its origin).

查看更多
你好瞎i
3楼-- · 2019-04-11 19:07

This sentence is here to help me reach the 30 character minimum. Ignore this and read the next sentence for your answer:

No.

UPDATE:

"Changing" and "Redirecting" are two different things. You need to clarify which it is. "Changing" the address bar is impossible. "Redirecting" IS possible.

Clicking on a standard link from within an iframe will not affect the topmost window on its own. A quick example of a Javascript redirect within an iframe would be something like this:

TOP WINDOW:

<html>
<head></head>
<body>
    <iframe src="http://yoursite.com/iframe_test.html" />
</body>

IFRAME TEST:

<html>
<head>
    <script>
    window.onload = ready;
    function ready()
    {
        document.getElementById("link1").onclick = linkClick;
        document.getElementById("link2").onclick = linkClick;
    }
    function linkClick(e)
    {
        e.preventDefault();
        window.top.location.href = this.href;
    }
    </script>
</head>
<body>
    <a id="link1" href="http://youtube.com">Link1</a>
    <a id="link2" href="http://facebook.com">Link2</a>
</body>

EXPLANATION:

Without the Javascript in place, what will happen when you click on a link in an iframe is that you will remain on the original page and the iframe will be redirected to the link you've clicked on. Using Javascript within an iframe in this fashion can force the topmost frame to redirect.

I would highly discourage relying on this in any way. It's sloppy programming in general, and I would stay away from iframes altogether if possible.

查看更多
登录 后发表回答