I have a site with an iframe in it, both parent and iframe pages are owned by me on my domain. I am trying to make it so that when a specific page is navigated to in that iframe (or any page containing a certain string in its URL), a function is called. I am pretty sure I need to use location.href
since src
retains its original value no matter what you do in the iframe. Right now I am just testing by trying to get an alert to show up. So far I have tried this:
if(
document.getElementById("myiframe").contentWindow.location.href.indexOf("command") > -1) {
alert("your iframe url contains the phrase command");
}
Nothing happens when I use this, nothing shows up in the console, etc. What am I doing wrong? Thanks.
(Answering my own question because the actual answer was through comments on the question)
It made much more sense to just use postMessage. I simply added a postMessage in the <head>
of the iframe:
<script>parent.postMessage("start", "*");</script>
...and an EventListener to in the <head>
of the parent page, to listen for the message:
<script>
window.addEventListener("message", function(e){
if(e.data == "start") stopwatch.start();
}, false);
</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.