Javascript Chrome 扩展程序:如何在磁盘上保存文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2153979/
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-08-22 22:58:13  来源:igfitidea点击:

Chrome extension: How to save a file on disk

javascriptgoogle-chromegoogle-chrome-extension

提问by X-Blaster

I'm currently creating an extension for google chrome which can save all images or links to images on the harddrive.

我目前正在为谷歌浏览器创建一个扩展程序,它可以保存所有图像或指向硬盘驱动器上图像的链接。

The problem is I don't know how to save file on disk with JS or with Google Chrome Extension API.

问题是我不知道如何使用 JS 或 Google Chrome 扩展 API 将文件保存在磁盘上。

Have you got an idea ?

你有什么想法吗?

采纳答案by Mohamed Mansour

You can use HTML5 FileSystem featuresto write to disk using the DownloadAPI. That is the only way to download files to disk and it is limited.

您可以使用HTML5 文件系统功能使用下载API写入磁盘。这是将文件下载到磁盘的唯一方法,而且它是有限的。

You could take a look at NPAPI plugin. Another way to do what you need is simply send a request to an external website via XHR POST and then another GET request to retrieve the file back which will appear as a save file dialog.

你可以看看 NPAPI 插件。另一种方法是简单地通过 XHR POST 向外部网站发送请求,然后通过另一个 GET 请求检索文件,该文件将显示为保存文件对话框。

For example, for my browser extension My HangoutsI created a utility to download a photo from HTML5 Canvas directly to disk. You can take a look at the code here capture_gallery_downloader.jsthe code that does that is:

例如,对于我的浏览器扩展My Hangouts,我创建了一个实用程序,用于将照片从 HTML5 Canvas 直接下载到磁盘。你可以看看这里的代码capture_gallery_downloader.js这样做的代码是:

var url = window.webkitURL || window.URL || window.mozURL || window.msURL;
var a = document.createElement('a');
a.download = 'MyHangouts-MomentCapture.jpg';
a.href = url.createObjectURL(dataURIToBlob(data.active, 'jpg'));
a.textContent = 'Click here to download!';
a.dataset.downloadurl = ['jpg', a.download, a.href].join(':');

If you would like the implementation of converting a URI to a Blob in HTML5 here is how I did it:

如果您想要在 HTML5 中将 URI 转换为 Blob 的实现,我是这样做的:

/**
 * Converts the Data Image URI to a Blob.
 *
 * @param {string} dataURI base64 data image URI.
 * @param {string} mimetype the image mimetype.
 */
var dataURIToBlob = function(dataURI, mimetype) {
  var BASE64_MARKER = ';base64,';
  var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
  var base64 = dataURI.substring(base64Index);
  var raw = window.atob(base64);
  var rawLength = raw.length;
  var uInt8Array = new Uint8Array(rawLength);

  for (var i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }

  var bb = new this.BlobBuilder();
  bb.append(uInt8Array.buffer);
  return bb.getBlob(mimetype);
};

Then after the user clicks on the download button, it will use the "download" HTML5 File API to download the blob URI into a file.

然后在用户单击下载按钮后,它将使用“下载”HTML5 文件 API 将 blob URI 下载到文件中。

回答by Allan Ruin

I had long been wishing to make a chrome extension for myself to batch download images. Yet every time I got frustrated because the only seemingly applicable option is NPAPI, which both chrome and firefox seem to have not desire in supporting any longer.

我一直希望为自己制作一个 chrome 扩展程序来批量下载图像。然而,每次我感到沮丧时,因为唯一看似适用的选项是 NPAPI,chrome 和 firefox 似乎都不再希望支持它。

I suggest those who still wanted to implement 'save-file-on-disk' functionality to have a look at this Stackoverflow post, the comment below this post help me a lot.

我建议那些仍然想要实现“磁盘上保存文件”功能的人看看这篇Stackoverflow 帖子,这篇帖子下面的评论对我有很大帮助。

