Repository navigation
feat(h5): 支持 createWorker #19676
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Single-Dancer
merged 3 commits into
NervJS:main
from
Jarvis636431:codex/h5-create-worker
Nov 30, 2026
Merged
feat(h5): 支持 createWorker #19676
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| import { createWorker } from '@tarojs/taro-h5' | ||
|
|
||
| class NativeWorker extends EventTarget { | ||
| static current: NativeWorker | ||
| postMessage = jest.fn() | ||
| terminate = jest.fn() | ||
|
|
||
| constructor (readonly scriptPath: string) { | ||
| super() | ||
| NativeWorker.current = this | ||
| } | ||
| } | ||
|
|
||
| describe('createWorker', () => { | ||
| const original = Object.getOwnPropertyDescriptor(globalThis, 'Worker') | ||
| let worker: ReturnType<typeof createWorker> | ||
|
|
||
| beforeEach(() => { | ||
| Object.defineProperty(globalThis, 'Worker', { configurable: true, value: NativeWorker }) | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| worker?.terminate() | ||
| if (original) Object.defineProperty(globalThis, 'Worker', original) | ||
| else Reflect.deleteProperty(globalThis, 'Worker') | ||
| }) | ||
|
|
||
| it('forwards messages and adapts native message events', () => { | ||
| worker = createWorker('/static/worker.js') | ||
| const native = NativeWorker.current | ||
| const onMessage = jest.fn() | ||
| worker.onMessage(onMessage) | ||
| worker.postMessage({ input: 21 }) | ||
| native.dispatchEvent(new MessageEvent('message', { data: { output: 42 } })) | ||
| expect(native.scriptPath).toBe('/static/worker.js') | ||
| expect(native.postMessage).toHaveBeenCalledWith({ input: 21 }) | ||
| expect(onMessage).toHaveBeenCalledWith({ message: { output: 42 } }) | ||
| }) | ||
|
|
||
| it('releases the active worker slot on termination', () => { | ||
| const first = createWorker('/first.js') | ||
| worker = first | ||
| const native = NativeWorker.current | ||
| expect(() => createWorker('/second.js')).toThrow('terminate the active worker') | ||
| first.terminate() | ||
| expect(native.terminate).toHaveBeenCalledTimes(1) | ||
| worker = createWorker('/second.js') | ||
| first.terminate() | ||
| expect(() => createWorker('/third.js')).toThrow('terminate the active worker') | ||
| }) | ||
|
|
||
| it('reports async script errors and permits explicit termination and retry', () => { | ||
| worker = createWorker('/missing.js') | ||
| const onError = jest.fn() | ||
| worker.onError(onError) | ||
| NativeWorker.current.dispatchEvent(new ErrorEvent('error', { message: 'script load failed' })) | ||
| expect(onError).toHaveBeenCalledWith({ errMsg: 'createWorker:fail script load failed' }) | ||
| worker.terminate() | ||
| worker = createWorker('/echo.js') | ||
| const onMessage = jest.fn() | ||
| worker.onMessage(onMessage) | ||
| worker.postMessage({ input: 21 }) | ||
| NativeWorker.current.dispatchEvent(new MessageEvent('message', { data: { output: 42 } })) | ||
| expect(onMessage).toHaveBeenCalledWith({ message: { output: 42 } }) | ||
| }) | ||
|
|
||
| it('fails synchronously on an invalid path or missing browser support', () => { | ||
| expect(() => createWorker('')).toThrow('non-empty string') | ||
| // Delete the mock so the VM sees an absent global binding. | ||
| Reflect.deleteProperty(globalThis, 'Worker') | ||
| expect(() => createWorker('/worker.js')).toThrow('unavailable') | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,38 @@ | ||
| import { temporarilyNotSupport } from '../../utils' | ||
| import Taro from '@tarojs/api' | ||
|
|
||
| // Worker | ||
| export const createWorker = /* @__PURE__ */ temporarilyNotSupport('createWorker') | ||
| export interface H5Worker extends Taro.Worker { | ||
| onError(callback: (result: TaroGeneral.CallbackResult) => void): void | ||
| } | ||
|
|
||
| let activeWorker: Worker | undefined | ||
|
|
||
| export const createWorker = (scriptPath: string): H5Worker => { | ||
| if (typeof Worker !== 'function') throw new Error('createWorker: Web Worker is unavailable') | ||
| if (typeof scriptPath !== 'string' || !scriptPath.trim()) { | ||
| throw new TypeError('createWorker: scriptPath must be a non-empty string') | ||
| } | ||
| if (activeWorker) throw new Error('createWorker: terminate the active worker before creating another') | ||
|
|
||
| const worker = new Worker(scriptPath) | ||
| activeWorker = worker | ||
| return { | ||
| onMessage (callback) { | ||
| worker.addEventListener('message', event => callback({ message: event.data })) | ||
| }, | ||
| onError (callback) { | ||
| worker.addEventListener('error', event => callback({ | ||
| errMsg: `createWorker:fail ${event.message || 'worker script failed'}`, | ||
| })) | ||
| }, | ||
| onProcessKilled () { | ||
| // Browsers do not expose system reclamation events for dedicated workers. | ||
| }, | ||
| postMessage (message) { | ||
| worker.postMessage(message) | ||
| }, | ||
| terminate () { | ||
| worker.terminate() | ||
| if (activeWorker === worker) activeWorker = undefined | ||
| }, | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[P2] Worker 脚本加载失败时,调用方收不到错误
在 Chrome 158 用本 PR 的实现复现。调用
createWorker('/missing.js'),让同源服务对该脚本返回 HTTP 404。createWorker()同步返回实例,随后原生 Worker 触发error。Taro 返回的对象没有暴露这个事件,onMessage也没有回调。此时改用有效的/echo.js重试,仍会抛出createWorker: terminate the active worker before creating another。对失败实例调用terminate()后,重新创建并发送{ input: 21 },正常收到{ message: { output: 42 } }。建议在 H5 暴露并声明 Worker 的错误回调(例如
onError),转发原生error,让调用方可以在失败时终止实例并重试。补一个脚本异步加载失败、收到错误回调、终止后用有效 URL 重建成功的回归测试。