# UTM Cleanup Script Interference

**Last Updated:** 2026-01-29

## Overview

This document describes script interference issues where other JavaScript files clean URL parameters (including UTMs) before the UTM tracker can initialize, causing cleanup to fail on excluded pages.

## Problem: pricing-page.js Interference

### Root Cause

The `pricing-page.js` script contains URL cleaning logic that runs immediately on page load (via IIFE) and removes ALL URL parameters, including UTM parameters, BEFORE the UTM tracker can initialize.

**Affected Pages:**
- `/gastro` (paid_nonbrand.php) - includes pricing-page.min.js
- `/schichtbetriebe` (paid_schichtbetriebe.php) - includes pricing-page.min.js
- `/v3` (landingpage_v3.php) - does NOT include pricing-page.js (no interference)

### Original Code Issue

```javascript
// In pricing-page.js lines 386-392 (BEFORE FIX)
// Clean URL on page load if it has parameters
(function() {
  if (window.location.search) {
    const cleanUrl = new URL(window.location.origin + window.location.pathname);
    window.history.replaceState({}, '', cleanUrl.toString());
  }
})();
```

**Problem:** This IIFE executes immediately when the script loads, removing all query parameters including UTMs, before the UTM tracker can:
1. Extract UTM parameters
2. Store them in cookies/instance variables
3. Check if the page is excluded

### Solution

Modified `pricing-page.js` to check for excluded pages before cleaning URLs:

```javascript
// In pricing-page.js lines 386-406 (AFTER FIX)
// Clean URL on page load if it has parameters (but NOT on excluded pages)
(function() {
  // Check if page is excluded from URL cleaning
  const excludedPages = ['/v3', '/gastro', '/schichtbetriebe'];
  const currentPath = window.location.pathname;
  const isPageExcluded = excludedPages.some(path => 
    currentPath === path || currentPath.startsWith(path + '/')
  );
  
  // Skip URL cleaning on excluded pages
  if (isPageExcluded) {
    console.log('[Pricing Page] URL cleaning skipped - Excluded page:', currentPath);
    return;
  }
  
  // Only clean URL if it has parameters AND page is not excluded
  if (window.location.search) {
    const cleanUrl = new URL(window.location.origin + window.location.pathname);
    window.history.replaceState({}, '', cleanUrl.toString());
  }
})();
```

**Also Fixed:** Similar exclusion check added at line 2545-2549 for comparison table initialization.

## Detection

### Symptoms

- UTMs removed immediately on page load
- No console messages from UTM tracker exclusion logic
- Happens specifically on pages that include pricing-page.js
- Analytics may not capture UTMs (if removed before analytics scripts load)

### Diagnosis Steps

1. **Check Console Messages:**
   ```javascript
   // Should see: [Pricing Page] URL cleaning skipped - Excluded page: /gastro
   // Should see: [UTM Cleanup] Cleanup DISABLED via excluded page
   ```

2. **Check Script Load Order:**
   - Open Network tab in DevTools
   - Check when pricing-page.min.js loads
   - Verify it loads after head.php (which includes utm-tracking)
   - The IIFE runs immediately when script loads

3. **Verify Exclusion Logic:**
   - Check pricing-page.js has exclusion check
   - Verify excluded pages array matches utm-tracking.js
   - Check pricing-page.min.js was regenerated after changes

4. **Test URL:**
   ```
   http://localhost:8003/gastro?utm_source=test&utm_campaign=test&utm_debug=true
   ```
   - UTMs should remain in URL
   - Console should show exclusion messages

## Prevention

### Best Practices

1. **Always Check Exclusions:**
   - Before cleaning URLs, check if page is excluded
   - Use consistent exclusion list across all scripts
   - Document exclusion logic in code comments

2. **Script Load Order:**
   - Be aware of script load order
   - IIFEs run immediately when script loads
   - Check for interference before UTM tracker initializes

3. **Testing:**
   - Test excluded pages after any script changes
   - Verify UTMs preserved on excluded pages
   - Check console for exclusion messages

4. **Documentation:**
   - Document script interference issues
   - Update troubleshooting guides
   - Note which pages include which scripts

### Code Pattern

When adding URL cleaning logic, use this pattern:

```javascript
(function() {
  // Check if page is excluded from URL cleaning
  const excludedPages = ['/v3', '/gastro', '/schichtbetriebe'];
  const currentPath = window.location.pathname;
  const isPageExcluded = excludedPages.some(path => 
    currentPath === path || currentPath.startsWith(path + '/')
  );
  
  // Skip URL cleaning on excluded pages
  if (isPageExcluded) {
    console.log('[Script Name] URL cleaning skipped - Excluded page:', currentPath);
    return;
  }
  
  // Only clean URL if page is not excluded
  if (window.location.search) {
    // URL cleaning logic here
  }
})();
```

## Related Issues

### Other Potential Interference

Check for other scripts that might interfere:

1. **Alpine.js Components:**
   - Search for `history.replaceState` in Alpine components
   - Check for URL parameter manipulation
   - Verify exclusion checks in Alpine init functions

2. **Page-Specific Scripts:**
   - Check inline scripts in PHP files
   - Look for `window.location` manipulation
   - Verify no automatic URL cleaning

3. **Third-Party Scripts:**
   - Check analytics scripts (shouldn't clean URLs)
   - Verify form scripts don't clean URLs
   - Check for conflicting URL manipulation

## Testing

### Test Scripts

Use test scripts to verify exclusion works:

1. **Test Pricing Page Exclusion:**
   ```
   /v2/scripts/dev-helpers/test-pricing-page-exclusion.php?utm_source=test&utm_campaign=test
   ```

2. **Test UTM Cleanup Exclusion:**
   ```
   /v2/scripts/dev-helpers/test-page-exclusions.php?utm_source=test&utm_campaign=test&utm_debug=true
   ```

### Manual Testing

1. Visit excluded page with UTMs:
   ```
   http://localhost:8003/gastro?utm_source=test&utm_campaign=test&utm_debug=true
   ```

2. Check console for messages:
   - `[Pricing Page] URL cleaning skipped - Excluded page: /gastro`
   - `[UTM Cleanup] Cleanup DISABLED via excluded page`

3. Verify UTMs remain in URL

4. Check analytics capture (GTM/GA4/HubSpot)

## Related Documentation

- `docs/development/UTM_CLEANUP_PAGE_EXCLUSIONS.md` - Page exclusion documentation
- `docs/development/UTM_CLEANUP_TROUBLESHOOTING.md` - Troubleshooting guide
- `v2/js/pricing-page.js` - Pricing page script with exclusion check
- `v2/js/utm-tracking.js` - UTM tracker with exclusion checks
