Mailto → Gmail Draft Redirector

Replace all mailto: links with Gmail compose draft links

// ==UserScript==
// @name         Mailto → Gmail Draft Redirector
// @author       Mr005K
// @version      1.0
// @description  Replace all mailto: links with Gmail compose draft links
// @match        *://*/*
// @license      MIT
// @grant        none
// @namespace https://gf.qytechs.cn/users/1226710
// ==/UserScript==

(function () {
    'use strict';

    // Convert mailto into Gmail compose link
    function mailtoToGmail(url) {
        try {
            const mailto = new URL(url);
            if (mailto.protocol !== 'mailto:') return null;

            const to = mailto.pathname; // recipient email
            const params = new URLSearchParams(mailto.search);

            const subject = params.get('subject') || '';
            const body = params.get('body') || '';

            const gmail = new URL('https://mail.google.com/mail/');
            gmail.searchParams.set('view', 'cm');
            gmail.searchParams.set('fs', '1');
            if (to) gmail.searchParams.set('to', to);
            if (subject) gmail.searchParams.set('su', subject);
            if (body) gmail.searchParams.set('body', body);

            return gmail.toString();
        } catch (e) {
            return null;
        }
    }

    // Replace all mailto links on page
    function replaceMailtoLinks(root = document) {
        const links = root.querySelectorAll('a[href^="mailto:"]');
        links.forEach(link => {
            const gmailUrl = mailtoToGmail(link.href);
            if (gmailUrl) link.href = gmailUrl;
        });
    }

    // Initial run
    replaceMailtoLinks();

    // Watch for dynamically added links
    const observer = new MutationObserver(muts => {
        muts.forEach(m => {
            m.addedNodes.forEach(node => {
                if (node.nodeType === 1) { // ELEMENT_NODE
                    if (node.matches && node.matches('a[href^="mailto:"]')) {
                        replaceMailtoLinks(node.parentNode);
                    } else {
                        replaceMailtoLinks(node);
                    }
                }
            });
        });
    });
    observer.observe(document.body, { childList: true, subtree: true });
})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址