Now since chrome 31+, the chrome.downloadsAPI became stable. We can use it to programmatically download file. If the user didn't set the ask me before every downloadadvance option in chrome setting, we can save file without prompting user to confirm!

现在从 chrome 31+ 开始,chrome.downloadsAPI 变得稳定了。我们可以使用它以编程方式下载文件。如果用户没有ask me before every download在chrome设置中设置高级选项,我们可以保存文件而不提示用户确认!

Here is what I use (at extension's background page):

这是我使用的(在扩展的背景页面):

    // remember to add "permissions": ["downloads"] to manifest.json
    // this snippet is inside a onMessage() listener function
    var imgurl = "https://www.google.com.hk/images/srpr/logo11w.png";
    chrome.downloads.download({url:imgurl},function(downloadId){
        console.log("download begin, the downId is:" + downloadId);
    });

Though it's a pity that chrome still doesn't provide an Eventwhen the download completes.chrome.downloads.download's callback function is called when the download beginsuccessfully (not on completed)

虽然很遗憾 chromeEvent在下载完成时仍然没有提供。chrome.downloads.download下载begin成功时调用的回调函数(未完成时)

The Official documentation about chrome.downloadsis here.

官方文档大约chrome.downloads在这里

It's not my original idea about the solution, but I posted here hoping that it may be of some use to someone.

这不是我对解决方案的最初想法,但我在这里发布希望它可能对某人有用。

回答by sandover

There's no way that I know of to silently save files to the user's drive, which is what it seems like you're hoping to do. I think you can ASK for files to be saved one at a time (prompting the user each time) using something like:

据我所知,没有办法将文件静默保存到用户的驱动器中,这似乎是您希望做的。我认为您可以使用以下内容要求一次保存一个文件(每次提示用户):

function saveAsMe (filename)
{
document.execCommand('SaveAs',null,filename)
}

If you wanted to only prompt the user once, you could grab all the images silently, zip them up in a bundle, then have the user download that. This might mean doing XmlHttpRequest on all the files, zipping them in Javascript, UPLOADING them to a staging area, and then asking the user if they would like to download the zip file. Sounds absurd, I know.

如果您只想提示用户一次,您可以静默抓取所有图像,将它们压缩成一个包,然后让用户下载。这可能意味着对所有文件执行 XmlHttpRequest,用 Javascript 压缩它们,将它们上传到暂存区,然后询问用户是否要下载 zip 文件。听起来很荒谬,我知道。

There are local storage options in the browser, but they are only for the developer's use, within the sandbox, as far as I know. (e.g. Gmail offline caching.) See recent announcements from Google like this one.

浏览器中有本地存储选项,但据我所知,它们仅供开发人员在沙箱内使用。(例如 Gmail 离线缓存。)查看 Google 最近发布的类似这样的公告。

回答by Arnaud Leymet

Consider using the HTML5 FileSystem featuresthat make writing to files possible using Javascript.

考虑使用HTML5文件系统功能,可以使用 Javascript 写入文件。

回答by DrJKL

Google Webstore
Github

Google 网上商店
Github

I made an extension that does something like this, if anyone here is still interested. It uses an XMLHTTPRequest to grab the object, which in this case is presumed to be an image, then makes an ObjectURL to it, a link to that ObjectUrl, and clicks on the imaginary link.

如果这里有人仍然感兴趣,我做了一个扩展,可以做这样的事情。它使用 XMLHTTPRequest 来获取对象(在本例中假定为图像),然后创建指向它的 ObjectURL、指向该 ObjectUrl 的链接,然后单击假想的链接。

回答by pavium

Since Javascript hitch-hikes to your computer with webpages from just about anywhere, it would be dangerous to give it the ability to write to your disk.

由于 Javascript 可以从几乎任何地方通过网页搭便车到您的计算机,因此让它能够写入您的磁盘是很危险的。

It's not allowed. Are you thinking that the Chrome extension will require user interaction? Otherwise it might fall into the same category.

这不被允许。您是否认为 Chrome 扩展程序需要用户交互?否则它可能属于同一类别。