AIアシスタントや大規模言語モデル(LLM)が日常的に使われる現代において、Web上の技術記事の読まれ方は大きく変化しました。読者はただ目で読むだけでなく、ChatGPT、Claude、Cursorなどのチャット画面に記事を貼り付けて、要約や解説、質問を求めることが当たり前になっています。
しかし、ブラウザ上で通常のテキスト選択とコピー(ドラッグして Ctrl + C)を行うと、不要なHTMLタグの混入、見出し構造の崩れ、テーブルの破損、コードブロックの書式消失など、不快な結果になりがちです。
本記事では、Astroで再利用可能な「Copy as Markdown」ボタンを作成し、ブログをAIエージェントに優しい(Agent-Friendly Web)サイトへ進化させる方法を詳しく解説します。
課題:なぜWebページのコピーはAIエージェントと相性が悪いのか?#
一般的なWebページでテキストを選択してコピーすると、次のような問題が発生します:
- クリップボードには、元のセマンティックな構造から切り離されたリッチテキストまたはプレーンテキストが渡されます。
- Markdownリンク、脚注、シンタックスハイライト付きのコードブロック、表組みが断片化してしまいます。
- ページ全体をまとめてコピーすると、ナビゲーションバー、フッター、ボタンのテキスト、広告などの余計なUI要素がAIのコンテキストウィンドウに混入し、トークンを無駄に消費して回答の精度を下げてしまいます。
[!NOTE] ELI5(10歳でもわかる例え話): あなたの記事を美味しいデコレーションケーキだと想像してみてください。WebページのUI(HTMLやCSS)は、ケーキを入れた紙箱やプラスチックのフォーク、飾りリボンにあたります。AIの友達がケーキを食べたいとき、欲しいのは純粋なスポンジケーキ(生のMarkdown)だけです。紙箱やプラスチックのフォーク(HTMLタグやサイドバー、広告)まで一緒に飲み込みたいわけではありません!
解決策:非表示のTextareaに生のMarkdownを埋め込む#
生のMarkdownをブラウザに提供する方法には主に2つあります:
- HTMLデータ属性への埋め込み(例:
data-markdown="..."):DOMツリーが肥大化し、特殊文字(二重引用符や改行コード、バッククォート)のエスケープ漏れで構文エラーが発生しやすく、ブラウザの描画パフォーマンスを損ないます。 - 非表示の
<textarea>要素への埋め込み:これが最も堅牢で推奨されるアプローチです。<textarea>は改行や特殊文字を完全に保護でき、ボタンが押された際にJavaScriptから瞬時に読み出すことができます。
実装ステップ#
ステップ1: CopyMarkdownButton.astro コンポーネントの作成#
src/components/CopyMarkdownButton.astro に独立したコンポーネントを作成します。生のMarkdown文字列(content)を受け取り、LLMの理解を助けるために任意のタイトル(title)と概要(description)を前置します。
ボタンスタイルには daisyUI 5 のユーティリティ(btn btn-sm btn-soft)を採用し、コピー完了時には成功ステート(btn-success)へ切り替わる心地よいインタラクションを持たせます:
---
import { cn } from '@/astro-pure/utils';
interface Props {
content?: string;
title?: string;
description?: string;
class?: string;
}
const { content = '', title, description, class: className } = Astro.props;
// ボタンとtextareaを一意に結びつけるIDを生成
const textareaId = `markdown-payload-${Math.random().toString(36).slice(2, 11)}`;
// LLM向けにタイトルと概要を明確に付与したペイロードを整形
const formattedPayload = [
title && !content.trim().startsWith('# ') ? `# ${title}\n` : '',
description ? `> ${description}\n` : '',
content,
]
.filter(Boolean)
.join('\n')
.trim();
---
<div class="copy-markdown-container inline-flex">
{/* 非表示textareaでMarkdown特殊文字を安全に保持 */}
<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="記事をMarkdown形式でコピー"
title="AIエージェントやノート用にMarkdownをコピー"
>
<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 {
// モダンなAsync Clipboard APIを利用
await navigator.clipboard.writeText(textarea.value);
// daisyUIクラスによる視覚的フィードバック
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');
// トースト通知イベントの発行
document.dispatchEvent(
new CustomEvent('toast', {
detail: { message: 'クリップボードにMarkdownをコピーしました!' },
}),
);
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('Markdownのコピーに失敗しました: ', err);
}
});
});
}
// 初回ロード時およびAstro View Transitions遷移時にイベントを登録
setupCopyMarkdownButtons();
document.addEventListener('astro:page-load', setupCopyMarkdownButtons);
document.addEventListener('astro:after-swap', setupCopyMarkdownButtons);
</script>astro[!TIP] View Transitions(画面遷移)対応の要点: Astroはクライアントサイドのページ遷移に対応しています。
astro:page-loadとastro:after-swapの両方を監視し、dataset.listenerフラグで重複登録を防ぐことで、画面遷移後もイベントが正常に動作し続けます。
ステップ2: 記事レイアウト(BlogPost.astro)への組み込み#
Astro Content Collections では、blog コレクションの各 entry に未コンパイルの生のMarkdownテキストである body プロパティが含まれています。
レイアウトコンポーネントで body を取り出し、記事本文の直前にボタンを配置します:
---
// [!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" />
{/* 記事本文の直前に配置するアクションボタン */}
<div class="not-prose -mt-2 mb-6 flex items-center justify-end">
<CopyMarkdownButton content={body} {title} {description} />
</div>
<slot />
</PageLayout>astro実装によるメリット#
- 優れたAI連携体験: 読者が記事をCursorやClaude Projects、ChatGPTに取り込みたい時、ワンクリックで表・数式・コードブロックを崩さず完全にコピーできます。
- ゼロ・オーバーヘッド: サーバーAPIやランタイムでのHTML→Markdown変換ライブラリは一切不要。静的ビルド時にすべて生成されます。
- daisyUIによる洗練されたデザイン: ライト/ダークモードに自然に溶け込み、軽量かつアクセシブルなUIを提供します。