playwright/api/
download.rs

1use crate::imp::{core::*, download::Download as Impl, prelude::*};
2
3/// `Download` objects are dispatched by page via the [`event: Page.download`] event.
4///
5/// All the downloaded files belonging to the browser context are deleted when the browser context is closed. All downloaded
6/// files are deleted when the browser closes.
7///
8/// Download event is emitted once the download starts. Download path becomes available once download completes:
9///
10/// ```js
11/// const [ download ] = await Promise.all([
12///  page.waitForEvent('download'), // wait for download to start
13///  page.click('a')
14/// ]);
15///// wait for download to complete
16/// const path = await download.path();
17/// ```
18/// 
19/// > NOTE: Browser context **must** be created with the `acceptDownloads` set to `true` when user needs access to the
20/// downloaded content. If `acceptDownloads` is not set, download events are emitted, but the actual download is not
21/// performed and user has no access to the downloaded files.
22#[derive(Clone)]
23pub struct Download {
24    inner: Arc<Impl>
25}
26
27impl Download {
28    pub(crate) fn new(inner: Arc<Impl>) -> Self { Self { inner } }
29
30    /// Returns downloaded url.
31    pub fn url(&self) -> &str { self.inner.url() }
32
33    /// Returns suggested filename for this download. It is typically computed by the browser from the
34    /// [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) response header
35    /// or the `download` attribute. See the spec on [whatwg](https://html.spec.whatwg.org/#downloading-resources). Different
36    /// browsers can use different logic for computing it.
37    pub fn suggested_filename(&self) -> &str { self.inner.suggested_filename() }
38
39    /// Returns path to the downloaded file in case of successful download. The method will wait for the download to finish if
40    /// necessary.
41    pub async fn path(&self) -> ArcResult<Option<PathBuf>> { self.inner.path().await }
42
43    /// Deletes the downloaded file. Will wait for the download to finish if necessary.
44    pub async fn delete(&self) -> ArcResult<()> { self.inner.delete().await }
45
46    /// Saves the download to a user-specified path. It is safe to call this method while the download is still in progress.
47    /// Path where the download should be saved.
48    pub async fn save_as<P: AsRef<Path>>(&self, path: P) -> Result<(), Arc<Error>> {
49        self.inner.save_as(path).await
50    }
51
52    ///// Returns readable stream for current download or `null` if download failed.
53    // fn create_read_stream(&self) -> Result<Option<Readable>, Arc<Error>> { todo!() }
54
55    /// Returns download error if any. Will wait for the download to finish if necessary.
56    pub async fn failure(&self) -> Result<Option<String>, Arc<Error>> { self.inner.failure().await }
57}