Chrome拡張・ダークモード・OGP取得・タグフィルター・モバイルドラッグの実装
概要
ブックマーク管理PWA「petapeta」にChrome拡張(Manifest V3)、OGP情報の自動取得、タグ/ラベル機能、モバイルタッチドラッグ対応、ダークモード + テーマ切替を一括で実装した。CORSプロキシ経由のOGP取得、Content Scriptによるページ情報抽出、Touch Eventsによるモバイルドラッグの実装パターンを解説する。
課題
- テーマはデフォルトのみで、ダークモードやコルクボード風テーマに対応していない
- モバイル端末でドラッグ&ドロップが動作しない(HTML5 D&D APIはTouch非対応)
- ブックマークにタグを付けてフィルタリングする機能がない
- URLを貼っても手動でタイトル・説明を入力する必要がある
- ブラウザで閲覧中のページをワンクリックで保存できない
解決策
ダークモード + テーマ切替
CSS変数と data-theme 属性セレクタでテーマを切り替える。
:root {
--bg-color: #f5f0e8;
--sidebar-bg: #fff9f0;
--text-primary: #333;
}
[data-theme="dark"] {
--bg-color: #1a1a2e;
--sidebar-bg: #16213e;
--text-primary: #eee;
}
[data-theme="cork"] {
--bg-color: #c4a574;
}
function setTheme(theme: string, save = true): void {
document.documentElement.setAttribute('data-theme', theme);
if (save) {
Storage.saveSettings({ theme });
}
}
モバイルタッチドラッグ対応
Touch Eventsを使い、長押し(500ms)でドラッグモードに入る。
class TouchDragManager {
private longPressTimer: ReturnType<typeof setTimeout> | null = null;
private dragClone: HTMLElement | null = null;
private dragSource: { listIndex: number; cardIndex: number } | null = null;
handleCardTouchStart(e: TouchEvent, card: HTMLElement): void {
this.longPressTimer = setTimeout(() => {
// 触覚フィードバック
if (navigator.vibrate) navigator.vibrate(50);
// クローン要素を作成してドラッグモード開始
this.dragClone = card.cloneNode(true) as HTMLElement;
this.dragClone.classList.add('drag-clone');
document.body.appendChild(this.dragClone);
this.dragSource = {
listIndex: parseInt(card.dataset.listIndex!),
cardIndex: parseInt(card.dataset.cardIndex!),
};
card.classList.add('dragging');
}, 500);
}
handleCardTouchMove(e: TouchEvent): void {
if (!this.dragClone) return;
e.preventDefault();
const touch = e.touches[0];
// クローンを指の位置に追従
this.dragClone.style.left = `${touch.clientX - 50}px`;
this.dragClone.style.top = `${touch.clientY - 30}px`;
// ドロップ先のコンテナをハイライト
const target = document.elementFromPoint(touch.clientX, touch.clientY);
const container = target?.closest('.collection-cards') as HTMLElement | null;
document.querySelectorAll('.drag-over').forEach((el) => el.classList.remove('drag-over'));
container?.classList.add('drag-over');
}
handleCardTouchEnd(e: TouchEvent): void {
if (this.longPressTimer) {
clearTimeout(this.longPressTimer);
this.longPressTimer = null;
}
if (!this.dragClone || !this.dragSource) return;
// ドロップ位置を計算してカード移動
const touch = e.changedTouches[0];
const target = document.elementFromPoint(touch.clientX, touch.clientY);
const container = target?.closest('.collection-cards') as HTMLElement | null;
if (container) {
const toListIndex = parseInt(container.dataset.listIndex!);
Storage.moveCard(
this.dragSource.listIndex, this.dragSource.cardIndex,
toListIndex, 0
);
}
// クリーンアップ
this.dragClone.remove();
this.dragClone = null;
this.dragSource = null;
}
}
タグ/ラベル機能
カードにタグ配列を追加し、複数タグでのOR検索フィルタリングを実装する。
interface CardData {
title: string;
url: string;
tags?: string[];
}
interface CollectionData {
title: string;
cards: CardData[];
}
function filterByTags(
lists: CollectionData[],
selectedTags: string[],
): CollectionData[] {
if (selectedTags.length === 0) return lists;
return lists
.map((list) => ({
...list,
cards: list.cards.filter((card) =>
selectedTags.some((tag) => card.tags?.includes(tag))
),
}))
.filter((list) => list.cards.length > 0);
}
OGP情報取得
CORSプロキシ経由でHTMLを取得し、DOMParserでOGPメタタグを解析する。
interface OGPData {
title: string | undefined;
description: string | undefined;
image: string | undefined;
}
async function fetchOGP(url: string): Promise<OGPData> {
const proxyUrl = `https://api.allorigins.win/raw?url=${encodeURIComponent(url)}`;
const response = await fetch(proxyUrl);
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
return {
title: doc.querySelector('meta[property="og:title"]')
?.getAttribute('content') ?? undefined,
description: doc.querySelector('meta[property="og:description"]')
?.getAttribute('content') ?? undefined,
image: doc.querySelector('meta[property="og:image"]')
?.getAttribute('content') ?? undefined,
};
}
Chrome拡張(Manifest V3)
Content Scriptでページ情報を取得し、ポップアップからpetapetaのタブに直接データを注入する。
// content.ts - OGP取得用Content Script
interface PageInfo {
url: string;
title: string;
description: string | undefined;
image: string | undefined;
}
function getPageInfo(): PageInfo {
return {
url: window.location.href,
title:
document.querySelector('meta[property="og:title"]')
?.getAttribute('content') || document.title,
description:
document.querySelector('meta[property="og:description"]')
?.getAttribute('content') ?? undefined,
image:
document.querySelector('meta[property="og:image"]')
?.getAttribute('content') ?? undefined,
};
}
chrome.runtime.onMessage.addListener(
(request: { action: string }, _sender, sendResponse) => {
if (request.action === 'getPageInfo') {
sendResponse(getPageInfo());
}
}
);
// popup.ts - petapetaのタブに直接localStorage更新
async function saveToCurrentPetapeta(card: CardData): Promise<void> {
const tabs = await chrome.tabs.query({ url: 'http://localhost:3000/*' });
if (tabs.length > 0 && tabs[0].id) {
await chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
func: (newCard: CardData) => {
const raw = localStorage.getItem('petapeta_data');
if (!raw) return;
const data = JSON.parse(raw);
data.lists[0].cards.push(newCard);
localStorage.setItem('petapeta_data', JSON.stringify(data));
location.reload();
},
args: [card],
});
}
}
Manifest V3の構成
{
"manifest_version": 3,
"name": "petapeta",
"version": "1.0.0",
"permissions": ["activeTab", "scripting"],
"action": {
"default_popup": "popup.html",
"default_icon": "icons/icon-48.png"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
}
Before/After表
| 項目 | Before | After |
|---|---|---|
| テーマ | デフォルトのみ | 4種類(デフォルト・ダーク・コルク等) |
| モバイルD&D | 非対応 | Touch Events + 長押しで対応 |
| タグ機能 | なし | タグ付与 + OR検索フィルタリング |
| URL情報取得 | 手動入力 | OGP自動取得(CORSプロキシ経由) |
| ブックマーク保存 | アプリ内操作のみ | Chrome拡張ポップアップからワンクリック保存 |
| Chrome拡張Manifest | なし | Manifest V3対応 |
まとめ
Chrome拡張のContent ScriptでOGPメタタグを直接読み取ることで、CORSプロキシなしでページ情報を取得できる。モバイルでのドラッグ&ドロップはTouch Eventsで独自実装が必要であり、長押し(500ms)でドラッグモードに入るパターンが直感的である。タグフィルタリングは Array.some と Array.includes の組み合わせでOR検索を実現する。将来的にはCloudflare Workersで独自OGPプロキシを構築し、IndexedDBへの移行やクラウド同期(Firebase/Supabase)を検討する。
この記事は、開発の記録をもとに Claude Code が下書きし、私が確認して公開しています。