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

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

问题描述

我正在创建一个扩展程序,用于从网站下载mp3文件。我正在尝试通过创建一个带有mp3文件链接的新选项卡来实现此目的,但chrome不断在播放器中打开它,而不是下载它。有什么办法可以创建一个弹出窗口让用户保存为文件吗?

快速-forward 3 years,now Google Chrome provides chrome.downloads API (自Chrome 31以来)。


$ b 在清单中声明downloads权限后,你可以用这个调用启动下载:

  chrome.downloads.download({
url:http:/ /your.url/to/download,
文件名:建议/文件名/ with / relative.path//可选
});

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

  var blob = new Blob([array of,parts of,text file], {type:text / plain}); 
var url = URL.createObjectURL(blob);
chrome.downloads.download({
url:url //对象URL可用作下载URL
// ...
});

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


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?

解决方案

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

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
});

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天全站免登陆