From Copy Text to Copy Image: A Reusable Blazor Clipboard Component



It all started with one of those tiny, repetitive annoyances that slowly drives a developer crazy. Whenever I needed an email template token like %%CustomerName%%, I’d have to carefully highlight it, squinting to make sure I grabbed every single percent sign. Dropping in a simple "Copy" button fixed that in a heartbeat. But then I thought—what about images? Why not use the exact same approach for copying a release badge or a report graphic right into an email or document?

So, I built it out. I kept the name CopyableValue because, from the user's perspective, the job hasn't changed: see the target, click a button, and get a clear confirmation. The real magic just happens under the hood depending on what's hitting the clipboard.



Component mockup: the same interaction works for a template token and a release badge.

Same Interaction, Two Formats

Handling text is straightforward: the component just calls navigator.clipboard.writeText(). Images, on the other hand, require the actual image bytes. You have to package those bytes into a ClipboardItem and hand them off to navigator.clipboard.write(). If you mistakenly pass an image URL to writeText(), you'll just end up with a raw link on the clipboard. But write the actual PNG data, and you can paste the image directly into any rich-text editor.

The browser needs a different clipboard format for each payload.

Here’s what the text setup looks like on a Blazor page:

<CopyableValue Label="Email template token" Value="%%CustomerName%%" />

For the image mode, the component needs a few extra pieces: a preview, some solid alt text, and the image source itself. I highly recommend labeling your buttons clearly—like Copy text and Copy image—so users know exactly what to expect before they click.

The JavaScript Glue

The code below assumes you're serving a PNG from the same app. This little JavaScript helper handles both text and image modes. The trick is to call it directly from the native button's click handler. Blazor can supply the value and take care of the success or failure callbacks once the browser wraps up the clipboard write.

export async function copyValue({ text, pngUrl }) {
  if (!navigator.clipboard) {
    throw new Error("Clipboard access is unavailable.");
  }

  if (!pngUrl) {
    await navigator.clipboard.writeText(text);
    return;
  }

  if (typeof ClipboardItem === "undefined" ||
      !navigator.clipboard.write) {
    throw new Error("Image copying is unavailable.");
  }

  const png = fetch(pngUrl).then(async response => {
    if (!response.ok) throw new Error("Image download failed.");
    const blob = await response.blob();
    if (blob.type !== "image/png") {
      throw new Error("Expected a PNG image.");
    }
    return blob;
  });

  // Start the clipboard write during the original click.
  await navigator.clipboard.write([
    new ClipboardItem({ "image/png": png })
  ]);
}

Timing is everything here. Modern browsers are pretty strict and often require a clipboard write to initiate during an active "user gesture" (like a click). In our image logic, fetch() fires off a promise for the PNG, while clipboard.write() starts right away. If you're running Blazor Server, wiring up a @onclick handler and making a round trip to the server before hitting JavaScript will likely lose that user gesture context, causing the browser to block the write.

My advice? Attach this browser handler as soon as the component becomes interactive, and clean up the listener using the module’s dispose lifecycle.

Also, keep the security context in mind: stick to HTTPS and same-origin PNGs to start. While an <img> tag can preview a cross-origin image just fine, JavaScript can’t fetch those raw bytes without explicit CORS permission from the image server. And no, you can't just rename a .jpg to .png and trick the browser. Serve an actual PNG, or build in a conversion step if you need to support other formats.

Making Success and Failure Visible

Accessibility matters. By sticking to a native <button>, we get Tab, Enter, and Spacebar support for free. I like to keep the button label stable, leave the focus exactly where it is, and update a nearby role="status" element once the clipboard operation succeeds or fails. If the browser happens to block the write, make sure the text remains selectable, and the image has a fallback link to open or download it.

Here’s my go-to smoke test for this:

  • Paste the copied token into a plain text field.
  • Paste the copied badge into an email or rich-text editor.
  • Try doing both entirely via the keyboard.

Be sure to also test the edge cases—what happens when the image is missing, the clipboard write is blocked, or you're viewing a long label on a narrow mobile screen. Keep in mind, the code above is a structural example to get you started; you'll want to thoroughly browser-test it in your own environment.

The Real-World Demo

If I were demoing this to the team, here's exactly what I'd show: I'd open up our email template editor and copy a token straight into the message body. Next, I'd tab over to the release portal, copy a release badge, and paste it into a blank Word doc. Then, I'd paste its raw URL as text just to highlight the difference. Finally, I'd intentionally block clipboard access in the browser settings to prove the component degrades gracefully and recovers without crashing the page.


[sample code]

Comments

Popular posts from this blog

Customizing PWA Manifest and Icons for a Polished User Experience 🚀

Offline-First Strategy with Blazor PWAs: A Complete Guide 🚀