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()
}
相關文章
相關標籤/搜索