使 Chrome 扩展程序下载文件 [英] Making a Chrome Extension download a file

查看:29
本文介绍了使 Chrome 扩展程序下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个扩展程序,用于从网站下载 mp3 文件.我试图通过创建一个带有 mp3 文件链接的新选项卡来做到这一点,但 chrome 一直在播放器中打开它,而不是下载它.有什么办法可以创建一个弹出窗口来要求用户另存为"文件?

I am creating an extension that will download a mp3 file off a website. I am trying to do this by creating a new tab with the link to the mp3 file, but chrome keeps opening it inside the player instead of downloading it. Is there any way I can create a pop-up to ask the user to "save-as" the file?

推荐答案

快进 3 年,现在 Google Chrome 提供 chrome.downloads API(自 Chrome 31 起).

Fast-forward 3 years, and now Google Chrome offers chrome.downloads API (since Chrome 31).

在清单中声明 "downloads" 权限后,可以通过此调用启动下载:

After declaring "downloads" permission in the manifest, one can initiate a download with this call:

chrome.downloads.download({
  url: "http://your.url/to/download",
  filename: "suggested/filename/with/relative.path" // Optional
});

如果要在脚本中生成文件内容,可以使用BlobURL APIs,例如:

If you want to generate the file content in the script, you can use Blob and URL APIs, e.g.:

var blob = new Blob(["array of", " parts of ", "text file"], {type: "text/plain"});
var url = URL.createObjectURL(blob);
chrome.downloads.download({
  url: url // The object URL can be used as download URL
  //...
});

有关更多选项(即另存为对话框、覆盖现有文件等),请参阅文档.

For more options (i.e. Save As dialog, overwriting existing files, etc.), see the documentation.

这篇关于使 Chrome 扩展程序下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