# `Playwright.Worker`
[🔗](https://github.com/ftes/playwright_ex/blob/v1.65.0-rc.3/lib/playwright/api/worker.ex#L7)

The Worker class represents a [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API). `worker`
event is emitted on the page object to signal a worker creation. `close` event is emitted on the worker object when the
worker is gone.

```elixir
Page.on(page, :worker, fn worker ->
  IO.puts("Worker created: " <> Worker.url(worker))
  Worker.on(worker, :close, &IO.puts("Worker destroyed: " <> Worker.url(&1)))
end)

IO.puts("Current workers:")
for worker <- Page.workers(page), do: IO.puts("  " <> Worker.url(worker))
```

*Since Playwright 1.8.*

The examples alias the modules they use (`alias Playwright.{Locator, Page}`).

## Events

### `:close`

Emitted when this dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is terminated.

### `:console`

*Since Playwright 1.57.* Emitted when JavaScript within the worker calls one of console API methods, e.g. `console.log` or `console.dir`.

# `event`

```elixir
@type event() :: :close | :console
```

An event name, see the module docs.

# `expect_event_options`

```elixir
@type expect_event_options() ::
  [
    predicate: fun(),
    timeout: number() | :infinity,
    signal: Playwright.AbortSignal.t()
  ]
  | %{
      optional(:predicate) =&gt; fun(),
      optional(:timeout) =&gt; number() | :infinity,
      optional(:signal) =&gt; Playwright.AbortSignal.t()
    }
```

Options of `expect_event/4`, see its docs.

# `t`

```elixir
@type t() :: %Playwright.Worker{
  conn: term(),
  guid: term(),
  initializer: term(),
  table: term(),
  type: term()
}
```

A `Worker` handle. Compare handles with `==`, their fields are internal.

# `wait_for_event_options`

```elixir
@type wait_for_event_options() ::
  [
    predicate: fun(),
    timeout: number() | :infinity,
    signal: Playwright.AbortSignal.t()
  ]
  | %{
      optional(:predicate) =&gt; fun(),
      optional(:timeout) =&gt; number() | :infinity,
      optional(:signal) =&gt; Playwright.AbortSignal.t()
    }
```

Options of `wait_for_event/3`, see its docs.

# `evaluate`

```elixir
@spec evaluate(t(), String.t(), term() | nil) ::
  {:ok, term()} | {:error, Playwright.error()}
```

Returns the return value of `expression`.

If the function passed to the `Playwright.Worker.evaluate/3` returns a `Promise`, then `Playwright.Worker.evaluate/3` would wait for the promise
to resolve and return its value.

If the function passed to the `Playwright.Worker.evaluate/3` returns a non-`Serializable` value, then `Playwright.Worker.evaluate/3` returns `nil`. Playwright also supports transferring some
additional values that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.

*Since Playwright 1.8.*

## Arguments

* `expression` - Function to be evaluated in the worker context.
* `arg` - Optional argument to pass to `expression`.

# `evaluate!`

```elixir
@spec evaluate!(t(), String.t(), term() | nil) :: term()
```

Like `evaluate/3`, but returns the value and raises on error.

# `evaluate_handle`

```elixir
@spec evaluate_handle(t(), String.t(), term() | nil) ::
  {:ok, Playwright.JSHandle.t()} | {:error, Playwright.error()}
```

Returns the return value of `expression` as a [`JSHandle`](`Playwright.JSHandle`).

The only difference between `Playwright.Worker.evaluate/3` and
`Playwright.Worker.evaluate_handle/3` is that `Playwright.Worker.evaluate_handle/3`
returns [`JSHandle`](`Playwright.JSHandle`).

If the function passed to the `Playwright.Worker.evaluate_handle/3` returns a `Promise`, then `Playwright.Worker.evaluate_handle/3` would wait for
the promise to resolve and return its value.

*Since Playwright 1.8.*

## Arguments

* `expression` - Function to be evaluated in the worker context.
* `arg` - Optional argument to pass to `expression`.

# `evaluate_handle!`

```elixir
@spec evaluate_handle!(t(), String.t(), term() | nil) :: Playwright.JSHandle.t()
```

Like `evaluate_handle/3`, but returns the value and raises on error.

# `expect_event`

```elixir
@spec expect_event(
  t(),
  event() | String.t(),
  (-&gt; term()),
  expect_event_options() | fun()
) ::
  {:ok, term()} | {:error, Playwright.error()}
```

Waits for event to fire and passes its value into the predicate function.
Returns when the predicate returns truthy value.
Will fail if the page is closed before the event is fired.
Returns the event data value.

**Usage**

```elixir
# Start waiting for download before clicking. Note no await.
console_promise = Worker.wait_for_event(worker, :console)
Worker.evaluate!(worker, "console.log(42)")
console_message = Promise.await!(console_promise)
```

*Since Playwright 1.57.*

## Arguments

* `event` - Event name, same one typically passed into `Playwright.Worker.on/3`.
* `action` - A function that performs the action triggering the wait. It runs once the wait is set up; its result is ignored and what it raises propagates.

## Options

A function in place of the options is the `:predicate` option.

* `:predicate` (`t:fun/0`) - Receives the event data and returns a truthy value when the waiting should resolve.
* `:timeout` (`t:number/0` | `:infinity`) - Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  The default value can be changed with its page's `Playwright.Page.set_default_timeout/2` or `Playwright.BrowserContext.set_default_timeout/2`.

  In Elixir, `:infinity` is the same as `0`: no timeout.
* `:signal` (`t:Playwright.AbortSignal.t/0`) - *Since Playwright 1.62.* Allows to cancel the waiting using an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal). If the signal is aborted, the waiting will be aborted and the operation will fail.
  Note that providing a signal does not disable the default timeout, which can be changed using `Playwright.BrowserContext.set_default_timeout/2`; pass `timeout: 0` to disable the timeout entirely.

  In Elixir, a `Playwright.AbortSignal` (`Playwright.AbortController.signal/1`).

  In Elixir, a `Playwright.AbortSignal` (`Playwright.AbortController.signal/1`).

