js 模拟window.open 打开新窗口

为何要去模拟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()
}
相关文章
相关标签/搜索