Tips & Tricks

Web Share API Usage Guide dengan Claude Code

Pelajari tentang web share api usage guide menggunakan Claude Code. Dilengkapi tips praktis dan contoh kode.

berbagi体験をpenyediaan Web Share APIでネイティブ

Web Share API 使えば、OSネイティブ berbagidialog 呼び出せ.mobile LINEやX(Twitter) dll.、インストール済み aplikasi 直接berbagi き、pengguna体験 大幅 向上.

implementasi dasar的なberbagitombol

> Web Share API 使ったberbagitombol buatkan.
> 非dukunganbrowser SNSリンク フォールバック tampilkan.
// components/ShareButton.tsx
import { useState } from 'react';

interface ShareButtonProps {
  title: string;
  text: string;
  url: string;
}

export function ShareButton({ title, text, url }: ShareButtonProps) {
  const [showFallback, setShowFallback] = useState(false);
  const canShare = typeof navigator !== 'undefined' && !!navigator.share;

  const handleShare = async () => {
    if (canShare) {
      try {
        await navigator.share({ title, text, url });
      } catch (err) {
        if ((err as Error).name !== 'AbortError') {
          setShowFallback(true);
        }
      }
    } else {
      setShowFallback(true);
    }
  };

  return (
    <div className="relative">
      <button
        onClick={handleShare}
        className="flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-white hover:bg-blue-700"
      >
        <ShareIcon />
        共有する
      </button>

      {showFallback && (
        <ShareFallback title={title} url={url} onClose={() => setShowFallback(false)} />
      )}
    </div>
  );
}

function ShareIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M4 12v8a2 2 0 002 2h12a2 2 0 002-2v-8" />
      <polyline points="16 6 12 2 8 6" />
      <line x1="12" y1="2" x2="12" y2="15" />
    </svg>
  );
}

SNSフォールバックkomponen

// components/ShareFallback.tsx
interface ShareFallbackProps {
  title: string;
  url: string;
  onClose: () => void;
}

function ShareFallback({ title, url, onClose }: ShareFallbackProps) {
  const encodedUrl = encodeURIComponent(url);
  const encodedTitle = encodeURIComponent(title);

  const platforms = [
    {
      name: 'X (Twitter)',
      href: `https://twitter.com/intent/tweet?text=${encodedTitle}&url=${encodedUrl}`,
      color: 'bg-black',
    },
    {
      name: 'Facebook',
      href: `https://www.facebook.com/sharer/sharer.php?u=${encodedUrl}`,
      color: 'bg-blue-600',
    },
    {
      name: 'LINE',
      href: `https://social-plugins.line.me/lineit/share?url=${encodedUrl}`,
      color: 'bg-green-500',
    },
    {
      name: 'てなブックマーク',
      href: `https://b.hatena.ne.jp/entry/${url}`,
      color: 'bg-blue-400',
    },
  ];

  return (
    <div className="absolute right-0 top-full mt-2 w-56 rounded-xl border bg-white p-3 shadow-lg dark:bg-gray-800">
      <div className="mb-2 flex items-center justify-between">
        <span className="text-sm font-medium">共有先を選択</span>
        <button onClick={onClose} className="text-gray-400 hover:text-gray-600">&times;</button>
      </div>
      <div className="space-y-1">
        {platforms.map(p => (
          <a
            key={p.name}
            href={p.href}
            target="_blank"
            rel="noopener noreferrer"
            className={`block rounded-lg ${p.color} px-3 py-2 text-sm text-white transition-opacity hover:opacity-80`}
          >
            {p.name}
          </a>
        ))}
      </div>
      <button
        onClick={() => { navigator.clipboard.writeText(url); onClose(); }}
        className="mt-2 w-full rounded-lg bg-gray-100 px-3 py-2 text-sm hover:bg-gray-200 dark:bg-gray-700"
      >
        URLをコピー
      </button>
    </div>
  );
}

berbagi file

// gambarやfile berbagi
async function shareFile(file: File, title: string): Promise<void> {
  if (!navigator.canShare?.({ files: [file] })) {
    console.log('fileberbagi 非dukungan す');
    return;
  }

  await navigator.share({
    title,
    files: [file],
  });
}

// Canvasgambar berbagi
async function shareCanvasImage(canvas: HTMLCanvasElement): Promise<void> {
  const blob = await new Promise<Blob | null>(resolve =>
    canvas.toBlob(resolve, 'image/png')
  );
  if (!blob) return;

  const file = new File([blob], 'image.png', { type: 'image/png' });
  await shareFile(file, 'generategambar');
}

Web Share Target API

PWA sebagai berbagiターゲット registrasi こ dan 、他 aplikasi dari berbagi 受け取るこ dan juga bisa dilakukan.

{
  "share_target": {
    "action": "/share-receiver",
    "method": "POST",
    "enctype": "multipart/form-data",
    "params": {
      "title": "title",
      "text": "text",
      "url": "url",
      "files": [
        {
          "name": "media",
          "accept": ["image/*", "video/*"]
        }
      ]
    }
  }
}

Summary

Untuk Web Share APIは、mobilepenggunaに特に効果的なberbagi機能をpenyediaanします。Claude Codeを使えば、clipboardAPIとintegrasiしたフォールバック付きのimplementasiをefisienにpembangunanできます。PWAと組み合わせれば、berbagiターゲットとしての機能もpenambahandimungkinkanです。詳しい仕様, lihat MDN Web Docs - Web Share API.

#Claude Code #Web Share API #SNSberbagi #mobile #PWA