首页 > 技术文章 > js 模拟window.open 打开新窗口

shenjp 2019-05-23 12:28 原文

为什么要去模拟window.open() 打开一个 新的窗口呢,因为有些浏览器默认会拦截 window.open, 当需要函数中打开新窗口时,接可以使用a标签去模拟打开。

/**
* a模拟window.open,不会被浏览器拦截
* @param {String} url        a标签打开的地址
* @param {String} id         a标签的ID
* @param {String} targetType a标签点击打开的方式(当前页面打开还是新窗口打开)
*/
openWindow: (url, targetType = '_blank', id = 'open', download = false) => {
    // 如果存在则删除
    if (document.getElementById(id)) {
        document.body.removeChild(document.getElementById(id))
    }
    const a = document.createElement('a')
    a.setAttribute('href', url)
    if (download) {
        a.setAttribute('download', url)
    }
    a.setAttribute('target', targetType)
    a.setAttribute('id', id)
    document.body.appendChild(a)
    a.click()
}

 

推荐阅读