diff --git a/js/background.js b/js/background.js index 0471d4d4f..a88a53d40 100644 --- a/js/background.js +++ b/js/background.js @@ -63,10 +63,10 @@ function downloadFile(url, filename, conflictAction, callback) { } function onMessage(message, sender, callback) { switch (message.action) { - case 'downloadFile': + case 'downloadFileBlob': // direct URL download through Chrome API might be prohibited (e.g: Pixiv) // workaround: - // 1. obtain ArrayBuffer from XHR request (GET URL) + // 1. obtain ArrayBuffer from XHR request (GET URL) // 2. create Blob from ArrayBuffer // 3. download Blob URL through Chrome API if (options.enableDownloads) { @@ -84,6 +84,39 @@ function onMessage(message, sender, callback) { } }); } + case 'downloadFile': + + function onChanged(delta) { + if (!delta) return; + if (delta.id != currentId) return; + if (delta.state && delta.state.current !== 'in_progress') { + chrome.downloads.onChanged.removeListener(onChanged); + // call callback only if download failed + if (delta.state.current !== 'complete') { + callback(); + } + } + } + + if (options.enableDownloads) { + var currentId; + chrome.downloads.onChanged.addListener(onChanged); + chrome.downloads.download({url: message.url, filename: message.filename, conflictAction: message.conflictAction, saveAs: false}, id => { currentId = id }); + return true; + } else { + chrome.permissions.request({ + permissions: ['downloads'] + }, function (granted) { + if (granted) { + var currentId; + chrome.downloads.onChanged.addListener(onChanged); + chrome.downloads.download({url: message.url, filename: message.filename, conflictAction: message.conflictAction, saveAs: false}, id => { currentId = id }); + return true; + } else { + return false; + } + }); + } case 'ajaxGet': ajaxRequest({url:message.url, response:message.response, method:'GET', headers:message.headers}, callback); return true; diff --git a/js/hoverzoom.js b/js/hoverzoom.js index 0d5c2752a..2cfb30a82 100644 --- a/js/hoverzoom.js +++ b/js/hoverzoom.js @@ -2799,12 +2799,18 @@ var hoverZoom = { cLog('filename: ' + filename); } - chrome.runtime.sendMessage({ - action: 'downloadFile', - url: url, - filename: filename, - conflictAction: 'uniquify' - }, callback); + // 1st attempt to download file (Chrome API) + chrome.runtime.sendMessage({action:'downloadFile', + url:url, + filename:filename, + conflictAction:'uniquify'}, + function() { + // 2nd attempt (blob + Chrome API) + chrome.runtime.sendMessage({action:'downloadFileBlob', + url:url, + filename:filename, + conflictAction:'uniquify'}); + }); } // 4 types of media can be saved to disk: image, video, audio, playlist