JAVASCRIPT

Share Content via Web Share API

Integrate the browser's native Web Share API, allowing users to share text, URLs, or files directly from your web application to other installed services.

    /**
     * Shares content using the Web Share API.
     * @param {object} shareData - An object conforming to the Navigator.share() API.
     *                             Must include at least one of: url, text, title, or files.
     *                             Example: { title: 'My Article', text: 'Check this out!', url: 'https://example.com/article/123' }
     *                             For files: { files: [new File(['content'], 'my-file.txt', { type: 'text/plain' })] }
     */
    async function shareContent(shareData) {
        if (!navigator.share) {
            console.warn('Web Share API is not supported in this browser.');
            // Fallback: implement a custom share dialog or copy to clipboard
            // Example fallback:
            // if (shareData.url) {
            //     prompt("Copy this URL:", shareData.url);
            // } else if (shareData.text) {
            //     prompt("Copy this text:", shareData.text);
            // }
            alert('Web Share API not supported. Please copy the URL or text manually.');
            return;
        }

        // Validate if files can be shared
        if (shareData.files && navigator.canShare && !(await navigator.canShare(shareData))) {
            console.error('Cannot share files with the provided data.');
            alert('Sharing files is not supported or allowed for this content.');
            return;
        }

        try {
            await navigator.share(shareData);
            console.log('Content shared successfully!');
        } catch (error) {
            if (error.name === 'AbortError') {
                console.log('User cancelled share.');
            } else {
                console.error('Error sharing content:', error);
            }
        }
    }

    // --- Example Usage ---

    // 1. Sharing text and URL
    /*
    document.getElementById('shareArticleBtn').addEventListener('click', () => {
        shareContent({
            title: 'Awesome Blog Post',
            text: 'I just read this amazing article about API integrations.',
            url: 'https://blog.example.com/api-integrations-post'
        });
    });
    */

    // 2. Sharing files (requires user interaction, e.g., via <input type="file">)
    /*
    document.getElementById('shareFileBtn').addEventListener('click', async () => {
        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.multiple = true;
        fileInput.onchange = async (e) => {
            const files = Array.from(e.target.files);
            if (files.length > 0) {
                await shareContent({
                    files: files,
                    title: 'Shared Files from My App',
                    text: 'Take a look at these documents!'
                });
            }
        };
        fileInput.click(); // Programmatically click the hidden file input
    });
    */

    // Minimal check before attaching event listeners:
    // if (navigator.share) {
    //     console.log("Web Share API supported.");
    //     // You can now safely show share buttons.
    // } else {
    //     console.log("Web Share API not supported, consider fallback.");
    //     // Hide share buttons or show fallback.
    // }
How it works: This snippet demonstrates how to use the browser's native Web Share API to allow users to share content directly from a web application. The `shareContent` function checks for `navigator.share` support and then calls it with an object containing `title`, `text`, `url`, or `files`. It includes handling for user cancellations (`AbortError`) and general sharing errors. A `navigator.canShare` check is also included for sharing files, ensuring the browser supports the given data type for sharing. This integrates browser capabilities into your web app for a seamless sharing experience.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs