针对第三方 iframe 中的 Web Share API 的新要求

为了提高隐私保护和安全性,现在需要明确允许第三方 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> 标记添加值为 web-shareallow 属性。这会告知浏览器,嵌入网站允许嵌入的第三方 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。所有浏览器供应商都同意实施此限制,以提高用户的隐私和安全性,并防止不良行为者(例如滥用广告)触发意外的分享操作。