问题
I'm using setInterval inside an iframe, and I need to be able to stop it from the parent window, and it doesn't seem to be working. I'm assigning a global variable ('modelViewRefresh') to the setInterval event to be accessed from the parent.
I'm using this code in the parent to try and trigger clearInterval, but it doesn't seem to be working:
var modelViewRefresh = document.getElementById(widget_id + '_iframe').contentWindow['modelViewRefresh'];
console.log("modelViewRefresh=" + modelViewRefresh); // this equals 2 for some reason
clearInterval( modelViewRefresh );
I'm even trying this directly:
clearInterval( document.getElementById(widget_id + '_iframe').contentWindow['modelViewRefresh'] );
I've opened the iframe in a window of its own to verify that the variable is being created (by looking in the DOM via Firebug). FYI it's not a different domain...
I'm mainly using jQuery elsewhere, but read somewhere that it's best to use 'raw' javascript in this instance. So I'm open to a jQuery solution too.
Any ideas? Maybe I am going about it wrong...
PS. I'd also like to be able to start the 'refresh' again from the parent.
回答1:
Iframes have their own window
object, meaning even if a variable is global in the iframe, it won't be accessible in the parent because parent and iframe do not share the same window
.
If you want to invoke a function in the iframe from the parent, I suggest you have a look at JSChannel or the jQuery postMessage plugin. It might be what you are looking for.
回答2:
Both clearInterval
and clearTimeout
require the iframe name
when called from outside the iframe.
HTML Example : <iframe name="iframe_0"></iframe>
JS Example :
iframe_0.clearInterval(modelViewRefresh)
To restart from the parent : modelViewRefresh=iframe_0.setInterval(do_this,1000)
来源:https://stackoverflow.com/questions/32776950/need-to-clearinterval-in-iframe-from-parent-and-its-not-working