js window.open()下载被拦截解决方案

由于个别浏览器对广告过滤或安全性做的比较严格,会认为window.open()打开的是小广告或者病毒网站,所以就会将其拦截。

解决方案:

        不使用window.open(),使用iframe标签在本页面打开下载,这样就绕过安全拦截。

调用:iframeDownload(url)

代码:

  function iframeDownload (url) {

      const iframe = document.createElement('iframe')

      iframe.style.display = 'none'

      function iframeLoad () {

            console.log('iframe onload')

            const win = iframe.contentWindow

             const doc = win.document

            if (win.location.href === url) {

                  if (doc.body.childNodes.length > 0) {

                        // response is error

                  }

                  iframe.parentNode.removeChild(iframe)

                }

          }

  if ('onload' in iframe) {

    iframe.onload = iframeLoad

  } else if (iframe.attachEvent) {

    iframe.attachEvent('onload', iframeLoad)

  } else {

    iframe.onreadystatechange = function onreadystatechange () {

      if (iframe.readyState === 'complete') {

        iframeLoad()

      }

    }

  }

  iframe.src = ''

  document.body.appendChild(iframe)

  setTimeout(function loadUrl () {

    iframe.contentWindow.location.href = url

  }, 50)

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 6,179评论 0 2
  • 北京2018年4月1日上午,NBA常规赛勇士客战国王的比赛中,发生了令人痛心不已的一幕。比赛进行到第三节还有41...
    Curry_宇阅读 5,031评论 1 1
  • 1. 什么是跨域? 跨域一词从字面意思看,就是跨域名嘛,但实际上跨域的范围绝对不止那么狭隘。具体概念如下:只要协议...
    w_zhuan阅读 3,590评论 0 0
  • 1. 什么是跨域? 跨域一词从字面意思看,就是跨域名嘛,但实际上跨域的范围绝对不止那么狭隘。具体概念如下:只要协议...
    他在发呆阅读 4,212评论 0 0
  • 什么是跨域 跨域,是指浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript实...
    他方l阅读 4,719评论 0 2

友情链接更多精彩内容