How to force Chrome to NOT open SaveAs Dialog when downloading a URL?

后端 未结 2 1281
一整个雨季
一整个雨季 2021-02-14 10:40

Chrome Build: the newest, 33+

A Chrome Extension extracts certain urls from currently viewed site and then downloads a subset of them (quite often hundreds of files).

2条回答
  •  心在旅途
    2021-02-14 11:14

    Edit : I've added complete sample code for multiple file downloads which doesn't show SaveAs Dialog.

    You can achieve this by using chrome.downloads API.

    manifest.json

    {
      "description": "Multiple file downloads without showing SaveAs Dialog",
      "background": {
         "scripts": [ "background.js" ],
         "persistent" : true
      },
      "content_scripts": [{
         "js": [ "content_script.js"],
         "matches": [ "" ],
         "run_at": "document_start"
      }],
      "manifest_version": 2,
      "name": "MultipleFileDownloads",
      "permissions": [ "downloads" ],
      "short_name": "MFD",
      "version": "0.0.0.1"
    }
    

    content_script.js

    var DOWNLOAD_LIMIT = 100;
    
    function downloadURL(url, filename, callback){
        chrome.runtime.sendMessage({
            download_url : url,
            filename : filename
        },function(){
            if(typeof callback == 'function'){
                callback();
            }
        })
    }
    
    function simulateFileDownload(i){
        if(i > DOWNLOAD_LIMIT){
            document.getElementById('download_btn').disabled = false;
            return false;
        }
        var blob = new Blob(['This is sample file '+i], {type:'text/plain'});
        var url = URL.createObjectURL(blob);
        downloadURL(url,'Sample-'+i+'.txt',function(){
            URL.revokeObjectURL(url);
            i++;
            simulateFileDownload(i);
        })
    }
    
    window.onload = function(){
        var btn = document.createElement('button');
        btn.id = 'download_btn';
        btn.style.cssText = 'position:fixed;top:10px;left:10px;width:140px;height:30px;z-index:1000000;';
        btn.textContent = 'Download Files';
        document.body.appendChild(btn);
        btn.addEventListener('click',function(){
            this.disabled = true;
            simulateFileDownload(0);
        })
    }
    

    background.js

    chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
        if(message.download_url){
            chrome.downloads.download({
                url : message.download_url,
                filename : message.filename,
                saveAs : false
            }
        }
    });
    

提交回复
热议问题