playwright/api/
worker.rs

1use crate::{
2    api::JsHandle,
3    imp::{
4        core::*,
5        prelude::*,
6        worker::{Evt, Worker as Impl}
7    }
8};
9
10/// The Worker class represents a [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API). `worker`
11/// event is emitted on the page object to signal a worker creation. `close` event is emitted on the worker object when the
12/// worker is gone.
13///
14/// ```js
15/// page.on('worker', worker => {
16///  console.log('Worker created: ' + worker.url());
17///  worker.on('close', worker => console.log('Worker destroyed: ' + worker.url()));
18/// });
19///
20/// console.log('Current workers:');
21/// for (const worker of page.workers())
22///  console.log('  ' + worker.url());
23/// ```
24#[derive(Clone)]
25pub struct Worker {
26    inner: Weak<Impl>
27}
28
29impl PartialEq for Worker {
30    fn eq(&self, other: &Self) -> bool {
31        let a = self.inner.upgrade();
32        let b = other.inner.upgrade();
33        a.and_then(|a| b.map(|b| (a, b)))
34            .map(|(a, b)| a.guid() == b.guid())
35            .unwrap_or_default()
36    }
37}
38
39impl Worker {
40    pub(crate) fn new(inner: Weak<Impl>) -> Self { Self { inner } }
41
42    pub fn url(&self) -> Result<String, Error> { Ok(upgrade(&self.inner)?.url().to_owned()) }
43
44    pub async fn eval_handle(&self, expression: &str) -> ArcResult<JsHandle> {
45        upgrade(&self.inner)?
46            .eval_handle(expression)
47            .await
48            .map(JsHandle::new)
49    }
50
51    pub async fn evaluate_handle<T>(&self, expression: &str, arg: Option<T>) -> ArcResult<JsHandle>
52    where
53        T: Serialize
54    {
55        upgrade(&self.inner)?
56            .evaluate_handle(expression, arg)
57            .await
58            .map(JsHandle::new)
59    }
60
61    pub async fn eval<U>(&self, expression: &str) -> ArcResult<U>
62    where
63        U: DeserializeOwned
64    {
65        upgrade(&self.inner)?.eval(expression).await
66    }
67
68    pub async fn evaluate<T, U>(&self, expression: &str, arg: Option<T>) -> ArcResult<U>
69    where
70        T: Serialize,
71        U: DeserializeOwned
72    {
73        upgrade(&self.inner)?.evaluate(expression, arg).await
74    }
75
76    subscribe_event! {}
77}
78
79#[derive(Debug)]
80pub enum Event {
81    Close
82}
83
84impl From<Evt> for Event {
85    fn from(e: Evt) -> Self {
86        match e {
87            Evt::Close => Self::Close
88        }
89    }
90}