代码之家  ›  专栏  ›  技术社区  ›  Konrad

阻止iframe使用javascript加载页面

  •  18
  • Konrad  · 技术社区  · 15 年前

    在javascript中,有没有一种方法可以在加载页面的过程中停止iframe?我需要这样做的原因是我有一个后台iframe流数据从一个Web服务器(通过一个comet风格的机制)和我需要能够切断连接在任意。

    欢迎有任何想法。

    6 回复  |  直到 7 年前
        1
  •  30
  •   Chris Van Opstal    15 年前

    对于firefox/safari/chrome,您可以使用window.stop():

    window.frames[0].stop()
    

    对于IE,可以对document.execcommand(“stop”)执行相同的操作:

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

    对于跨浏览器解决方案,您可以使用:

    if (navigator.appName == 'Microsoft Internet Explorer') {
      window.frames[0].document.execCommand('Stop');
    } else {
      window.frames[0].stop();
    }
    
        2
  •  13
  •   Alex    13 年前

    整个代码应该是这样的(Unbenorton的行缺少一个括号)

    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);
    }
    
        3
  •  1
  •   devside    11 年前

    仅仅是

    document.getElementById("myiframe").src = '';
    
        4
  •  0
  •   CommonSenseCode    7 年前

    非常容易:

    1)获取您不想加载的iframe或img:

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

    2)然后您可以将src属性替换为about.blank:

    myIframe.src = 'about:blank'
    

    这就是全部。


    如果您希望在发生某些事件时在feature中的某个时间加载iframe或image,那么只需将src变量存储在 dataset :

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

    现在,您可以在需要时轻松使用它:

    myIframe.src = myIframe.dataset.srcBackup
    
        5
  •  0
  •   Hashbrown    7 年前

    如果只有对元素的引用,则需要使用 .contentX 得到 document / window 运行已接受的答案。
    对于动态添加的iframe元素,还需要检查iframe是否实际具有文档。

    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');
    }
    
        6
  •  -1
  •   Shakir K Moideen    10 年前

    不支持IE

    <script>
    function stopit() {
    window.stop();
    
    };
    </script>
    
    
    <a href="#" onclick="stopit()" class="Stop" title="Stop"></a>