如何使用 JavaScript 设置 chrome 扩展的文件下载位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20988041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:46:25  来源:igfitidea点击:

How to set the file download location for chrome extension Using JavaScript?

javascriptgoogle-chromegoogle-chrome-extension

提问by Arvind Anandala

Hi i am downloading selected links using chrome extension but I can't set downloads location. All the urls downloaded to default location of chrome. i know we can't do it because of security reason. can we prompt directory chooser dialog in chrome extension popup from here user can select the Download path.Need any information from my side let me know.

嗨,我正在使用 chrome 扩展程序下载选定的链接,但我无法设置下载位置。所有 url 下载到 chrome 的默认位置。我知道出于安全原因我们不能这样做。我们能否在 chrome 扩展弹出窗口中提示目录选择器对话框,用户可以从这里选择下载路径。需要我这边的任何信息让我知道。

Is this possible at all? Any suggestions on how to go about it?

这可能吗?关于如何去做的任何建议?

Thanks in advance My code

提前致谢 我的代码

function downloadFile(url, onSuccess,arrayOfUrl,zip) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = "blob";
    xhr.onreadystatechange = function () {

        if (xhr.readyState == 4) {
            if (onSuccess)
            {
            onDownloadComplete(xhr.response, arrayOfUrl,zip)
             }
}
}
xhr.send("null");
}
function onDownloadComplete(blobData,urls,zip ){
    if (count < urls.length) {
        blobToBase64(blobData, function(binaryData){
                var fileName = urls[count].substring(urls[count].lastIndexOf('/')+1);
                 zip.file(fileName+".docx", binaryData, {base64: true}); 
                if (count < urls.length -1){
                    count++;
                    downloadFile(urls[count], onDownloadComplete, urls,zip);

                }
                else {

                    var content = zip.generate();

                     var zipName = 'download.zip';
                var a = document.createElement('a'); 
                a.href = "data:application/zip;base64," + content;
                a.download = zipName;
                a.click();
                  count = 0;

                }
            });
    }
}

popup.js

弹出窗口.js

function onDownloadComplete(blobData,urls,zip ){


    if (count < urls.length) {
        blobToBase64(blobData, function(binaryData){
                // add downloaded file to zip:
                var fileName = urls[count].substring(urls[count].lastIndexOf('/')+1);
               // zip.file(fileName, binaryData, {base64: true});
                 zip.file(fileName+".docx", binaryData, {base64: true}); //file"+count+".docx"
                if (count < urls.length -1){
                    count++;
                    downloadFile(urls[count], onDownloadComplete, urls,zip);

                }
                else {
                chrome.runtime.getBackgroundPage(function () {
            zipAndSaveFiles(zip);});



            }

            });
    }
}

**background.js**

function zipAndSaveFiles(zip)
{
    var content = zip.generate(zip);
                   var zipName = 'download.zip';
                   var dataURL = 'data:application/zip;base64,' + content;
                   chrome.downloads.download({
                   url:      dataURL,
                   filename: zipName,
                    saveAs:   true
                    });
}

采纳答案by gkalpak

Since you are generating and downloading just one ZIP file, you can use the chrome.downloads.download()method. E.g.:

由于您只生成和下载一个 ZIP 文件,因此您可以使用该chrome.downloads.download()方法。例如:

var content = zip.generate();
var zipName = 'download.zip';
var dataURL = 'data:application/zip;base64,' + content;
chrome.downloads.download({
    url:      dataURL,
    filename: zipName,
    saveAs:   true
});
count = 0;


If you omit the display of a SaveAsdialog, then you can only specify a file name that is inside the user-defined download folder or in a subfolder of it.

如果省略SaveAs对话框的显示,则只能指定用户定义的下载文件夹内或其子文件夹中的文件名。



Regarding the issue with the popup (see comment below): You should call the function from your background-page, not the popup. E.g. you could use chrome.runtime.sendMessage/onMessageto pass a message to your background-page:

关于弹出窗口的问题(请参阅下面的评论):您应该从后台页面而不是弹出窗口调用该函数。例如,您可以使用chrome.runtime.sendMessage/onMessage将消息传递到您的后台页面:

In background.js:

background.js 中

...
function zipAndSaveFiles(...) { ... }
chrome.runtime.onMessage.addListener(function(msg, sender) {
    if ((msg.action === 'zipAndSave')
            && (msg.params !== undefined)) {
        zipAndSaveFiles(msg.params);
    }
});

In popup.js:

popup.js 中

...
chrome.runtime.sendMessage({
    action: 'zipAndSave',
    params: ['url1', 'url2', 'url3']
});