# `expect_event!`

```elixir
@spec expect_event!(
  t(),
  event() | String.t(),
  (-&gt; term()),
  expect_event_options() | fun()
) :: term()
```

Like `expect_event/4`, but returns the value and raises on error.

# `url`

```elixir
@spec url(t()) :: String.t()
```

*Since Playwright 1.8.*

# `wait_for_event`

```elixir
@spec wait_for_event(t(), event() | String.t(), wait_for_event_options() | fun()) ::
  Playwright.Promise.t()
```

Waits for event to fire and passes its value into the predicate function.
Returns when the predicate returns truthy value.
Will fail if the page is closed before the event is fired.
Returns the event data value.

**Usage**

```elixir
# Start waiting for download before clicking. Note no await.
console_promise = Worker.wait_for_event(worker, :console)
Worker.evaluate!(worker, "console.log(42)")
console_message = Promise.await!(console_promise)
```

*Since Playwright 1.57.*

## Arguments

* `event` - Event name, same one typically passed into `Playwright.Worker.on/3`.

## Options

A function in place of the options is the `:predicate` option.

* `:predicate` (`t:fun/0`) - Receives the event data and returns a truthy value when the waiting should resolve.
* `:timeout` (`t:number/0` | `:infinity`) - Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  The default value can be changed with its page's `Playwright.Page.set_default_timeout/2` or `Playwright.BrowserContext.set_default_timeout/2`.

  In Elixir, `:infinity` is the same as `0`: no timeout.
* `:signal` (`t:Playwright.AbortSignal.t/0`) - *Since Playwright 1.62.* Allows to cancel the waiting using an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal). If the signal is aborted, the waiting will be aborted and the operation will fail.
  Note that providing a signal does not disable the default timeout, which can be changed using `Playwright.BrowserContext.set_default_timeout/2`; pass `timeout: 0` to disable the timeout entirely.

  In Elixir, a `Playwright.AbortSignal` (`Playwright.AbortController.signal/1`).

Returns a `Playwright.Promise` at once, with the wait already set up. Start it before the action that triggers it and await it after with `Playwright.Promise.await/1`:

```elixir
promise = Playwright.Worker.wait_for_event(worker, event)
Playwright.Locator.click!(button)
value = Playwright.Promise.await!(promise)
```

The callback form `expect_event/4` runs the action:

```elixir
value = Playwright.Worker.expect_event!(worker, event, fn -> Playwright.Locator.click!(button) end)
```

# `wait_for_event!`

```elixir
@spec wait_for_event!(t(), event() | String.t(), wait_for_event_options() | fun()) ::
  term()
```

Like `wait_for_event/3`, but awaits the promise: `Playwright.Promise.await!(wait_for_event(...))`, the value or a raise.

> #### Start waiting before the action {: .warning}
>
> This waits from the time it is called, so it misses what the code before it triggered. Start the wait with `wait_for_event/3` before the action and await it after, or use the callback form `expect_event!/4`:
>
> ```elixir
> promise = Playwright.Worker.wait_for_event(worker, event)
> Playwright.Locator.click!(button)
> value = Playwright.Promise.await!(promise)
> ```
>
> ```elixir
> value = Playwright.Worker.expect_event!(worker, event, fn -> Playwright.Locator.click!(button) end)
> ```

# `add_listener`

```elixir
@spec add_listener(t(), :close, (t() -&gt; term())) :: t()
@spec add_listener(t(), :console, (Playwright.ConsoleMessage.t() -&gt; term())) :: t()
@spec add_listener(t(), String.t(), (term() -&gt; term())) :: t()
```

Adds an event listener for `event`, see the module docs for the events.

# `off`

```elixir
@spec off(t(), :close, (t() -&gt; term())) :: t()
@spec off(t(), :console, (Playwright.ConsoleMessage.t() -&gt; term())) :: t()
@spec off(t(), String.t(), (term() -&gt; term())) :: t()
```

Removes an event listener added by `on/3` or `add_listener/3`.

# `on`

```elixir
@spec on(t(), :close, (t() -&gt; term())) :: t()
@spec on(t(), :console, (Playwright.ConsoleMessage.t() -&gt; term())) :: t()
@spec on(t(), String.t(), (term() -&gt; term())) :: t()
```

Adds an event listener for `event`, see the module docs for the events.

# `once`

```elixir
@spec once(t(), :close, (t() -&gt; term())) :: t()
@spec once(t(), :console, (Playwright.ConsoleMessage.t() -&gt; term())) :: t()
@spec once(t(), String.t(), (term() -&gt; term())) :: t()
```

Adds an event listener that is removed after it is triggered once. See `on/3`.

# `prepend_listener`

```elixir
@spec prepend_listener(t(), :close, (t() -&gt; term())) :: t()
@spec prepend_listener(t(), :console, (Playwright.ConsoleMessage.t() -&gt; term())) ::
  t()
@spec prepend_listener(t(), String.t(), (term() -&gt; term())) :: t()
```

Adds an event listener for `event`, see the module docs for the events.

# `remove_listener`

```elixir
@spec remove_listener(t(), :close, (t() -&gt; term())) :: t()
@spec remove_listener(t(), :console, (Playwright.ConsoleMessage.t() -&gt; term())) :: t()
@spec remove_listener(t(), String.t(), (term() -&gt; term())) :: t()
```

Removes an event listener added by `on/3` or `add_listener/3`.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
