In the age of AI assistants, code companions, and Large Language Models (LLMs), reading habits on the web have fundamentally shifted. Readers no longer just read with their eyes; they frequently copy technical posts directly into ChatGPT, Claude, or Cursor to summarize, query, and refactor concepts.
However, standard web copying (highlighting text with a cursor and pressing Ctrl + C) produces frustrating results: mixed HTML junk, broken header structures, mangled tables, and lost code block formatting.
This post walks through how to build a reusable “Copy as Markdown” button for Astro, turning your blog into an Agent-Friendly Web resource.
The Problem: Why Copying from Web Pages Fails AI Agents#
When someone highlights text and copies content from a typical rendered web page:
- The system clipboard receives a stripped rich-text or plain-text representation torn away from its semantic source.
- Markdown links, footnotes, code syntax highlighting blocks, and formatted tables degrade into disconnected fragments.
- When copying entire articles, peripheral interface chrome like navigation headers, footers, buttons, and sidebars bleed into the LLM context window, burning tokens and degrading prompt fidelity.
[!NOTE] ELI5 (Explain Like I’m 10): Imagine your article is a delicious birthday cake. The web UI (HTML/CSS) is the disposable cardboard box, plastic fork, and ribbon wrapped around it. When an AI agent wants to taste your cake, it only wants the pure sponge cake (original Markdown) — it does not want to choke on the cardboard box or plastic wrap (HTML wrappers, sidebars, and ads)!
The Solution: Injecting Raw Markdown into a Hidden Textarea#
There are two common architectural patterns to deliver raw Markdown:
- Injecting into HTML data attributes (such as
data-markdown="..."): This bloats the browser’s DOM tree, creates edge cases with character escaping (quotes, newlines, code ticks), and slows down DOM rendering. - Injecting into a visually hidden
<textarea>element: This is the gold standard. A<textarea>element safely preserves multiline text and special characters without HTML entity escaping issues, while remaining instantly accessible via JavaScript when the copy button is clicked.
Step-by-Step Implementation#
Step 1: Create CopyMarkdownButton.astro#
We create a self-contained component at src/components/CopyMarkdownButton.astro. It accepts the raw Markdown string (content), alongside optional title and description props to enrich the prompt context for LLMs.
The button is styled with daisyUI 5 utility classes (btn btn-sm btn-soft), providing instant visual feedback by switching to btn-success upon a successful copy operation:
---
import { cn } from '@/astro-pure/utils';
interface Props {
content?: string;
title?: string;
description?: string;
class?: string;
}
const { content = '', title, description, class: className } = Astro.props;
// Generate a unique ID to safely link the button to its textarea
const textareaId = `markdown-payload-${Math.random().toString(36).slice(2, 11)}`;
// Ensure the payload has clear title and description headers for LLMs
const formattedPayload = [
title && !content.trim().startsWith('# ') ? `# ${title}\n` : '',
description ? `> ${description}\n` : '',
content,
]
.filter(Boolean)
.join('\n')
.trim();
---
<div class="copy-markdown-container inline-flex">
{/* Hidden textarea preserves raw markdown characters safely */}
<textarea id={textareaId} class="sr-only" aria-hidden="true" tabindex="-1" readonly>{formattedPayload}</textarea>
<button
type="button"
data-target={textareaId}
class={cn(
'copy-markdown-btn btn btn-sm btn-soft rounded-lg gap-1.5 text-xs font-normal border border-border/60 hover:border-primary/50 transition-all cursor-pointer',
className,
)}
aria-label="Copy post as Markdown"
title="Copy Markdown for AI agents or personal notes"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="copy-icon size-3.5 transition-transform"
aria-hidden="true"
>
<rect width="14" height="14" x="8" y="8" rx="2" ry="2"></rect>
<path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"></path>
</svg>
<svg
xmlns="http://www.w3.org/2000/svg"
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.5"
stroke-linecap="round"
stroke-linejoin="round"
class="check-icon hidden size-3.5 text-success"
aria-hidden="true"
>
<polyline points="20 6 9 17 4 12"></polyline>
</svg>
<span class="btn-text">Copy as Markdown</span>
</button>
</div>
<script>
function setupCopyMarkdownButtons() {
const buttons = document.querySelectorAll<HTMLButtonElement>('.copy-markdown-btn');
buttons.forEach((button) => {
if (button.dataset.listener === 'true') return;
button.dataset.listener = 'true';
button.addEventListener('click', async () => {
const targetId = button.getAttribute('data-target');
if (!targetId) return;
const textarea = document.getElementById(targetId) as HTMLTextAreaElement | null;
const btnText = button.querySelector<HTMLElement>('.btn-text');
const copyIcon = button.querySelector<SVGElement>('.copy-icon');
const checkIcon = button.querySelector<SVGElement>('.check-icon');
if (!textarea || !btnText) return;
try {
// Modern Async Clipboard API
await navigator.clipboard.writeText(textarea.value);
// Visual feedback using daisyUI state classes
const originalText = btnText.textContent;
btnText.textContent = 'Copied!';
button.classList.add('btn-success', 'text-success-content');
button.classList.remove('btn-soft');
copyIcon?.classList.add('hidden');
checkIcon?.classList.remove('hidden');
// Dispatch optional toast event
document.dispatchEvent(
new CustomEvent('toast', {
detail: { message: 'Copied Markdown to clipboard!' },
}),
);
setTimeout(() => {
btnText.textContent = originalText;
button.classList.remove('btn-success', 'text-success-content');
button.classList.add('btn-soft');
copyIcon?.classList.remove('hidden');
checkIcon?.classList.add('hidden');
}, 2000);
} catch (err) {
console.error('Failed to copy Markdown: ', err);
}
});
});
}
// Initialize on first load and on Astro View Transitions navigation
setupCopyMarkdownButtons();
document.addEventListener('astro:page-load', setupCopyMarkdownButtons);
document.addEventListener('astro:after-swap', setupCopyMarkdownButtons);
</script>astro[!TIP] View Transitions Compatibility: Astro supports client-side navigation via View Transitions. Listening to both
astro:page-loadandastro:after-swap, guarded bydataset.listener = 'true', prevents duplicate listeners and ensures the button remains fully interactive after soft navigations.
Step 2: Integrate into BlogPost.astro#
Under Astro’s Content Collections, every entry inside the blog collection contains a raw body property representing the uncompiled Markdown text.
Extract body in your layout file and render the button directly above the article contents:
---
// [!code focus]
import CopyMarkdownButton from '@/components/CopyMarkdownButton.astro';
import { Hero } from '@/astro-pure/components/pages';
const {
// [!code focus]
post: { id, data, body },
headings,
} = Astro.props;
const { title, description } = data;
---
<PageLayout ...>
<Hero {data} slot="header" />
{/* Agent-friendly action button positioned right above content */}
<div class="not-prose -mt-2 mb-6 flex items-center justify-end">
<CopyMarkdownButton content={body} {title} {description} />
</div>
<slot />
</PageLayout>astroKey Benefits#
- Superior AI Experience: When readers want to feed your article to Cursor, Claude Projects, or ChatGPT, a single click delivers clean, 100% formatted Markdown with code blocks, headings, and tables intact.
- Zero Runtime Overhead: No server endpoints, no heavy client-side HTML-to-Markdown converters; payloads are injected at static build-time.
- daisyUI Aesthetic: The button is lightweight, fully accessible, and adapts effortlessly to dark and light color themes.