Working with files

Your browser extension may need to work with files to deliver its full functionality. This article looks at the five mechanisms you have for handling files:

  • Downloading files to the user’s selected download folder.
  • Opening files using a file picker on a web page.
  • Opening files using drag and drop onto a web page.
  • Storing files or blobs locally with IndexedDB using the idb-file-storage library.
  • Passing files to a native application on the user’s computer.

For each of these mechanisms, we introduce their use with references to the relevant API documentation, guides, and any examples that show how to use the API.

Download files using the downloads API

This mechanism enables you to get a file from your website (or any location you can define as a URL) to the user’s computer. The key method is downloads.download() , which in its simplest form accepts a URL and downloads the file from that URL to the user’s default downloads folder:

browser.downloads.download({url: "https://example.org/image.png"})

					

You can let the user download to a location of their choice by specifying the saveAs 参数。

注意: 使用 URL.createObjectURL() you can also download files and blobs defined in your JavaScript, which can include local content retrieved from IndexedDB.

The downloads API also provides features to cancel, pause, resume, erase, and remove downloads; search for downloaded files in the download manager; show downloaded files in the computer’s file manager; and open a file in an associated application.

To use this API, you need to have the "downloads" API permission specified in your manifest.json 文件。

范例: Latest download API reference: downloads API

Open files in an extension using a file picker

If you want to work with a file from the user’s computer one option is to let the user select a file using the computer’s file browser. Either create a new page or inject code into an existing page to use the file type of the HTML input element to offer the user a file picker. Once the user has picked a file or files, the script associated with the page can access the content of the file using the DOM File API , in the same way a web application does.

范例: Imagify Guide: 使用来自 Web 应用程序的文件 API references: HTML input element | DOM File API

注意: If you want to access or process all the files in a selected folder, you can do so using <input type="file" webkitdirectory="true"/> to select the folder and return all the files it contains.

Open files in an extension using drag and drop

The Web Drag and Drop API offers an alternative to using a file picker. To use this method, establish a ‘drop zone’ that fits with your UI, then add listeners for the dragenter , dragover ,和 drop events to the element. In the handler for the drop event, your code can access any file dropped by the user from the object offered by the dataTransfer property using DataTransfer.files . Your code can then access and manipulate the files using the DOM File API .

范例: Imagify Guides: 使用来自 Web 应用程序的文件 | File drag and drop API references: DOM File API

Store files data locally using the IndexedDB file storage library

If your extension needs to save files locally, the idb-file-storage library provides a simple Promise-based wrapper to the IndexedDB API to aid the storage and retrieval of files and blobs.

On Firefox, this library also provides a Promise-based API wrapper for the non-standard IDBMutableFile API. (The IDBMutableFile API enables extensions to create and persist an IndexedDB database file object that provides an API to read and change the file’s content without loading all the file into memory.)

The key features of the library are:

getFileStorage

返回 IDBFileStorage instance, creating the named storage if it does not exist.

IDBFileStorage

Provides the methods to save and retrieve files, such as:

  • list to obtain an optionally filtered list of file in the database.
  • put to add a file or blob to the database.
  • get to retrieve a file or blob from the database.
  • remove to delete a file or blob from the database.

Store Collected Images example illustrates how to use most of these features. (IDBMutableFile is not included, but you can find examples in the idb-file-storage examples along with a number of other examples of the library in action).

The Store Collected Images example lets users add images to a collection using an option on the image context menu. Selected images are collected in a popup and can be saved to a named collection. A toolbar button ( browserAction ) opens a navigate collection page, on which the user can view and delete saved images, with a filter option to narrow choices. See the example in action .

The workings of the library can be understood by viewing image-store.js in /utils/:

Creating the store and saving the images

async function saveCollectedBlobs(collectionName, collectedBlobs) {
 const storedImages = await getFileStorage({name: "stored-images"});
 for (const item of collectedBlobs) {
    await storedImages.put(`${collectionName}/${item.uuid}`, item.blob);
 }
}

					

saveCollectedBlobs is called when the user clicks save in the popup and has provided a name for the image collection.

首先, getFileStorage creates, if it does not exist already, or retrieves the IndexedDB database "stored-images"  to the object storedImages . storedImages.put() then adds each collected image to the database, under the collection name, using the blob’s unique id (the file name).

If the image being stored has the same name as one already in the database, it is overwritten. If you want to avoid this, query the database first using imagesStore.list() with a filter for the file name; and, if the list returns a file, add a suitable suffix to the name of the new image to store a separate item.

Retrieving stored images for display

export async function loadStoredImages(filter) {

const

 imagesStore

=


await


getFileStorage


(


{


名称


:


"stored-images"


}


)


;


let

 listOptions

=

 filter

?


{


包括


:

 filter

}


:


undefined


;


const

 imagesList

=


await

 imagesStore

.


list


(

listOptions

)


;


let

 storedImages

=


[


]


;


for


(


const

 storedName

of

 imagesList

)


{


const

 blob

=


await

 imagesStore

.


get


(

storedName

)


;

storedImages

.


push


(


{

storedName

,


blobUrl


:


URL


.


createObjectURL


(

blob

)


}


)


;


}


return

 storedImages

;


}


					

loadStoredImages() is called when the user clicks view or reload in the navigate collection page. getFileStorage() opens the "stored-images"  database, then imagesStore.list() gets a filtered list of the stored images. This list is then used to retrieve images with imagesStore.get() and build a list to return to the UI.

Note the use of URL.createObjectURL(blob) to create a URL that references the image blob. This URL is then used in the UI ( navigate-collection.js collection.js ) to display the image.

Delete collected images

