From 935f1ffedc59286c011d96f88501333d828a80be Mon Sep 17 00:00:00 2001 From: s Date: Sun, 3 Nov 2024 23:45:35 +0900 Subject: [PATCH] :bug: fix unable to paste blob images by using navigator.clipboard instead of e.clipboardData --- src/main.ts | 42 ++++++++++++++---------------------------- 1 file changed, 14 insertions(+), 28 deletions(-) diff --git a/src/main.ts b/src/main.ts index edc3319..3874f3e 100644 --- a/src/main.ts +++ b/src/main.ts @@ -4,36 +4,22 @@ import './style.css' class ClipboardFileListener { constructor(callback: (imgData: string | ArrayBuffer) => any) { - document.addEventListener("paste", event => { - const items = event.clipboardData?.items; - let notFileCounter = 0 - console.log("items", items); - - // Correct iteration using a for loop - if (!items) throw new Error("Error: no items found") - - for (let i = 0; i < items.length; i++) { - const item = items[i]; - console.log("item", item); - - if (item.kind === 'file') { - console.log("item", item); - const blob = item.getAsFile(); - const reader = new FileReader(); - reader.onload = e => { - if (!e.target?.result) throw new Error("Error: file format not supported") - callback(e.target?.result) - } - reader.onerror = e => { throw new Error(`${e}`) } - - if (!blob) throw new Error("Error: blob was null") - reader.readAsDataURL(blob); - } else { - notFileCounter++ + document.addEventListener("paste", async event => { + const clipboardItems = await navigator.clipboard.read(); + console.log("clipboardItems", clipboardItems) + for (const clipboardItem of clipboardItems) { + const imageTypes = clipboardItem.types?.filter((type) => + type.startsWith("image/") + ); + + for (const imageType of imageTypes) { + const blob = await clipboardItem.getType(imageType); + // const img = document.createElement("img"); + // img.src = ; + // document.body.append(img); + callback(URL.createObjectURL(blob)) } } - - if (notFileCounter === items.length) throw new Error("No image/file found") }); } }