Tampermonkey® by Jan Biniok

GM_download(details), GM_download(url, name)

GM_download allows userscripts to download a file from a specified URL and save it to the user's local machine.

The GM_download function takes the following parameters:

details can have the following attributes:

  • url: The URL of the file to download or a Blob or File objectv5.4.6226+. In case of a string, this must be a valid URL and must point to a file that is accessible to the user.
  • name: The name to use for the downloaded file. This should include the file's extension, such as .txt or .pdf. For security reasons the file extension needs to be whitelisted at Tampermonkey's options page
  • headers: An object containing HTTP headers to include in the download request. See GM_xmlhttpRequest for more details.
  • saveAs: A boolean value indicating whether to use the user's default download location, or to prompt the user to choose a different location. This option works in browser API mode only.
  • conflictAction: A string that control what happens when a file with this name already exists. This option works in browser API mode only. Possible values are uniquify, overwrite and prompt. Please check this link for more details.
  • onload: A function to call when the download has completed successfully.
  • onerror: A function to call if the download fails or is cancelled.
  • onprogress A callback to be executed if this download made some progress.
  • ontimeout A callback to be executed if this download failed due to a timeout.

The download argument of the onerror callback can have the following attributes:

  • error: error reason
    • not_enabled - the download feature isn't enabled by the user
    • not_whitelisted - the requested file extension is not whitelisted
    • not_permitted - the user enabled the download feature, but did not give the downloads permission
    • not_supported - the download feature isn't supported by the browser/version
    • not_succeeded - the download wasn't started or failed, the details attribute may provide more information
  • details: detail about that error

Returns an object with the following property:

  • abort: A function which can be called to cancel this download.

If GM.download is used it returns a promise that resolves to the download details and also has an abort function.

Depending on the download mode GM_info provides a property called downloadMode which is set to one of the following values: native, disabled or browser.

GM_download("http://example.com/file.txt", "file.txt");

const download = GM_download({
    url: "http://example.com/file.txt",
    name: "file.txt",
    saveAs: true
});

// cancel download after 5 seconds
window.setTimeout(() => download.abort(), 5000);

Note: The browser might modify the desired filename. Especially a file extension might be added if the browser finds this to be safe to download at the current OS.