async function removeStoredImages(storedImages) {

const

 imagesStore

=


await


getFileStorage


(


{


名称


:


"stored-images"


}


)


;


for


(


const

 storedImage

of

 storedImages

)


{


URL


.


revokeObjectURL


(

storedImage

.

blobUrl

)


;


await

 imagesStore

.


remove


(

storedImage

.

storedName

)


;


}


}


					

removeStoredImages() is called when the user clicks delete in the navigate collection page. Again, getFileStorage() opens the "stored-images"  database then imagesStore.remove() removes each image from the filtered list of images.

Note the use of URL.revokeObjectURL() to explicitly revoke the blob URL. This enables the garbage collector to free the memory allocated to the URL. If this is not done, the memory will not get returned until the page on which it was created is closed. If the URL was created in an extension’s background page, this is not unloaded until the extension is disabled, uninstalled, or reloaded, so holding this memory unnecessarily could affect browser performance. If the URL is created in an extension’s page (new tab, popup, or sidebar) the memory is released when the page is closed, but it is still a good practice to revoke the URL when it is no longer needed.

Once the blob URL has been revoked, any attempt to load it will result in an error. For example, if the blob url was used as the SRC attribute of an IMG tag, the image will not load and will not be visible. It is therefore good practice to remove any revoked blob URLs from generated HTML elements when the blob URL is revoked.

范例: Store Collected Images API References:   idb-file-storage library

注意: You can also use the full Web IndexedDB API to store data from your extension. This can be useful where you need to store data that isn’t handled well by the simple key/value pairs offered by the DOM 存储 API .

Process files in a local app

Where you have a native app or want to deliver additional native features for file processing, use native messaging to pass a file to a native app for processing.

You have two options:

Connection-based messaging

Here you trigger the process with runtime.connectNative() ,其返回 runtime.Port object. You can then pass a JSON message to the native application using the postMessage() function of Port . Using the onMessage.addListener() function of Port you can listen for messages from the native application. The native application is opened if it is not running when runtime.connectNative() is called and the application remains running until the extension calls Port.disconnect() or the page that connected to it is closed.

Connectionless messaging

Here you use runtime.sendNativeMessage() to send a JSON message to a new, temporary instance of the native application. The browser closes the native application after receiving any message back from the native application.

To add the file or blob you want the native application to process use JSON.stringify() .

To use this method the extension must request the "nativeMessaging" permission or optional permission 在其 manifest.json file. Where optional permission is used, remember to check that permission has being granted and where necessary request permission from the user with the permissions API. Reciprocally, the native application must grant permission for the extension by including its ID in the "allowed_extensions" field of the app manifest.

范例: Native Messaging (illustrates simple messaging only) Guides: Native messaging API references: runtime API

Found a problem with this page?

最后修改: , 由 MDN 贡献者

  1. 浏览器扩展名
  2. 快速入门
    1. What are extensions?
    2. Your first extension
    3. Your second extension
    4. Anatomy of an extension
    5. Example extensions
    6. What next?
  3. 概念
    1. Using the JavaScript APIs
    2. Content scripts
    3. Match patterns
    4. Working with files
    5. 国际化
    6. Content Security Policy
    7. Native messaging
    8. Differences between API implementations
    9. Chrome incompatibilities
  4. 用户界面
    1. 用户界面
    2. Toolbar button
    3. Address bar button
    4. Sidebars
    5. Context menu items
    6. Options page
    7. Extension pages
    8. Notifications
    9. Address bar suggestions
    10. Developer tools panels
  5. 如何
    1. Intercept HTTP requests
    2. Modify a web page
    3. Insert external content
    4. Share objects with page scripts
    5. Add a button to the toolbar
    6. Implement a settings page
    7. Work with the Tabs API
    8. Work with the Bookmarks API
    9. Work with the Cookies API
    10. Work with contextual identities
    11. Interact with the clipboard
    12. Build a cross-browser extension
  6. Firefox differentiators
  7. JavaScript API
    1. Browser support for JavaScript APIs
    2. alarms
    3. bookmarks
    4. browserAction
    5. browserSettings
    6. browsingData
    7. captivePortal
    8. clipboard
    9. 命令
    10. contentScripts
    11. contextualIdentities
    12. Cookie
    13. devtools
    14. dns
    15. downloads
    16. events
    17. extension
    18. extensionTypes
    19. find
    20. history
    21. i18n
    22. identity
    23. idle
    24. management
    25. menus
    26. notifications
    27. omnibox
    28. pageAction
    29. permissions
    30. pkcs11
    31. privacy
    32. proxy
    33. runtime
    34. search
    35. sessions
    36. sidebarAction
    37. storage
    38. tabs
    39. theme
    40. topSites
    41. 类型
    42. userScripts
    43. webNavigation
    44. webRequest
    45. windows
  8. Manifest keys
    1. 介绍
    1. 作者
    2. background
    3. browser_action
    4. browser_specific_settings
    5. chrome_settings_overrides
    6. chrome_url_overrides
    7. 命令
    8. content_scripts
    9. content_security_policy
    10. default_locale
    11. description
    12. developer
    13. devtools_page
    14. dictionaries
    15. externally_connectable
    16. homepage_url
    17. icons
    18. incognito
    19. manifest_version
    20. name
    21. offline_enabled
    22. omnibox
    23. optional_permissions
    24. options_page
    25. options_ui
    26. page_action
    27. permissions
    28. protocol_handlers
    29. short_name
    30. sidebar_action
    31. storage
    32. theme
    33. theme_experiment
    34. user_scripts
    35. version
    36. version_name
    37. web_accessible_resources
  9. Extension Workshop
    1. Develop
    2. Publish
    3. Manage
    4. Enterprise
  10. Contact us
  11. Channels
    1. Add-ons blog
    2. Add-ons forum
    3. Add-ons chat