在Html和JavaScript中如何使用web share API进行本机分享选项

在Html和JavaScript中如何使用web share API进行本机分享选项

Web Share API 是一个JavaScript API,允许网站通过与操作系统集成,通过设备的本机分享对话框分享 文本/URL/文件 。它仅适用于 移动设备 和部分浏览器。它首次在Chrome 61上为安卓引入。

web share API的特点:

  • 能够分享URL、纯文本或文件。
  • 本机、用户友好和用户定制的分享对话框。
  • 代码量较少且由操作系统管理的用户界面。(开发人员不需要手动处理对话框)
  • 广泛的共享选项。(开发人员无需担心)

    web share API的限制:

  • 仅支持特定的浏览器和设备。(建议添加备用方案以防止兼容性问题)

  • 仅通过HTTPS可用。
  • 为了防止错误操作,它只能作为对某些用户动作的响应而触发,例如点击。

注意: Web share API不支持桌面设备和非HTTPS协议。因此,需要通过HTTPS提供网页以使用它。

示例:

<!DOCTYPE html>
<html>
 
<head>
    <title>
        How to use web share API for native 
        share options in HTML and JavaScript?
    </title>
</head>
 
<body style="text-align: center;">
    <h1 style="color: green;">GeeksforGeeks</h1>
 
    <h2>Web Share API Demonstration</h2>
 
    <button id="shareBtn">Share</button>
 
    <script>
        document.querySelector('#shareBtn')
        .addEventListener('click', event => {
 
            // Fallback, Tries to use API only
            // if navigator.share function is
            // available
            if (navigator.share) {
                navigator.share({
 
                    // Title that occurs over
                    // web share dialog
                    title: 'GeeksForGeeks',
 
                    // URL to share
                    url: 'https://geeksforgeeks.org'
                }).then(() => {
                    console.log('Thanks for sharing!');
                }).catch(err => {
 
                    // Handle errors, if occurred
                    console.log(
                    "Error while using Web share API:");
                    console.log(err);
                });
            } else {
 
                // Alerts user if API not available 
                alert("Browser doesn't support this API !");
            }
        })
    </script>
</body>
 
</html>

输出:

在Html和JavaScript中如何使用web share API进行本机分享选项

参考: https://developer.mozilla.org/zh-CN/docs/Web/API/Navigator/share

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程