|
| 1 | + |
| 2 | +let isWaiting = false; |
| 3 | + |
| 4 | +const previewElement = document.querySelector(".preview"); |
| 5 | +const previewImageElement = previewElement?.querySelector(".ogpImage"); |
| 6 | +const previewTitleElement = previewElement?.querySelector(".ogpTitle"); |
| 7 | +const previewDescriptionElement = |
| 8 | + previewElement?.querySelector(".ogpDescription"); |
| 9 | + |
| 10 | +previewElement?.addEventListener("interest", async (event) => { |
| 11 | + const sourceElement = event.source; |
| 12 | + const url = sourceElement.href; |
| 13 | + |
| 14 | + // プレビュー要素を現在のリンクにアンカー |
| 15 | + if (previewElement) { |
| 16 | + previewElement.style.positionAnchor = sourceElement.style.anchorName; |
| 17 | + } |
| 18 | + isWaiting = false; |
| 19 | + const response = await fetch(url); |
| 20 | + const html = await response.text(); |
| 21 | + |
| 22 | + // DOMParserでHTMLをパース |
| 23 | + const parser = new DOMParser(); |
| 24 | + const doc = parser.parseFromString(html, "text/html"); |
| 25 | + |
| 26 | + // タイトルを取得(og:title) |
| 27 | + const title = doc.querySelector(`meta[property="og:title"]`)?.getAttribute("content") ?? ""; |
| 28 | + |
| 29 | + // 説明を取得(og:description) |
| 30 | + const description = |
| 31 | + doc.querySelector(`meta[property="og:description"]`)?.getAttribute("content") ?? ""; |
| 32 | + |
| 33 | + // 画像を取得(og:image) |
| 34 | + const image = doc.querySelector(`meta[property="og:image"]`)?.getAttribute("content") ?? ""; |
| 35 | + |
| 36 | + // 画像の読み込みが完了するまで待つ |
| 37 | + await awaitImageLoad(image); |
| 38 | + previewImageElement.src = image; |
| 39 | + previewTitleElement.textContent = title; |
| 40 | + previewDescriptionElement.textContent = description; |
| 41 | + |
| 42 | + // OGPデータの取得が完了したらプレビューを表示 |
| 43 | + previewElement?.showPopover?.(); |
| 44 | +}); |
| 45 | + |
| 46 | +previewElement?.addEventListener("loseinterest", async () => { |
| 47 | + isWaiting = true; |
| 48 | + // アニメーションを待つために250ms待つ |
| 49 | + await new Promise((resolve) => setTimeout(resolve, 250)); |
| 50 | + |
| 51 | + // プレビューを非表示 |
| 52 | + if (isWaiting) { |
| 53 | + // データをクリア |
| 54 | + previewImageElement.src = ""; |
| 55 | + previewTitleElement.textContent = ""; |
| 56 | + previewDescriptionElement.textContent = ""; |
| 57 | + previewElement?.hidePopover?.(); |
| 58 | + isWaiting = false; |
| 59 | + } |
| 60 | +}); |
| 61 | + |
| 62 | +const awaitImageLoad = async (image) => { |
| 63 | + return new Promise((resolve) => { |
| 64 | + const img = new Image(); |
| 65 | + img.onload = () => { |
| 66 | + return resolve(); |
| 67 | + }; |
| 68 | + img.src = image; |
| 69 | + }); |
| 70 | +}; |
0 commit comments