把網頁變得像手機 App 的關鍵一步,就是呼叫系統「原生分享面板」! 📤 🔗
這篇會帶你用 Web Share 分享連結、檔案、Canvas 截圖,行動裝置支援最好,桌機則是逐年進步!
navigator.share(data)
:呼叫系統原生分享面板。data
可帶 title
、text
、url
、files
。navigator.canShare({ files })
:檢查是否支援分享檔案(含大小/型別等條件)。連結/文字分享只需檢查 navigator.share
是否存在;不要用 navigator.canShare
來判斷這種情況。
<button id="btnShare">Share</button>
<script>
document.getElementById('btnShare').addEventListener('click', async () => {
if (!navigator.share) {
alert('此裝置/瀏覽器不支援 Web Share');
return;
}
try {
await navigator.share({
title: document.title,
text: '看看這頁',
url: location.href
});
} catch (e) {
/* 使用者取消不算錯 */
}
});
</script>
檔案分享在平台/瀏覽器上限制較多(容量、型別、來源),所以先用 navigator.canShare({ files })
檢查。
<input type="file" id="fileInput" multiple />
<button id="btnShareFiles">Share selected files</button>
<script>
const picker = document.getElementById('fileInput');
document.getElementById('btnShareFiles').addEventListener('click', async () => {
const files = Array.from(picker.files || []);
if (!files.length) return alert('請先選檔');
if (navigator.canShare && navigator.canShare({ files })) {
try {
await navigator.share({ files, title: '檔案分享' });
}
catch (e) {
/* 使用者取消 */
}
} else {
alert('此裝置/瀏覽器暫不支援分享檔案');
}
});
</script>
<canvas id="cv" width="160" height="90"></canvas>
<button id="btnShareCanvas">Share Canvas</button>
<script>
const cv = document.getElementById('cv');
const ctx = cv.getContext('2d');
ctx.fillStyle = '#09f';
ctx.fillRect(0,0,160,90); // 畫點東西
document.getElementById('btnShareCanvas').addEventListener('click', async () => {
const blob = await new Promise(r => cv.toBlob(r, 'image/png'));
const file = new File([blob], 'screenshot.png', { type: 'image/png' });
if (navigator.canShare && navigator.canShare({ files: [file] })) {
try {
await navigator.share({ files: [file], title: 'Canvas Screenshot' });
}
catch (e) {
/* 使用者取消 */
}
} else {
// Fallback:下載檔案
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'screenshot.png';
a.click();
URL.revokeObjectURL(a.href);
}
});
</script>
<button id="btnShareFallback">Share (with fallback)</button>
<script>
const fallbackShare = async () => {
const url = location.href;
try {
await navigator.clipboard.writeText(url);
alert('已複製連結');
}
catch {
prompt('請手動複製以下連結', url);
}
};
document.getElementById('btnShareFallback').addEventListener('click', async () => {
if (navigator.share) {
try {
await navigator.share({ title: document.title, url: location.href });
return;
}
catch (e) {
/* 取消則走 fallback */
}
}
await fallbackShare();
});
</script>
share()
。navigator.canShare({ files })
;不支援就走 Copy Link / 下載 的替代路徑。上面用簡單程式碼示範了「分享連結、檔案、Canvas 截圖」的基本流程。
想直接體驗完整互動,請看這個線上範例(本文截圖也來自這裡):
👉 歡迎追蹤這個系列,我會從 Canvas 開始,一步步帶你認識更多 Web API 🎯