Why Electron.js Clipboard returns the same image twice while doing clipboard.readImage()?

16 views Asked by At

I'm developing an Electron app where I'm implementing a feature to monitor the clipboard for changes and capture images when they are copied. I've set up a listener function to detect image changes in the clipboard using the electron module's clipboard functionality.

However, I've encountered an issue where duplicate images are sometimes captured, particularly when using the Snipping Tool in Windows. Despite implementing logic to filter out duplicate images, the app still occasionally captures two images instead of one.

Here's a simplified version of my clipboardWatcher function:

const { clipboard } = require("electron");

export function clipboardWatcher({
  watchDelay = 1000,
  onImageChange,
  onTextChange,
}) {
  let lastText = clipboard.readText();
  let lastImage = clipboard.readImage();

  const intervalId = setInterval(() => {
    const text = clipboard.readText();
    const image = clipboard.readImage();

    if (onImageChange && imageHasDiff(image, lastImage)) {
      lastImage = image;
      onImageChange(image);
    }

    if (onTextChange && textHasDiff(text, lastText)) {
      lastText = text;
      onTextChange(text);
    }
  }, watchDelay);

  return {
    stop: () => clearInterval(intervalId),
  };
}

function imageHasDiff(a, b) {
  return !a.isEmpty() && b.toDataURL() !== a.toDataURL();
}

function textHasDiff(a, b) {
  return a && b !== a;
}

I suspect that my imageHasDiff function might not accurately identify duplicate images. Is there a better approach to comparing images in an Electron app to ensure that only unique images are captured? Should I consider using a different method for comparing images, such as comparing pixel data or using image processing techniques?

I have noticed that when logging out the data URL of a copied image, I get two different URLs for the same copied image. This observation aligns with the issue I'm experiencing where duplicate images are captured despite there being only one copied image.

Any suggestions or insights would be greatly appreciated. Thank you!

0

There are 0 answers