Copy-Paste Snippet to Replace All mailto Links with a Contact Form

JavaScript snippet that automatically converts mailto links to your contact form across your entire site.

The Snippet

Basic Version

Replace all mailto links on page load:

// Replace all mailto links with contact form
(function() {
  // Your SupportRetriever form URL
  const FORM_URL = 'https://supportretriever.com/form/your-form-id';
  
  // Find all mailto links
  const mailtoLinks = document.querySelectorAll('a[href^="mailto:"]');
  
  // Replace each one
  mailtoLinks.forEach(link => {
    const originalHref = link.getAttribute('href');
    const emailMatch = originalHref.match(/mailto:([^?]+)/);
    
    if (emailMatch) {
      // Keep the visible text, change the URL
      link.setAttribute('href', FORM_URL);
      
      // Add data attribute for reference
      link.setAttribute('data-original-email', emailMatch[1]);
      
      // Optional: Add analytics tracking
      link.setAttribute('data-converted', 'true');
    }
  });
})();

How It Works

  1. Finds all mailto links using a[href^="mailto:"]
  2. Extracts the email address from each link
  3. Replaces href with your form URL
  4. Keeps the visible text unchanged
  5. Adds data attributes for tracking

Before and After

Before (HTML):

<a href="mailto:support@example.com">Contact Support</a>
<a href="mailto:sales@example.com?subject=Inquiry">Talk to Sales</a>

After (rendered):

<a href="https://supportretriever.com/form/your-form-id" 
   data-original-email="support@example.com"
   data-converted="true">Contact Support</a>

<a href="https://supportretriever.com/form/your-form-id" 
   data-original-email="sales@example.com"
   data-converted="true">Talk to Sales</a>

User sees: Exact same link text, but clicking opens form instead of email client.

Advanced Version with Options

With Department Routing

Extract department from email and add to form URL:

(function() {
  const FORM_URL = 'https://supportretriever.com/form/your-form-id';
  
  // Map email addresses to departments
  const departmentMap = {
    'support': 'support',
    'help': 'support',
    'sales': 'sales',
    'press': 'press',
    'info': 'general',
    'contact': 'general'
  };
  
  document.querySelectorAll('a[href^="mailto:"]').forEach(link => {
    const originalHref = link.getAttribute('href');
    const emailMatch = originalHref.match(/mailto:([^@]+)@/);
    
    if (emailMatch) {
      const prefix = emailMatch[1].toLowerCase();
      const department = departmentMap[prefix] || 'general';
      
      // Add department parameter to form URL
      const newHref = `${FORM_URL}?type=${department}&converted=true`;
      link.setAttribute('href', newHref);
      link.setAttribute('data-original-email', emailMatch[0].replace('mailto:', ''));
      link.setAttribute('data-converted', 'true');
    }
  });
})();

Result:

  • mailto:support@example.comform-url?type=support
  • mailto:sales@example.comform-url?type=sales
  • mailto:press@example.comform-url?type=press

With Source Tracking

Add source parameter based on page location:

(function() {
  const FORM_URL = 'https://supportretriever.com/form/your-form-id';
  
  // Determine source from current page
  const path = window.location.pathname;
  let source = 'unknown';
  
  if (path === '/' || path === '/index.html') {
    source = 'homepage';
  } else if (path.includes('/pricing')) {
    source = 'pricing';
  } else if (path.includes('/blog')) {
    source = 'blog';
  } else if (path.includes('/support')) {
    source = 'support-page';
  } else if (path.includes('/contact')) {
    source = 'contact-page';
  }
  
  document.querySelectorAll('a[href^="mailto:"]').forEach(link => {
    const originalHref = link.getAttribute('href');
    const emailMatch = originalHref.match(/mailto:([^?]+)/);
    
    if (emailMatch) {
      // Add source parameter
      const newHref = `${FORM_URL}?source=${source}&converted=true`;
      link.setAttribute('href', newHref);
      link.setAttribute('data-original-email', emailMatch[1]);
    }
  });
})();

With Analytics Integration

Track conversions in Google Analytics:

(function() {
  const FORM_URL = 'https://supportretriever.com/form/your-form-id';
  
  document.querySelectorAll('a[href^="mailto:"]').forEach(link => {
    const originalHref = link.getAttribute('href');
    const emailMatch = originalHref.match(/mailto:([^?]+)/);
    
    if (emailMatch) {
      link.setAttribute('href', FORM_URL);
      link.setAttribute('data-original-email', emailMatch[1]);
      
      // Add click tracking
      link.addEventListener('click', function(e) {
        // Google Analytics 4
        if (typeof gtag !== 'undefined') {
          gtag('event', 'form_link_click', {
            'link_type': 'converted_mailto',
            'original_email': emailMatch[1],
            'page_path': window.location.pathname
          });
        }
        
        // Google Analytics Universal
        if (typeof ga !== 'undefined') {
          ga('send', 'event', 'Contact', 'Click', 'Converted mailto');
        }
      });
    }
  });
})();

Safety Options

Exclude Specific Links

Don't convert certain mailto links:

(function() {
  const FORM_URL = 'https://supportretriever.com/form/your-form-id';
  
  // Emails to exclude from conversion
  const excludeEmails = [
    'personal@example.com',
    'noreply@example.com'
  ];
  
  // Selectors to exclude from conversion
  const excludeSelectors = [
    '.keep-mailto',
    '#footer .personal-email',
    '[data-keep-mailto="true"]'
  ];
  
  document.querySelectorAll('a[href^="mailto:"]').forEach(link => {
    // Check if link should be excluded
    const shouldExclude = excludeSelectors.some(selector => 
      link.matches(selector) || link.closest(selector)
    );
    
    if (shouldExclude) return;
    
    const originalHref = link.getAttribute('href');
    const emailMatch = originalHref.match(/mailto:([^?]+)/);
    
    if (emailMatch && !excludeEmails.includes(emailMatch[1])) {
      link.setAttribute('href', FORM_URL);
      link.setAttribute('data-original-email', emailMatch[1]);
      link.setAttribute('data-converted', 'true');
    }
  });
})();

Usage:

<!-- This will be converted -->
<a href="mailto:support@example.com">Contact Us</a>

<!-- This will NOT be converted (has class) -->
<a href="mailto:personal@example.com" class="keep-mailto">Personal Email</a>

<!-- This will NOT be converted (data attribute) -->
<a href="mailto:john@example.com" data-keep-mailto="true">John's Email</a>

Add Fallback

Provide fallback if form doesn't load:

(function() {
  const FORM_URL = 'https://supportretriever.com/form/your-form-id';
  
  document.querySelectorAll('a[href^="mailto:"]').forEach(link => {
    const originalHref = link.getAttribute('href');
    const emailMatch = originalHref.match(/mailto:([^?]+)/);
    
    if (emailMatch) {
      // Store original mailto in data attribute
      link.setAttribute('data-mailto-fallback', originalHref);
      link.setAttribute('data-original-email', emailMatch[1]);
      
      // Replace with form URL
      link.setAttribute('href', FORM_URL);
      
      // Add error handler
      link.addEventListener('click', function(e) {
        setTimeout(() => {
          // If form didn't load, offer fallback
          const fallback = confirm(
            'Having trouble opening the form? Click OK to use email instead.'
          );
          if (fallback) {
            window.location.href = originalHref;
          }
        }, 5000);
      });
    }
  });
})();

Installation Instructions

Plain HTML Site

Add before closing </body> tag:

<!DOCTYPE html>
<html>
<head>
  <title>Your Site</title>
</head>
<body>
  
  <!-- Your content with mailto links -->
  <a href="mailto:support@example.com">Contact Us</a>
  
  <!-- Add script before closing body tag -->
  <script>
    (function() {
      const FORM_URL = 'https://supportretriever.com/form/your-form-id';
      
      document.querySelectorAll('a[href^="mailto:"]').forEach(link => {
        const originalHref = link.getAttribute('href');
        const emailMatch = originalHref.match(/mailto:([^?]+)/);
        
        if (emailMatch) {
          link.setAttribute('href', FORM_URL);
          link.setAttribute('data-original-email', emailMatch[1]);
        }
      });
    })();
  </script>
</body>
</html>

WordPress

Method 1: Theme Footer

  1. Go to Appearance → Theme Editor
  2. Open footer.php
  3. Add script before </body> tag
  4. Save changes

Method 2: Plugin (Code Snippets)

  1. Install Code Snippets plugin
  2. Add new snippet
  3. Paste the script (without <script> tags)
  4. Set to run in Frontend
  5. Activate snippet

Method 3: Custom Plugin

Create wp-content/plugins/replace-mailto/replace-mailto.php:

