Skip to main content
Version: 24.38.0

WebWorker 类

🌐 WebWorker class

这个类表示一个 WebWorker

🌐 This class represents a WebWorker.

语法

🌐 Signature

export declare abstract class WebWorker extends EventEmitter<Record<EventType, unknown>>

Extends: EventEmitter<Record<EventType, unknown>>

附注

🌐 Remarks

事件 workercreatedworkerdestroyed 会在页面对象上触发,以表示工作线程的生命周期。

🌐 The events workercreated and workerdestroyed are emitted on the page object to signal the worker lifecycle.

这个类的构造函数被标记为内部。第三方代码不应直接调用构造函数或创建继承 WebWorker 类的子类。

🌐 The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the WebWorker class.

示例

🌐 Example

page.on('workercreated', worker =>
console.log('Worker created: ' + worker.url()),
);
page.on('workerdestroyed', worker =>
console.log('Worker destroyed: ' + worker.url()),
);

console.log('Current workers:');
for (const worker of page.workers()) {
console.log(' ' + worker.url());
}

属性

🌐 Properties

属性

🌐 Property

修饰符

🌐 Modifiers

类型

🌐 Type

描述

🌐 Description

client

readonly

CDPSession

WebWorker 所属的 CDP 会话客户端。

🌐 The CDP session client the WebWorker belongs to.

方法

🌐 Methods

方法

🌐 Method

修饰符

🌐 Modifiers

描述

🌐 Description

close()
evaluate(func, args)

worker 中评估给定的函数。

🌐 Evaluates a given function in the worker.

附注

如果给定的函数返回一个 promise,evaluate 将等待该 promise 解决。

🌐 If the given function returns a promise, evaluate will wait for the promise to resolve.

通常情况下,如果给定函数的返回值比 JSON 对象更复杂(例如大多数类),那么 evaluate 很可能会返回某个截断的值(或 {})。这是因为我们不是返回实际的返回值,而是通过协议将返回值传输到 Puppeteer 后反序列化得到的版本。

🌐 As a rule of thumb, if the return value of the given function is more complicated than a JSON object (e.g. most classes), then evaluate will _likely_ return some truncated value (or {}). This is because we are not returning the actual return value, but a deserialized version as a result of transferring the return value through a protocol to Puppeteer.

一般来说,如果 evaluate 无法正确序列化返回值,或者你需要对返回对象使用可变的 handle,你应该使用 evaluateHandle

🌐 In general, you should use evaluateHandle if evaluate cannot serialize the return value properly or you need a mutable handle to the return object.

evaluateHandle(func, args)

worker 中评估给定的函数。

🌐 Evaluates a given function in the worker.

附注

如果给定的函数返回一个 promise,evaluate 将等待该 promise 解决。

🌐 If the given function returns a promise, evaluate will wait for the promise to resolve.

一般来说,如果 evaluate 无法正确序列化返回值,或者你需要对返回对象使用可变的 handle,你应该使用 evaluateHandle

🌐 In general, you should use evaluateHandle if evaluate cannot serialize the return value properly or you need a mutable handle to the return object.

url()

此 Web Worker 的 URL。

🌐 The URL of this web worker.