Stopping a iframe from loading a page using javascript

前端 未结 6 516
情话喂你
情话喂你 2020-12-01 12:36

Is there a way in javascript of stopping an iframe in the middle of loading a page? The reason I need to do this is I have a background iframe streaming data from a web serv

相关标签:
6条回答
  • 2020-12-01 13:00

    Merely,

    document.getElementById("myiframe").src = '';
    
    0 讨论(0)
  • 2020-12-01 13:00

    If you only have a reference to the element, you need to use .contentX to get the document/window to run the accepted answer.
    Checking that the iframe actually has a document is also necessary for dynamically added iframe elements.

    function stopIframe(element) {
        var doc = element.contentDocument;
        //iframes wont have a document if they aren't loading/loaded
        //check so JS wont throw
        if (!doc)
            return;
    
        //try for modern browsers
        if (doc.defaultView.stop)
            doc.defaultView.stop();
        //fallback for IE
        else
            doc.execCommand('Stop');
    }
    
    0 讨论(0)
  • 2020-12-01 13:04

    not support in IE

    <script>
    function stopit() {
    window.stop();
    
    };
    </script>
    
    
    <a href="#" onclick="stopit()" class="Stop" title="Stop"></a>
    
    0 讨论(0)
  • 2020-12-01 13:07

    The whole code should be like this, (unclenorton's line was missing a bracket)

    if (typeof (window.frames[0].stop) === 'undefined'){
        //Internet Explorer code
        setTimeout(function() {window.frames[0].document.execCommand('Stop');},1000);
    }else{
        //Other browsers
        setTimeout(function() {window.frames[0].stop();},1000);
    }
    
    0 讨论(0)
  • 2020-12-01 13:12

    For FireFox/Safari/Chrome you can use window.stop():

    window.frames[0].stop()
    

    For IE, you can do the same thing with document.execCommand('Stop'):

    window.frames[0].document.execCommand('Stop')
    

    For a cross-browser solution you could use:

    if (navigator.appName == 'Microsoft Internet Explorer') {
      window.frames[0].document.execCommand('Stop');
    } else {
      window.frames[0].stop();
    }
    
    0 讨论(0)
  • 2020-12-01 13:14

    Very easy:

    1) Get the iframe or img you don't want to load:

    let myIframe = document.getElementById('my-iframe')
    

    2) Then you can just replace src attribute to about.blank:

    myIframe.src = 'about:blank'
    

    That's all.


    If you wanted to load the iframe or image at a time in feature when some event happens then just store the src variable in dataset:

    myIframe.dataset.srcBackup = myIframe.src
    // then replace by about blank
    myIframe.src = 'about:blank'
    

    Now you can use it when needed easily:

    myIframe.src = myIframe.dataset.srcBackup
    
    0 讨论(0)
提交回复
热议问题