为了更好地保障隐私性和安全性,现在需要明确允许第三方 iframe 中的 Web Share API 调用。
本文介绍了 Web Share API 中一项潜在的重大变更。此更改已在 Firefox 中推出,从版本 110 开始将登陆 Chrome,并预计很快会在 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>
标记添加值为 web-share
的 allow
属性。这会告知浏览器,嵌入网站允许嵌入的第三方 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>
您可以在 Glitch 上的演示中查看此操作的实际效果,并查看源代码。如果不提供该属性,则会导致 NotAllowedError
并显示消息 Failed to execute 'share' on 'Navigator': Permission denied
。所有浏览器供应商都同意此限制旨在加强用户的隐私和安全,并防止不法分子(例如误导性广告)触发意外的分享操作。