0

I have an iframe. I want to create a loop in Javascript that monitors the iframe's URL. So what I want is something like this:

while(1){
    if(iframe.src == "foo"){
        iframe.src = "bar"
    }
}

What's the correct way to do this (ideally without jQuery etc)?

Chris
  • 1,090
  • 2
  • 11
  • 22
  • You totally must not use a loop for this. Try to find if there is not some kind of event you can attach a listener to. Such a loop would hog the whole browser. – MightyPork Jul 13 '14 at 20:11
  • I would avoid `while(1){...}`..... – 1252748 Jul 13 '14 at 20:11
  • Just to be clear, I know that while() is not the right way to do this. Just trying to demonstrate the functionality I want. – Chris Jul 13 '14 at 20:12
  • 2
    The question is, why and how would the URL change, that's the event you have to hook into – adeneo Jul 13 '14 at 20:14
  • Posted an answer on the question that this is marked a duplicate of. http://stackoverflow.com/a/24726977/592253 – Xotic750 Jul 13 '14 at 21:01

1 Answers1

0

If you have an infinite loop you have to stop it manually using break:

while (1) {
    if(...) {
        ...
        break; //exit loop
    }
}

Is this what you wanted to ask? Feel free to ask any further question.

Edit:

The solution I would choose is creating an own event to listen for and a function to trigger the event if needed:

var iframeSrcChangeEvt = new Event("iframeSrcChanged"); //create event
document.querySelector("iframe").addEventListener("iframeSrcChanged",function() { //add event listener to the iframe
    this.src = "bar"; //change src as you need it
    this.removeEventListener("iframeSrcChanged"); //remove listener if fired
    clearInterval(monitorIframe); //stop monitoring the iframe
});

var monitorIframe = setInterval(function() { //set an interval to monitor the iframe
    var iframe = document.querySelector("iframe");
    if(iframe.src == "foo") {
        iframe.dispatchEvent(iframeSrcCHangeEvt); //fire event
    }
 },500);

I think this solution is better because you are able to add more than one iframe to monitor if you adapt that code.

SVSchmidt
  • 6,269
  • 2
  • 26
  • 37