為提升隱私權和安全性,第三方 iframe 中的 Web Share API 呼叫現在必須明確允許。
本文將介紹 Web Share API 中可能造成中斷的變更。這項異動已在 Firefox 生效,Chrome 110 版也將採用,Safari 預計不久後也會跟進。
Web Share API 可讓您分享文字、網址或檔案。最簡單的分享碼如下所示:
try {
await navigator.share({
title: 'Title',
text: 'Text',
url: location.href,
});
} catch (err) {
console.error(`${err.name}: ${err.message}`);
}
如果分享動作需要在第三方 iframe 中進行,根據最近的規格變更,您必須明確允許這項作業。方法是在 <iframe>
標記中加入 allow
屬性,並將值設為 web-share
。這會告知瀏覽器,嵌入網站允許嵌入的第三方 iframe 觸發分享動作。
<!DOCTYPE html>
<html lang="en">
<body>
<h1>Web Share in third-party iframes</h1>
<!-- The embedding page is hosted on https://example.com/index.html. -->
<iframe allow="web-share" src="https://third-party.example.com/iframe.html"></iframe>
</body>
</html>
如要查看實際運作情形,請參閱 GitHub 上的示範,並查看原始碼。如未提供屬性,系統會傳回 NotAllowedError
,並顯示 Failed to execute 'share' on 'Navigator': Permission denied
訊息。所有瀏覽器供應商都同意這項限制,目的是為了提升使用者隱私和安全性,並防止不肖人士 (例如濫用廣告) 觸發非預期的分享動作。