<?php
/**
 * Plugin Name: Replace mailto Links
 * Description: Replaces mailto links with contact form
 * Version: 1.0
 */

function replace_mailto_script() {
    ?>
    <script>
    (function() {
      const FORM_URL = 'https://supportretriever.com/form/your-form-id';
      
      document.querySelectorAll('a[href^="mailto:"]').forEach(link => {
        const originalHref = link.getAttribute('href');
        const emailMatch = originalHref.match(/mailto:([^?]+)/);
        
        if (emailMatch) {
          link.setAttribute('href', FORM_URL);
          link.setAttribute('data-original-email', emailMatch[1]);
        }
      });
    })();
    </script>
    <?php
}
add_action('wp_footer', 'replace_mailto_script');

Activate plugin in WordPress admin.

Webflow

  1. Go to Project Settings
  2. Click Custom Code tab
  3. Scroll to Footer Code
  4. Paste script with <script> tags
  5. Publish site
<script>
(function() {
  const FORM_URL = 'https://supportretriever.com/form/your-form-id';
  
  document.querySelectorAll('a[href^="mailto:"]').forEach(link => {
    const originalHref = link.getAttribute('href');
    const emailMatch = originalHref.match(/mailto:([^?]+)/);
    
    if (emailMatch) {
      link.setAttribute('href', FORM_URL);
      link.setAttribute('data-original-email', emailMatch[1]);
    }
  });
})();
</script>

Shopify

  1. Go to Online Store → Themes
  2. Click Actions → Edit Code
  3. Open theme.liquid
  4. Add script before </body> tag
  5. Save changes

Squarespace

  1. Go to Settings → Advanced → Code Injection
  2. Paste in Footer section
  3. Save changes

React/Next.js

Create a hook or component:

// hooks/useReplaceMailto.js
import { useEffect } from 'react';

export function useReplaceMailto(formUrl) {
  useEffect(() => {
    const mailtoLinks = document.querySelectorAll('a[href^="mailto:"]');
    
    mailtoLinks.forEach(link => {
      const originalHref = link.getAttribute('href');
      const emailMatch = originalHref.match(/mailto:([^?]+)/);
      
      if (emailMatch) {
        link.setAttribute('href', formUrl);
        link.setAttribute('data-original-email', emailMatch[1]);
      }
    });
  }, [formUrl]);
}

// Usage in component:
import { useReplaceMailto } from '../hooks/useReplaceMailto';

function Layout({ children }) {
  useReplaceMailto('https://supportretriever.com/form/your-form-id');
  
  return <div>{children}</div>;
}

Testing

Verify It Works

1. Check console for errors:

// Add to snippet for debugging
console.log('mailto replacement script loaded');
console.log('Found ' + mailtoLinks.length + ' mailto links');

2. Inspect converted links:

// Check what was converted
document.querySelectorAll('[data-converted="true"]').forEach(link => {
  console.log('Converted:', link.getAttribute('data-original-email'));
});

3. Test on staging first:

  • Deploy to staging environment
  • Check all pages with mailto links
  • Click each converted link
  • Verify form opens correctly

4. Verify on iPhone Mail:

  • Send test email with mailto link
  • Open in iPhone Mail
  • Tap the link
  • Verify form opens (not email client)

Verify It Works on iPhone Mail

Why This Matters

The iOS 26.1 mailto issue happens specifically when tapping mailto links in Apple Mail, not in web browsers. This snippet solves it for web pages, but email content is different.

For Email Links (HTML Emails)

If you want to fix mailto links in HTML emails you send:

  1. Before sending email, run your HTML through the converter
  2. Or send links to your form instead of mailto links

Example email content:

<!-- Instead of -->
<p>Reply to this email or <a href="mailto:support@example.com">contact support</a></p>

<!-- Use -->
<p>Reply to this email or <a href="https://supportretriever.com/form/your-form-id">contact support</a></p>

Testing Checklist

  • Deploy snippet to your website
  • Test clicking links on iPhone Safari
  • Test clicking links on desktop browsers
  • Send test email with form link (not mailto)
  • Open email on iPhone Mail
  • Tap form link from email
  • Verify form opens in Safari
  • Test form submission
  • Verify notification arrives

Related Topics

Ready to simplify your support?
Join thousands using SupportRetriever to manage customer conversations.
Try Free

Explore More

Browse All Articles