【问题标题】:How to simulate paste from clipboard in Playwright?如何在 Playwright 中模拟剪贴板中的粘贴?
【发布时间】:2022-11-04 22:59:08
【问题描述】:

我正在尝试使用 Playwright 测试图像粘贴功能。

我设法将图像复制到剪贴板,但无法粘贴。 这是我的代码。

 test.only("Clipboard", async ({browser}, testInfo) => {
        const context = await browser.newContext({ permissions: ["clipboard-read", "clipboard-write"] });
        const page = await context.newPage();

        await page.evaluate(async () => {
            const base64 = `data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
            AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
                9TXL0Y4OHwAAAABJRU5ErkJggg==`;

            const response = await fetch(base64);
            const blob = await response.blob();
            await navigator.clipboard.write([new ClipboardItem({ "image/png": blob })]);

            const clipboardImageHolder = document.getElementById("clipboard-image");
            clipboardImageHolder.focus();
            const result = await navigator.clipboard.readText();
            console.log(result);
        });
    });

当我运行测试时,然后按 Ctrl+v manaull;我看到粘贴在 div 元素中的图像

【问题讨论】:

    标签: javascript playwright


    【解决方案1】:

    最后,这对我有用。

      await page.evaluate(async () => {
                const base64 = `data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
                AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
                    9TXL0Y4OHwAAAABJRU5ErkJggg==`;
    
                const response = await fetch(base64);
                const blob = await response.blob();
                const clipboardImageHolder = document.getElementById("you-are-the-one");
                clipboardImageHolder.focus();
    
                let pasteEvent = new Event("paste", { bubbles: true, cancelable: true });
                pasteEvent = Object.assign(pasteEvent, {
                    clipboardData: {
                        items: {
                            a: {
                                kind: "file",
                                getAsFile() {
                                    return new File([blob], "foo.png", { type: blob.type });
                                },
                            },
                        },
                    },
                });
    
                console.log("event", pasteEvent);
                clipboardImageHolder.dispatchEvent(pasteEvent);
            });
    
    

    我不得不调度paste 事件并添加clipboardData 对象。

    【讨论】:

      猜你喜欢
      • 2017-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多