乐闻世界logo
搜索文章和话题

Chrome extension: How to save a file on disk

1个答案

1

In developing Chrome extensions, saving files to the user's disk typically involves several steps, primarily through Chrome's download API. Here is a step-by-step guide on how to implement this functionality:

1. Ensure your extension has the necessary permissions

First, declare the downloads permission in your extension's manifest file to use Chrome's download API.

json
{ "name": "My Chrome Extension", "version": "1.0", "permissions": [ "downloads" ], "background": { "scripts": ["background.js"] }, "manifest_version": 2 }

2. Use Chrome's download API

In your extension code (e.g., background.js), call chrome.downloads.download to save a file to disk. This method accepts an object parameter specifying the file URL, save path, filename, and conflict resolution strategy.

javascript
chrome.downloads.download({ url: "http://example.com/path/to/file.txt", // file URL filename: "saved_file.txt", // saved filename conflictAction: 'uniquify' // handling filename conflicts }, function(downloadId) { console.log("Download started with ID: " + downloadId); });

3. Process file content (optional)

If you need to process file content before saving—such as modifying text content or generating a data file—create a Blob object and use URL.createObjectURL to generate a temporary URL for downloading the Blob.

javascript
const content = "This is the modified file content"; const blob = new Blob([content], {type: 'text/plain'}); const url = URL.createObjectURL(blob); chrome.downloads.download({ url: url, filename: "modified_file.txt" }, function(downloadId) { URL.revokeObjectURL(url); // Release the URL object after download console.log("Modified file downloaded with ID: " + downloadId); });

4. User interaction (optional)

Depending on your requirements, you may need to interact with users—for example, allowing them to choose the save path. This can be implemented by adding UI elements (e.g., buttons or forms) in popup.html or options pages.

Example

Suppose you develop an extension where clicking the browser extension icon automatically downloads a processed text file. In this case, listen for the browser icon click event in the background script and execute similar download code:

javascript
chrome.browserAction.onClicked.addListener(function(tab) { const content = "This is the file content generated after clicking the icon"; const blob = new Blob([content], {type: 'text/plain'}); const url = URL.createObjectURL(blob); chrome.downloads.download({ url: url, filename: "onClick_saved_file.txt" }, function(downloadId) { URL.revokeObjectURL(url); console.log("File downloaded on icon click with ID: " + downloadId); }); });

This approach enables Chrome extensions to save files to disk while handling and interacting with data, supporting more advanced functionality.

2024年6月29日 12:07 回复

你的答案