Skip to content

Commit

Permalink
🐛 fix unable to paste blob images by using navigator.clipboard instea…
Browse files Browse the repository at this point in the history
…d of e.clipboardData
  • Loading branch information
slooi committed Nov 3, 2024
1 parent 68545ae commit 935f1ff
Showing 1 changed file with 14 additions and 28 deletions.
42 changes: 14 additions & 28 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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")
});
}
}
Expand Down

0 comments on commit 935f1ff

Please sign in to comment.