Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

window.open被拦截的问题 #16

Open
Jeffersondyj opened this issue Jul 24, 2018 · 0 comments
Open

window.open被拦截的问题 #16

Jeffersondyj opened this issue Jul 24, 2018 · 0 comments

Comments

@Jeffersondyj
Copy link
Owner

Jeffersondyj commented Jul 24, 2018

背景:在chrome的安全机制里面,非用户触发的window.open方法,是会被拦截的
原因:非用户行为导致的新窗口打开会触发浏览器的安全拦截机制,需要用户授权不拦截才能打开
那么,具体哪些场景下,会被拦截或者不被拦截呢?我们来看——

场景篇

$('#btn').click(() => { window.open('不会拦截'); });

而ajax的回调,会被拦截

ajax.request(params).then(() => { window.open('惨遭拦截'); });

那么,我们就重点针对这种场景做方案。

尝试篇

function newWindow(url) { 
    var a = document.createElement('a'); 
    a.setAttribute('href', url); 
    a.setAttribute('target', '_blank');
    document.body.appendChild(a);
    a.click(); 
}

贴一段简短的代码,mock一个a标签,后续可以优化比如说removeChild
运行一下,结果不起作用。

ok,我们换一个思路:

var tempWindow = window.open('', '_blank', '');
tempWindow.location.href = 'http://www.baidu.com';

依然不行。我们得到启发,既然是ajax回调里面不能open,我放在ajax调用之前先open好window呢?

解决篇

var win = window.open('');
win.document.write('文件下载中,请耐心等待...');
ajax.request(params).then(res => {
    win.location.href = res.fileName;
}, () => {
    win.close();
    // 母页面报错TODO
});

然而有一个问题,打开的新页面在下载成功的情况下,不能自动关闭。如果直接在win.location.href后面直接win.close(),会导致下载不能正常进行。用win.onload也无效。

为了追求极致,思来想去,还是决定用iframe来解决~

function download(url) {
    var divId = '__DownloadContainer__';
    var iframeId = '__DownloadIframe__';
    var div = document.getElementById(divId);
    if (!div) {
        div = document.createElement('div');
        div.id = divId;
        div.innerHTML = '<iframe id="' + iframeId
            + '" name="' + iframeId + '"></iframe>';
        div.style.display = 'none';
        document.body.appendChild(div);
    }
    div.getElementsByTagName('iframe')[0].src = url;
}

ajax.request(params).then(res => {
    download(res.fileName);
}, () => {
    // 母页面报错TODO
});

测一下跨浏览器兼容性,无错!大功告成。本篇博客比较简短,可能读者你早就知道这个技巧了~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant