简体   繁体   中英

How can I change the domain the scr of an iFrame based on the parent window's URL?

How can I change the scr="" attribute of an iFrame based on the current window's URL? Here's an example of what I'm trying to do: If the parent window's URL is "/i/foo" the iFrame's scr should be "/i/new/foo" . If it's "/i/cake" then the scr needs to be "/i/new/cake" . If the parent window's URL is just "/i" then the iFrame's scr needs to be "/i/new" .
How can I achieve this using php, javascript, or some other method?
I believe there are some issues when using php with an iframe.

You can put some javascript in the top level page that can examine the URL of its page and then set the URL of the iframe:

var iframeURL = window.location.href.replace(/\/[^\/]+\/?$/, "/new$&");
document.getElementById("myIframe").src = iframeURL;

This finds the last segment of the URL and then inserts /new in front of it and then finds the iframe and sets it's .src property. You would need to insert this script AFTER the iframe object in the page (or wait for the document to be loaded before running the script) and you would need to attach an id to the iframe so it can be found.

<iframe id="myIframe"></iframe>
<script>
var iframeURL = window.location.href.replace(/\/[^\/]+\/?$/, "/new$&");
document.getElementById("myIframe").src = iframeURL;
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM