2020-08-14 08:46:34 +02:00
|
|
|
import browser from '../scripts/browser';
|
2018-10-23 01:05:09 +03:00
|
|
|
|
2020-07-27 20:06:11 +01:00
|
|
|
function fallback(urls) {
|
2020-10-07 21:12:14 +09:00
|
|
|
let i = 0;
|
2019-01-10 15:39:37 +03:00
|
|
|
|
2020-07-27 20:06:11 +01:00
|
|
|
(function createIframe() {
|
2020-10-07 21:12:14 +09:00
|
|
|
const frame = document.createElement('iframe');
|
2020-07-27 20:06:11 +01:00
|
|
|
frame.style.display = 'none';
|
|
|
|
frame.src = urls[i++];
|
|
|
|
document.documentElement.appendChild(frame);
|
2019-01-10 15:39:37 +03:00
|
|
|
|
2020-07-27 20:06:11 +01:00
|
|
|
// the download init has to be sequential otherwise IE only use the first
|
2020-10-08 00:47:23 +09:00
|
|
|
const interval = setInterval(function () {
|
2020-07-27 20:06:11 +01:00
|
|
|
if (frame.contentWindow.document.readyState === 'complete' || frame.contentWindow.document.readyState === 'interactive') {
|
|
|
|
clearInterval(interval);
|
2019-01-10 15:39:37 +03:00
|
|
|
|
2020-07-27 20:06:11 +01:00
|
|
|
// Safari needs a timeout
|
|
|
|
setTimeout(function () {
|
|
|
|
frame.parentNode.removeChild(frame);
|
|
|
|
}, 1000);
|
2019-01-10 15:39:37 +03:00
|
|
|
|
2020-07-27 20:06:11 +01:00
|
|
|
if (i < urls.length) {
|
|
|
|
createIframe();
|
2019-01-10 15:39:37 +03:00
|
|
|
}
|
2020-07-27 20:06:11 +01:00
|
|
|
}
|
|
|
|
}, 100);
|
|
|
|
})();
|
|
|
|
}
|
|
|
|
|
|
|
|
function sameDomain(url) {
|
2020-10-07 21:12:14 +09:00
|
|
|
const a = document.createElement('a');
|
2020-07-27 20:06:11 +01:00
|
|
|
a.href = url;
|
|
|
|
|
2020-08-25 10:12:35 +09:00
|
|
|
return window.location.hostname === a.hostname && window.location.protocol === a.protocol;
|
2020-07-27 20:06:11 +01:00
|
|
|
}
|
2018-10-23 01:05:09 +03:00
|
|
|
|
2020-07-27 20:06:11 +01:00
|
|
|
function download(url) {
|
2020-10-07 21:12:14 +09:00
|
|
|
const a = document.createElement('a');
|
2020-07-27 20:06:11 +01:00
|
|
|
a.download = '';
|
|
|
|
a.href = url;
|
|
|
|
// firefox doesn't support `a.click()`...
|
|
|
|
a.dispatchEvent(new MouseEvent('click'));
|
|
|
|
}
|
2019-01-10 15:39:37 +03:00
|
|
|
|
2020-07-27 20:06:11 +01:00
|
|
|
export default function (urls) {
|
|
|
|
if (!urls) {
|
|
|
|
throw new Error('`urls` required');
|
2018-10-23 01:05:09 +03:00
|
|
|
}
|
|
|
|
|
2020-07-27 20:06:11 +01:00
|
|
|
if (typeof document.createElement('a').download === 'undefined') {
|
|
|
|
return fallback(urls);
|
2018-10-23 01:05:09 +03:00
|
|
|
}
|
2019-01-10 15:39:37 +03:00
|
|
|
|
2020-10-07 21:12:14 +09:00
|
|
|
let delay = 0;
|
2019-01-10 15:39:37 +03:00
|
|
|
|
2020-07-27 20:06:11 +01:00
|
|
|
urls.forEach(function (url) {
|
|
|
|
// the download init has to be sequential for firefox if the urls are not on the same domain
|
|
|
|
if (browser.firefox && !sameDomain(url)) {
|
|
|
|
return setTimeout(download.bind(null, url), 100 * ++delay);
|
2019-01-10 15:39:37 +03:00
|
|
|
}
|
|
|
|
|
2020-07-27 20:06:11 +01:00
|
|
|
download(url);
|
|
|
|
});
|
|
|
|
}
|