From 1853fd65e30688397d75ccd097af2a43b3abce3d Mon Sep 17 00:00:00 2001 From: Jarvis Date: Tue, 20 Oct 2026 15:40:30 +0800 Subject: [PATCH 1/5] fix(h5): handle clipboard copy failures and clean up temporary textareas --- .../__tests__/device/clipboard.test.ts | 105 ++++++++++++++++++ packages/taro-h5/src/api/device/clipboard.ts | 15 ++- 2 files changed, 115 insertions(+), 5 deletions(-) create mode 100644 packages/taro-h5/__tests__/device/clipboard.test.ts diff --git a/packages/taro-h5/__tests__/device/clipboard.test.ts b/packages/taro-h5/__tests__/device/clipboard.test.ts new file mode 100644 index 000000000000..dc6befabfcf3 --- /dev/null +++ b/packages/taro-h5/__tests__/device/clipboard.test.ts @@ -0,0 +1,105 @@ +import { getClipboardData, setClipboardData } from '../../src/api/device/clipboard' +import { setStorageSync } from '../../src/api/storage' +import { showToast } from '../../src/api/ui/interaction' + +jest.mock('../../src/api/ui/interaction', () => ({ showToast: jest.fn() })) + +describe('setClipboardData', () => { + let execCommand: jest.Mock + const originalExecCommand = Object.getOwnPropertyDescriptor(document, 'execCommand') + + beforeEach(() => { + execCommand = jest.fn(() => true) + Object.defineProperty(document, 'execCommand', { configurable: true, value: execCommand }) + setStorageSync('taro_clipboard', 'previous content') + jest.mocked(showToast).mockClear() + }) + + afterEach(() => { + document.body.innerHTML = '' + localStorage.clear() + jest.restoreAllMocks() + if (originalExecCommand) Object.defineProperty(document, 'execCommand', originalExecCommand) + else delete document.execCommand + }) + + function failCopy (mode: string) { + if (mode === 'returns false') execCommand.mockReturnValue(false) + else execCommand.mockImplementation(() => { throw new Error('copy denied') }) + } + + test.each(['returns false', 'throws'])('rejects when copying %s and removes the temporary textarea', async mode => { + failCopy(mode) + + await expect(setClipboardData({ data: 'new content' })).rejects.toEqual({ + errMsg: `setClipboardData:fail ${mode === 'returns false' ? 'Failed to copy to clipboard' : 'copy denied'}` + }) + + expect(document.querySelector('textarea')).toBeNull() + expect(showToast).not.toHaveBeenCalled() + expect((await getClipboardData()).data).toBe('previous content') + }) + + test.each(['returns false', 'throws'])('calls fail and complete once when copying %s', async mode => { + failCopy(mode) + const success = jest.fn() + const fail = jest.fn() + const complete = jest.fn() + + const result = await setClipboardData({ data: 'new content', success, fail, complete }) + + expect(result.errMsg).toMatch(/^setClipboardData:fail /) + expect(success).not.toHaveBeenCalled() + expect(fail).toHaveBeenCalledTimes(1) + expect(fail).toHaveBeenCalledWith(result) + expect(complete).toHaveBeenCalledTimes(1) + expect(complete).toHaveBeenCalledWith(result) + expect(document.querySelector('textarea')).toBeNull() + expect(showToast).not.toHaveBeenCalled() + }) + + test('cleans up when selecting the text throws', async () => { + jest.spyOn(HTMLTextAreaElement.prototype, 'select').mockImplementation(() => { throw new Error('selection failed') }) + + await expect(setClipboardData({ data: 'new content' })).rejects.toEqual({ errMsg: 'setClipboardData:fail selection failed' }) + + expect(document.querySelector('textarea')).toBeNull() + expect(execCommand).not.toHaveBeenCalled() + expect(showToast).not.toHaveBeenCalled() + }) + + test('rejects when execCommand is unavailable without changing the cached value', async () => { + Object.defineProperty(document, 'execCommand', { configurable: true, value: undefined }) + + await expect(setClipboardData({ data: 'new content' })).rejects.toEqual({ + errMsg: 'setClipboardData:fail Unsupported Function: \'document.execCommand\'.' + }) + + expect((await getClipboardData()).data).toBe('previous content') + expect(document.querySelector('textarea')).toBeNull() + expect(showToast).not.toHaveBeenCalled() + }) + + test.each([false, true])('preserves successful copying with hideDefaultMessage=%s', async hideDefaultMessage => { + const data = 'line one\nline two' + const success = jest.fn() + const fail = jest.fn() + const complete = jest.fn() + execCommand.mockImplementation(() => { + expect(document.querySelector('textarea')?.value).toBe(data) + return true + }) + + const result = await setClipboardData({ data, options: { hideDefaultMessage }, success, fail, complete }) + + expect(result).toEqual({ errMsg: 'setClipboardData:ok' }) + expect(execCommand).toHaveBeenCalledWith('copy') + expect(document.querySelector('textarea')).toBeNull() + expect((await getClipboardData()).data).toBe(data) + expect(success).toHaveBeenCalledTimes(1) + expect(success).toHaveBeenCalledWith(result) + expect(fail).not.toHaveBeenCalled() + expect(complete).toHaveBeenCalledTimes(1) + expect(showToast).toHaveBeenCalledTimes(hideDefaultMessage ? 0 : 1) + }) +}) diff --git a/packages/taro-h5/src/api/device/clipboard.ts b/packages/taro-h5/src/api/device/clipboard.ts index 2e88f4fa1b44..5b9b83390f95 100644 --- a/packages/taro-h5/src/api/device/clipboard.ts +++ b/packages/taro-h5/src/api/device/clipboard.ts @@ -30,7 +30,6 @@ export const setClipboardData: typeof Taro.setClipboardData = async ({ data, opt const hideDefaultMessage = options?.hideDefaultMessage ?? false const handle = new MethodHandler({ name: 'setClipboardData', success, fail, complete }) try { - setStorageSync(CLIPBOARD_STORAGE_NAME, data) /** * 已于 iPhone 6s Plus iOS 13.1.3 上的 Safari 测试通过 * iOS < 10 的系统可能无法使用编程方式访问剪贴板,参考: @@ -44,13 +43,19 @@ export const setClipboardData: typeof Taro.setClipboardData = async ({ data, opt textarea.style.width = '100px' textarea.style.left = '-10000px' document.body.appendChild(textarea) - textarea.select() - textarea.setSelectionRange(0, textarea.value.length) - document.execCommand('copy') - document.body.removeChild(textarea) + try { + textarea.select() + textarea.setSelectionRange(0, textarea.value.length) + if (!document.execCommand('copy')) { + throw new Error('Failed to copy to clipboard') + } + } finally { + textarea.remove() + } } else { throw new Error('Unsupported Function: \'document.execCommand\'.') } + setStorageSync(CLIPBOARD_STORAGE_NAME, data) if (!hideDefaultMessage) { showToast({ title: '内容已复制', From b2798960e37b28e9ea5e42fe8c4d440770eb6aae Mon Sep 17 00:00:00 2001 From: Jarvis Date: Thu, 22 Oct 2026 15:45:13 +0800 Subject: [PATCH 2/5] fix(h5): preserve clipboard cleanup compatibility --- .../__tests__/device/clipboard.test.ts | 66 +++++++++++++++++++ packages/taro-h5/src/api/device/clipboard.ts | 5 +- 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/packages/taro-h5/__tests__/device/clipboard.test.ts b/packages/taro-h5/__tests__/device/clipboard.test.ts index dc6befabfcf3..c1aae3ed4be4 100644 --- a/packages/taro-h5/__tests__/device/clipboard.test.ts +++ b/packages/taro-h5/__tests__/device/clipboard.test.ts @@ -28,6 +28,72 @@ describe('setClipboardData', () => { else execCommand.mockImplementation(() => { throw new Error('copy denied') }) } + test.each(['succeeds', 'returns false', 'throws'])('cleans up without textarea.remove when copying %s', async mode => { + jest.spyOn(HTMLTextAreaElement.prototype, 'select').mockImplementation(function () { + Object.defineProperty(this, 'remove', { value: undefined }) + }) + if (mode !== 'succeeds') failCopy(mode) + const success = jest.fn() + const fail = jest.fn() + const complete = jest.fn() + + const result = await setClipboardData({ data: 'new content', success, fail, complete }) + + expect(result).toEqual({ + errMsg: mode === 'succeeds' + ? 'setClipboardData:ok' + : `setClipboardData:fail ${mode === 'returns false' ? 'Failed to copy to clipboard' : 'copy denied'}` + }) + expect(execCommand).toHaveBeenCalledWith('copy') + expect(document.querySelector('textarea')).toBeNull() + expect(success).toHaveBeenCalledTimes(mode === 'succeeds' ? 1 : 0) + expect(fail).toHaveBeenCalledTimes(mode === 'succeeds' ? 0 : 1) + expect(complete).toHaveBeenCalledTimes(1) + expect(complete).toHaveBeenCalledWith(result) + expect(showToast).toHaveBeenCalledTimes(mode === 'succeeds' ? 1 : 0) + expect((await getClipboardData()).data).toBe(mode === 'succeeds' ? 'new content' : 'previous content') + }) + + describe.each(['QuotaExceededError', 'SecurityError'])('when caching throws %s after a successful copy', errorName => { + beforeEach(() => { + jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new DOMException('Clipboard cache write failed', errorName) + }) + }) + + test('rejects and cleans up while leaving the readable cache unchanged', async () => { + await expect(setClipboardData({ data: 'new content' })).rejects.toEqual({ + errMsg: 'setClipboardData:fail Clipboard cache write failed' + }) + + expect(execCommand).toHaveBeenCalledTimes(1) + expect(execCommand).toHaveBeenCalledWith('copy') + expect(document.querySelector('textarea')).toBeNull() + expect(showToast).not.toHaveBeenCalled() + expect((await getClipboardData()).data).toBe('previous content') + }) + + test('calls fail and complete once without reporting success', async () => { + const success = jest.fn() + const fail = jest.fn() + const complete = jest.fn() + + const result = await setClipboardData({ data: 'new content', success, fail, complete }) + + expect(result).toEqual({ errMsg: 'setClipboardData:fail Clipboard cache write failed' }) + expect(execCommand).toHaveBeenCalledTimes(1) + expect(execCommand).toHaveBeenCalledWith('copy') + expect(success).not.toHaveBeenCalled() + expect(fail).toHaveBeenCalledTimes(1) + expect(fail).toHaveBeenCalledWith(result) + expect(complete).toHaveBeenCalledTimes(1) + expect(complete).toHaveBeenCalledWith(result) + expect(document.querySelector('textarea')).toBeNull() + expect(showToast).not.toHaveBeenCalled() + expect((await getClipboardData()).data).toBe('previous content') + }) + }) + test.each(['returns false', 'throws'])('rejects when copying %s and removes the temporary textarea', async mode => { failCopy(mode) diff --git a/packages/taro-h5/src/api/device/clipboard.ts b/packages/taro-h5/src/api/device/clipboard.ts index 5b9b83390f95..67ffaf04a2a0 100644 --- a/packages/taro-h5/src/api/device/clipboard.ts +++ b/packages/taro-h5/src/api/device/clipboard.ts @@ -50,11 +50,14 @@ export const setClipboardData: typeof Taro.setClipboardData = async ({ data, opt throw new Error('Failed to copy to clipboard') } } finally { - textarea.remove() + if (textarea.parentNode) { + textarea.parentNode.removeChild(textarea) + } } } else { throw new Error('Unsupported Function: \'document.execCommand\'.') } + // Cache failures are reported even if the system clipboard was already updated. setStorageSync(CLIPBOARD_STORAGE_NAME, data) if (!hideDefaultMessage) { showToast({ From 63ebff72c1b90f6755bcf0d8cb1f4f230d839361 Mon Sep 17 00:00:00 2001 From: Jarvis Date: Tue, 20 Oct 2026 15:40:30 +0800 Subject: [PATCH 3/5] fix(h5): handle clipboard copy failures and clean up temporary textareas --- .../__tests__/device/clipboard.test.ts | 105 ++++++++++++++++++ packages/taro-h5/src/api/device/clipboard.ts | 15 ++- 2 files changed, 115 insertions(+), 5 deletions(-) create mode 100644 packages/taro-h5/__tests__/device/clipboard.test.ts diff --git a/packages/taro-h5/__tests__/device/clipboard.test.ts b/packages/taro-h5/__tests__/device/clipboard.test.ts new file mode 100644 index 000000000000..dc6befabfcf3 --- /dev/null +++ b/packages/taro-h5/__tests__/device/clipboard.test.ts @@ -0,0 +1,105 @@ +import { getClipboardData, setClipboardData } from '../../src/api/device/clipboard' +import { setStorageSync } from '../../src/api/storage' +import { showToast } from '../../src/api/ui/interaction' + +jest.mock('../../src/api/ui/interaction', () => ({ showToast: jest.fn() })) + +describe('setClipboardData', () => { + let execCommand: jest.Mock + const originalExecCommand = Object.getOwnPropertyDescriptor(document, 'execCommand') + + beforeEach(() => { + execCommand = jest.fn(() => true) + Object.defineProperty(document, 'execCommand', { configurable: true, value: execCommand }) + setStorageSync('taro_clipboard', 'previous content') + jest.mocked(showToast).mockClear() + }) + + afterEach(() => { + document.body.innerHTML = '' + localStorage.clear() + jest.restoreAllMocks() + if (originalExecCommand) Object.defineProperty(document, 'execCommand', originalExecCommand) + else delete document.execCommand + }) + + function failCopy (mode: string) { + if (mode === 'returns false') execCommand.mockReturnValue(false) + else execCommand.mockImplementation(() => { throw new Error('copy denied') }) + } + + test.each(['returns false', 'throws'])('rejects when copying %s and removes the temporary textarea', async mode => { + failCopy(mode) + + await expect(setClipboardData({ data: 'new content' })).rejects.toEqual({ + errMsg: `setClipboardData:fail ${mode === 'returns false' ? 'Failed to copy to clipboard' : 'copy denied'}` + }) + + expect(document.querySelector('textarea')).toBeNull() + expect(showToast).not.toHaveBeenCalled() + expect((await getClipboardData()).data).toBe('previous content') + }) + + test.each(['returns false', 'throws'])('calls fail and complete once when copying %s', async mode => { + failCopy(mode) + const success = jest.fn() + const fail = jest.fn() + const complete = jest.fn() + + const result = await setClipboardData({ data: 'new content', success, fail, complete }) + + expect(result.errMsg).toMatch(/^setClipboardData:fail /) + expect(success).not.toHaveBeenCalled() + expect(fail).toHaveBeenCalledTimes(1) + expect(fail).toHaveBeenCalledWith(result) + expect(complete).toHaveBeenCalledTimes(1) + expect(complete).toHaveBeenCalledWith(result) + expect(document.querySelector('textarea')).toBeNull() + expect(showToast).not.toHaveBeenCalled() + }) + + test('cleans up when selecting the text throws', async () => { + jest.spyOn(HTMLTextAreaElement.prototype, 'select').mockImplementation(() => { throw new Error('selection failed') }) + + await expect(setClipboardData({ data: 'new content' })).rejects.toEqual({ errMsg: 'setClipboardData:fail selection failed' }) + + expect(document.querySelector('textarea')).toBeNull() + expect(execCommand).not.toHaveBeenCalled() + expect(showToast).not.toHaveBeenCalled() + }) + + test('rejects when execCommand is unavailable without changing the cached value', async () => { + Object.defineProperty(document, 'execCommand', { configurable: true, value: undefined }) + + await expect(setClipboardData({ data: 'new content' })).rejects.toEqual({ + errMsg: 'setClipboardData:fail Unsupported Function: \'document.execCommand\'.' + }) + + expect((await getClipboardData()).data).toBe('previous content') + expect(document.querySelector('textarea')).toBeNull() + expect(showToast).not.toHaveBeenCalled() + }) + + test.each([false, true])('preserves successful copying with hideDefaultMessage=%s', async hideDefaultMessage => { + const data = 'line one\nline two' + const success = jest.fn() + const fail = jest.fn() + const complete = jest.fn() + execCommand.mockImplementation(() => { + expect(document.querySelector('textarea')?.value).toBe(data) + return true + }) + + const result = await setClipboardData({ data, options: { hideDefaultMessage }, success, fail, complete }) + + expect(result).toEqual({ errMsg: 'setClipboardData:ok' }) + expect(execCommand).toHaveBeenCalledWith('copy') + expect(document.querySelector('textarea')).toBeNull() + expect((await getClipboardData()).data).toBe(data) + expect(success).toHaveBeenCalledTimes(1) + expect(success).toHaveBeenCalledWith(result) + expect(fail).not.toHaveBeenCalled() + expect(complete).toHaveBeenCalledTimes(1) + expect(showToast).toHaveBeenCalledTimes(hideDefaultMessage ? 0 : 1) + }) +}) diff --git a/packages/taro-h5/src/api/device/clipboard.ts b/packages/taro-h5/src/api/device/clipboard.ts index 2e88f4fa1b44..5b9b83390f95 100644 --- a/packages/taro-h5/src/api/device/clipboard.ts +++ b/packages/taro-h5/src/api/device/clipboard.ts @@ -30,7 +30,6 @@ export const setClipboardData: typeof Taro.setClipboardData = async ({ data, opt const hideDefaultMessage = options?.hideDefaultMessage ?? false const handle = new MethodHandler({ name: 'setClipboardData', success, fail, complete }) try { - setStorageSync(CLIPBOARD_STORAGE_NAME, data) /** * 已于 iPhone 6s Plus iOS 13.1.3 上的 Safari 测试通过 * iOS < 10 的系统可能无法使用编程方式访问剪贴板,参考: @@ -44,13 +43,19 @@ export const setClipboardData: typeof Taro.setClipboardData = async ({ data, opt textarea.style.width = '100px' textarea.style.left = '-10000px' document.body.appendChild(textarea) - textarea.select() - textarea.setSelectionRange(0, textarea.value.length) - document.execCommand('copy') - document.body.removeChild(textarea) + try { + textarea.select() + textarea.setSelectionRange(0, textarea.value.length) + if (!document.execCommand('copy')) { + throw new Error('Failed to copy to clipboard') + } + } finally { + textarea.remove() + } } else { throw new Error('Unsupported Function: \'document.execCommand\'.') } + setStorageSync(CLIPBOARD_STORAGE_NAME, data) if (!hideDefaultMessage) { showToast({ title: '内容已复制', From 3c56a55345ffa44c790e4604a6b8353a3235da28 Mon Sep 17 00:00:00 2001 From: Jarvis Date: Thu, 22 Oct 2026 15:45:13 +0800 Subject: [PATCH 4/5] fix(h5): preserve clipboard cleanup compatibility --- .../__tests__/device/clipboard.test.ts | 66 +++++++++++++++++++ packages/taro-h5/src/api/device/clipboard.ts | 5 +- 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/packages/taro-h5/__tests__/device/clipboard.test.ts b/packages/taro-h5/__tests__/device/clipboard.test.ts index dc6befabfcf3..c1aae3ed4be4 100644 --- a/packages/taro-h5/__tests__/device/clipboard.test.ts +++ b/packages/taro-h5/__tests__/device/clipboard.test.ts @@ -28,6 +28,72 @@ describe('setClipboardData', () => { else execCommand.mockImplementation(() => { throw new Error('copy denied') }) } + test.each(['succeeds', 'returns false', 'throws'])('cleans up without textarea.remove when copying %s', async mode => { + jest.spyOn(HTMLTextAreaElement.prototype, 'select').mockImplementation(function () { + Object.defineProperty(this, 'remove', { value: undefined }) + }) + if (mode !== 'succeeds') failCopy(mode) + const success = jest.fn() + const fail = jest.fn() + const complete = jest.fn() + + const result = await setClipboardData({ data: 'new content', success, fail, complete }) + + expect(result).toEqual({ + errMsg: mode === 'succeeds' + ? 'setClipboardData:ok' + : `setClipboardData:fail ${mode === 'returns false' ? 'Failed to copy to clipboard' : 'copy denied'}` + }) + expect(execCommand).toHaveBeenCalledWith('copy') + expect(document.querySelector('textarea')).toBeNull() + expect(success).toHaveBeenCalledTimes(mode === 'succeeds' ? 1 : 0) + expect(fail).toHaveBeenCalledTimes(mode === 'succeeds' ? 0 : 1) + expect(complete).toHaveBeenCalledTimes(1) + expect(complete).toHaveBeenCalledWith(result) + expect(showToast).toHaveBeenCalledTimes(mode === 'succeeds' ? 1 : 0) + expect((await getClipboardData()).data).toBe(mode === 'succeeds' ? 'new content' : 'previous content') + }) + + describe.each(['QuotaExceededError', 'SecurityError'])('when caching throws %s after a successful copy', errorName => { + beforeEach(() => { + jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new DOMException('Clipboard cache write failed', errorName) + }) + }) + + test('rejects and cleans up while leaving the readable cache unchanged', async () => { + await expect(setClipboardData({ data: 'new content' })).rejects.toEqual({ + errMsg: 'setClipboardData:fail Clipboard cache write failed' + }) + + expect(execCommand).toHaveBeenCalledTimes(1) + expect(execCommand).toHaveBeenCalledWith('copy') + expect(document.querySelector('textarea')).toBeNull() + expect(showToast).not.toHaveBeenCalled() + expect((await getClipboardData()).data).toBe('previous content') + }) + + test('calls fail and complete once without reporting success', async () => { + const success = jest.fn() + const fail = jest.fn() + const complete = jest.fn() + + const result = await setClipboardData({ data: 'new content', success, fail, complete }) + + expect(result).toEqual({ errMsg: 'setClipboardData:fail Clipboard cache write failed' }) + expect(execCommand).toHaveBeenCalledTimes(1) + expect(execCommand).toHaveBeenCalledWith('copy') + expect(success).not.toHaveBeenCalled() + expect(fail).toHaveBeenCalledTimes(1) + expect(fail).toHaveBeenCalledWith(result) + expect(complete).toHaveBeenCalledTimes(1) + expect(complete).toHaveBeenCalledWith(result) + expect(document.querySelector('textarea')).toBeNull() + expect(showToast).not.toHaveBeenCalled() + expect((await getClipboardData()).data).toBe('previous content') + }) + }) + test.each(['returns false', 'throws'])('rejects when copying %s and removes the temporary textarea', async mode => { failCopy(mode) diff --git a/packages/taro-h5/src/api/device/clipboard.ts b/packages/taro-h5/src/api/device/clipboard.ts index 5b9b83390f95..67ffaf04a2a0 100644 --- a/packages/taro-h5/src/api/device/clipboard.ts +++ b/packages/taro-h5/src/api/device/clipboard.ts @@ -50,11 +50,14 @@ export const setClipboardData: typeof Taro.setClipboardData = async ({ data, opt throw new Error('Failed to copy to clipboard') } } finally { - textarea.remove() + if (textarea.parentNode) { + textarea.parentNode.removeChild(textarea) + } } } else { throw new Error('Unsupported Function: \'document.execCommand\'.') } + // Cache failures are reported even if the system clipboard was already updated. setStorageSync(CLIPBOARD_STORAGE_NAME, data) if (!hideDefaultMessage) { showToast({ From e07be5cb532753d5a011988f85723aafa897cd69 Mon Sep 17 00:00:00 2001 From: Jarvis Date: Thu, 22 Oct 2026 20:50:45 +0800 Subject: [PATCH 5/5] fix(h5): guard clipboard cache updates during copy events --- .../__tests__/device/clipboard.test.ts | 43 +++++++++++++++++++ packages/taro-h5/src/api/device/clipboard.ts | 16 ++++--- 2 files changed, 53 insertions(+), 6 deletions(-) diff --git a/packages/taro-h5/__tests__/device/clipboard.test.ts b/packages/taro-h5/__tests__/device/clipboard.test.ts index c1aae3ed4be4..a1ba98412a1c 100644 --- a/packages/taro-h5/__tests__/device/clipboard.test.ts +++ b/packages/taro-h5/__tests__/device/clipboard.test.ts @@ -28,6 +28,49 @@ describe('setClipboardData', () => { else execCommand.mockImplementation(() => { throw new Error('copy denied') }) } + test.each(['succeeds', 'returns false', 'throws'])('defers copy-event caching until the command %s', async mode => { + jest.spyOn(window, 'getSelection').mockReturnValue({ toString: () => 'selected content' } as Selection) + const setItem = jest.spyOn(Storage.prototype, 'setItem') + execCommand.mockImplementation(() => { + document.dispatchEvent(new Event('copy')) + expect(setItem).not.toHaveBeenCalled() + if (mode === 'throws') throw new Error('copy denied') + return mode === 'succeeds' + }) + const success = jest.fn() + const fail = jest.fn() + const complete = jest.fn() + + const result = await setClipboardData({ data: 'new content', success, fail, complete }) + + expect(execCommand).toHaveBeenCalledTimes(1) + expect(result.errMsg).toBe(mode === 'succeeds' + ? 'setClipboardData:ok' + : `setClipboardData:fail ${mode === 'throws' ? 'copy denied' : 'Failed to copy to clipboard'}`) + expect(setItem).toHaveBeenCalledTimes(mode === 'succeeds' ? 1 : 0) + expect((await getClipboardData()).data).toBe(mode === 'succeeds' ? 'new content' : 'previous content') + expect(success).toHaveBeenCalledTimes(mode === 'succeeds' ? 1 : 0) + expect(fail).toHaveBeenCalledTimes(mode === 'succeeds' ? 0 : 1) + expect(complete).toHaveBeenCalledTimes(1) + expect(document.querySelector('textarea')).toBeNull() + expect(showToast).toHaveBeenCalledTimes(mode === 'succeeds' ? 1 : 0) + + // Manual copies must resume caching after both successful and failed API calls. + document.dispatchEvent(new Event('copy')) + expect((await getClipboardData()).data).toBe('selected content') + }) + + test.each(['QuotaExceededError', 'SecurityError'])('catches synchronous %s from a manual copy', errorName => { + const error = new DOMException('Clipboard cache write failed', errorName) + jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw error }) + const logError = jest.spyOn(console, 'error').mockImplementation(() => {}) + + document.dispatchEvent(new Event('copy')) + + expect(logError).toHaveBeenCalledTimes(1) + expect(logError).toHaveBeenCalledWith(error) + }) + test.each(['succeeds', 'returns false', 'throws'])('cleans up without textarea.remove when copying %s', async mode => { jest.spyOn(HTMLTextAreaElement.prototype, 'select').mockImplementation(function () { Object.defineProperty(this, 'remove', { value: undefined }) diff --git a/packages/taro-h5/src/api/device/clipboard.ts b/packages/taro-h5/src/api/device/clipboard.ts index 67ffaf04a2a0..254a937cf067 100644 --- a/packages/taro-h5/src/api/device/clipboard.ts +++ b/packages/taro-h5/src/api/device/clipboard.ts @@ -9,18 +9,20 @@ import Taro from '@tarojs/api' import { isFunction } from '@tarojs/shared' import { MethodHandler } from '../../utils/handler' -import { getStorageSync, setStorage, setStorageSync } from '../storage/index' +import { getStorageSync, setStorageSync } from '../storage/index' import { showToast } from '../ui/interaction' const CLIPBOARD_STORAGE_NAME = 'taro_clipboard' +let clipboardCopyDepth = 0 document.addEventListener('copy', () => { - setStorage({ - key: CLIPBOARD_STORAGE_NAME, - data: window.getSelection()?.toString() - }).catch(e => { + // Programmatic copies update the cache only after execCommand succeeds. + if (clipboardCopyDepth > 0) return + try { + setStorageSync(CLIPBOARD_STORAGE_NAME, window.getSelection()?.toString()) + } catch (e) { console.error(e) - }) + } }) /** @@ -43,6 +45,7 @@ export const setClipboardData: typeof Taro.setClipboardData = async ({ data, opt textarea.style.width = '100px' textarea.style.left = '-10000px' document.body.appendChild(textarea) + clipboardCopyDepth++ try { textarea.select() textarea.setSelectionRange(0, textarea.value.length) @@ -50,6 +53,7 @@ export const setClipboardData: typeof Taro.setClipboardData = async ({ data, opt throw new Error('Failed to copy to clipboard') } } finally { + clipboardCopyDepth-- if (textarea.parentNode) { textarea.parentNode.removeChild(textarea) }