Skip to content

Instantly share code, notes, and snippets.

@eevmanu
Created March 23, 2025 21:51
Show Gist options
  • Save eevmanu/2bc540f7126f2eb11bfb0558e5ee752c to your computer and use it in GitHub Desktop.
Save eevmanu/2bc540f7126f2eb11bfb0558e5ee752c to your computer and use it in GitHub Desktop.
Amazon URL Redirect userscript explanation and userscript.js file to have a Amazon Product URL Cleaner

Okay, I understand the requirements. You want a Tampermonkey userscript that redirects Amazon product URLs to their most concise form, specifically https://www.amazon.es/dp/<product_id>, regardless of whether the original URL includes the product name or query parameters. Here's a robust solution, along with a detailed explanation:

// ==UserScript==
// @name         Amazon URL Cleaner (ES)
// @namespace    http://tampermonkey.net/
// @version      0.5
// @description  Redirects Amazon.es product URLs to the shortest /dp/ format.
// @author       You
// @match        https://www.amazon.es/*
// @grant        none
// @run-at       document-start
// ==/UserScript==

(function() {
    'use strict';

    const currentUrl = window.location.href;
    const dpRegex = /\/dp\/([A-Z0-9]+)/;  // Matches /dp/<product_id> and captures the product ID.

    const match = dpRegex.exec(currentUrl);

    if (match) {
        const productId = match[1]; // Extract the captured product ID.
        const newUrl = `https://www.amazon.es/dp/${productId}`;

        if (currentUrl !== newUrl) { //avoid infinite loop
            window.location.replace(newUrl); // Use replace to avoid back button issues.
        }
    }
})();

Explanation and Breakdown:

  1. Metadata Block (// ==UserScript== ... // ==/UserScript==):

    • @name: A descriptive name for your userscript.
    • @namespace: A unique identifier (often a URL) to prevent naming conflicts.
    • @version: The version number of your script. Increment this when you make changes.
    • @description: A brief explanation of what the script does.
    • @author: Your name or identifier.
    • @match: This is crucial. It tells Tampermonkey which URLs the script should run on. https://www.amazon.es/* means the script will run on any URL under the amazon.es domain. This is important because we want to catch all the variations of product URLs.
    • @grant none: This indicates that the script doesn't need any special Tampermonkey API permissions. This is good for security and performance.
    • @run-at document-start: This is also very important. It makes the script run before the page content starts loading. This is essential for redirection, as we want to redirect before the browser spends time loading the original, longer URL. This makes the redirection much faster and avoids flickering.
  2. use strict';: Enables strict mode, which helps catch common JavaScript errors and enforces cleaner coding practices.

  3. currentUrl: Stores the current URL of the page.

  4. dpRegex: This is the heart of the URL parsing. Let's break down the regular expression:

    • \/dp\/: Matches the literal string /dp/. The backslashes (\) escape the forward slashes, which have special meaning in regular expressions.
    • ([A-Z0-9]+): This is the capturing group.
      • (...): Parentheses create a capturing group. This means that the part of the URL that matches this part of the regex will be extracted and made available separately.
      • [A-Z0-9]: This character set matches any uppercase letter (A-Z) or any digit (0-9). This is based on the typical format of Amazon product IDs.
      • +: This quantifier means "one or more" of the preceding character set. So, it will match one or more uppercase letters or digits. This ensures that the entire product ID is captured.
  5. dpRegex.exec(currentUrl): This executes the regular expression against the current URL. The exec() method returns:

    • An array if a match is found. The first element of the array (match[0]) is the entire matched string (e.g., /Brennenstuhl-1168120015-Cable-Pl%C3%A1stico-Blanco/dp/B003DPNVPA), and subsequent elements are the captured groups (in our case, match[1] will be the product ID, B003DPNVPA).
    • null if no match is found.
  6. if (match): This checks if a match was found. If match is not null, it means the URL contains the /dp/<product_id> pattern.

  7. productId = match[1]: Extracts the captured product ID from the match array.

  8. newUrl: Constructs the new, clean URL using the extracted product ID.

  9. if (currentUrl !== newUrl): This is a crucial check to prevent infinite redirection loops. If the current URL is already in the desired format, there's no need to redirect. This handles cases where the user is already on the clean URL.

  10. window.location.replace(newUrl): This performs the redirection. Crucially, it uses replace() instead of window.location.href = newUrl.

    • replace(): Replaces the current page in the browser's history with the new URL. This means that if the user clicks the "Back" button, they won't be taken back to the original, longer URL; they'll go to the page before the Amazon page. This is generally the desired behavior for redirects.
    • window.location.href = newUrl: This would add a new entry to the browser's history. The "Back" button would take the user back to the original, longer URL, which would then immediately redirect again, creating a bad user experience.

How to Install and Use:

  1. Install Tampermonkey: If you don't already have it, install the Tampermonkey extension for your browser (Chrome, Firefox, Edge, Safari, etc.).
  2. Create a New Userscript:
    • Open the Tampermonkey dashboard (click the Tampermonkey icon in your browser's toolbar).
    • Click the "+" button to create a new script.
    • Replace the default script content with the code provided above.
  3. Save the Script: Click "File" -> "Save" (or Ctrl+S / Cmd+S).
  4. Test: Visit any Amazon.es product page with a long URL or query parameters. The script should automatically redirect you to the clean /dp/<product_id> URL.

Key Improvements and Considerations:

  • @run-at document-start: Ensures fast redirection before the page loads.
  • window.location.replace(): Prevents back-button issues.
  • Regular Expression (dpRegex): Accurately extracts the product ID, handling variations in the URL.
  • Infinite Loop Prevention: The if (currentUrl !== newUrl) check is essential to prevent the script from redirecting endlessly if the user is already on the clean URL.
  • Error Handling (Optional): While not strictly necessary for this specific use case, you could add error handling (e.g., using try...catch) to gracefully handle unexpected situations, although the regex is quite robust.
  • Specificity: The script is specifically designed for amazon.es. If you need to support other Amazon domains (e.g., .com, .co.uk, .de), you would need to add additional @match rules or modify the script to handle those domains. You could create separate scripts for each domain, or you could modify this script to be more general.
  • Robustness: The regular expression is designed to be robust and handle various URL formats, including those with or without product names and query parameters.

This improved script provides a clean, efficient, and user-friendly solution for redirecting Amazon.es product URLs. It addresses all the requirements and includes best practices for Tampermonkey userscripts. It is also well-commented and easy to understand.


Okay, to generalize the script to handle multiple Amazon domains, you have two main options:

Option 1: Multiple @match Rules (Simpler)

This is the easiest approach if you have a limited, known set of domains you want to support. You simply add more @match lines to your userscript's metadata.

// ==UserScript==
// @name         Amazon URL Cleaner (Multiple Domains)
// @namespace    http://tampermonkey.net/
// @version      0.6
// @description  Redirects Amazon product URLs to the shortest /dp/ format.
// @author       You
// @match        https://www.amazon.es/*
// @match        https://www.amazon.com/*
// @match        https://www.amazon.de/*
// @match        https://www.amazon.co.uk/*
// @match        https://www.amazon.fr/*  // Add more as needed
// @match        https://www.amazon.it/*
// @match        https://www.amazon.ca/*
// @match        https://www.amazon.co.jp/*
// @match        https://www.amazon.com.br/*
// @match        https://www.amazon.com.au/*
// @match        https://www.amazon.cn/*
// @grant        none
// @run-at       document-start
// ==/UserScript==

(function() {
    'use strict';

    const currentUrl = window.location.href;
    const dpRegex = /\/dp\/([A-Z0-9]+)/;

    const match = dpRegex.exec(currentUrl);

    if (match) {
        const productId = match[1];
        // Extract the domain from the current URL
        const domain = window.location.hostname; // e.g., "www.amazon.es"
        const newUrl = `https://${domain}/dp/${productId}`;

        if (currentUrl !== newUrl) {
            window.location.replace(newUrl);
        }
    }
})();

Explanation of Changes:

  • Multiple @match lines: The script now includes @match lines for each Amazon domain you want to support. Tampermonkey will run the script on any URL that matches any of these lines.
  • const domain = window.location.hostname;: This line extracts the domain name (e.g., "www.amazon.com", "www.amazon.co.uk") from the current URL. This is important because we need to construct the new URL using the correct domain.
  • const newUrl = https://${domain}/dp/${productId};: This line now uses the extracted domain to build the new URL. This ensures that the redirection stays within the same Amazon domain.

Option 2: Dynamic Domain Matching (More Flexible)

This approach is more flexible if you want to support any Amazon domain without having to list them all explicitly. It uses a regular expression in the @match rule and within the script to identify Amazon domains.

// ==UserScript==
// @name         Amazon URL Cleaner (Dynamic Domains)
// @namespace    http://tampermonkey.net/
// @version      0.7
// @description  Redirects Amazon product URLs to the shortest /dp/ format.
// @author       You
// @match        https://www.amazon.*/
// @grant        none
// @run-at       document-start
// ==/UserScript==

(function() {
    'use strict';

    const currentUrl = window.location.href;
    const dpRegex = /\/dp\/([A-Z0-9]+)/;
    const domainRegex = /^https?:\/\/(www\.amazon\.(?:com?\.(?:[a-z]{2,3})|[a-z]{2,3}))\//;

    const domainMatch = domainRegex.exec(currentUrl);

    if (!domainMatch) {
        return; // Not an Amazon URL, do nothing.
    }

    const domain = domainMatch[1];

    const dpMatch = dpRegex.exec(currentUrl);

    if (dpMatch) {
        const productId = dpMatch[1];
        const newUrl = `https://${domain}/dp/${productId}`;

        if (currentUrl !== newUrl) {
            window.location.replace(newUrl);
        }
    }
})();

Explanation of Changes:

  • @match https://www.amazon.*/: This @match rule is more general. It matches any URL that starts with https://www.amazon.. The * is a wildcard that matches any characters. This is almost what we want, but it's too broad (it would match www.amazon.something-else.com, which we don't want). That's why we need the domainRegex.
  • domainRegex: This regular expression is used to validate that we're on a legitimate Amazon domain. Let's break it down:
    • ^https?:\/\/: Matches the beginning of the URL, allowing for either http or https.
    • (www\.amazon\.): Matches the literal string "www.amazon.".
    • (?:com?\.(?:[a-z]{2,3})|[a-z]{2,3}): This is the most complex part. It's a non-capturing group ((?:...)) that matches the top-level domain (TLD) and any optional country code.
      • com?\.(?:[a-z]{2,3}): Matches "com" or "com." followed by a 2- or 3-letter country code (e.g., "com.au", "com.br").
      • |: This is the "or" operator.
      • [a-z]{2,3}: Matches a 2- or 3-letter TLD (e.g., "de", "fr", "co.uk").
    • \/: Matches the trailing slash.
  • domainMatch = domainRegex.exec(currentUrl): This executes the domainRegex against the current URL.
  • if (!domainMatch) { return; }: This is critical. If the domainRegex doesn't match, it means we're not on a valid Amazon URL (even though the @match rule might have triggered). In this case, we return; early, which means the rest of the script won't run. This prevents the script from interfering with non-Amazon pages.
  • const domain = domainMatch[1];: Extracts the captured domain.
  • The rest of the script is the same as in Option 1, using the extracted domain to construct the new URL.

Which Option to Choose:

  • Option 1 (Multiple @match Rules): Simpler to implement and understand. Best if you have a small, fixed set of Amazon domains to support.
  • Option 2 (Dynamic Domain Matching): More flexible and robust. Handles any Amazon domain without needing to be updated. Slightly more complex to understand due to the regular expression. This is the recommended approach for most cases, as it's more future-proof.

Important Considerations (Both Options):

  • Thorough Testing: Test thoroughly with different Amazon domains and URL structures to ensure the script works correctly.
  • Edge Cases: There might be rare edge cases with unusual URL formats that aren't handled perfectly. Regular expressions can be complex, and it's difficult to cover every possible variation. If you encounter such cases, you might need to refine the regular expressions.
  • Amazon Changes: Amazon could change its URL structure in the future, which might break the script. You might need to update the script periodically to keep it working.
  • Performance: Both options are generally very fast, especially with @run-at document-start. The dynamic matching (Option 2) might have a very slightly higher overhead due to the more complex regular expression, but the difference is likely negligible.

I strongly recommend using Option 2 (Dynamic Domain Matching) for its flexibility and robustness. It's the best long-term solution.

// ==UserScript==
// @name Amazon Product URL Cleaner
// @namespace http://tampermonkey.net/
// @version 0.0.1
// @description Redirects Amazon.** product URLs to the shortest /dp/ format.
// @author You
// @match https://www.amazon.com/*
// @match https://www.amazon.es/*
// @match https://www.amazon.de/*
// @match https://www.amazon.co.uk/*
// @grant none
// @run-at document-start
// ==/UserScript==
(function() {
'use strict';
const currentUrl = window.location.href;
const dpRegex = /\/dp\/([A-Z0-9]+)/; // Matches /dp/<product_id> and captures the product ID.
const match = dpRegex.exec(currentUrl);
if (match) {
const productId = match[1]; // Extract the captured product ID.
// Extract the domain from the current URL
const domain = window.location.hostname; // e.g., "www.amazon.es"
const newUrl = `https://${domain}/dp/${productId}`;
if (currentUrl !== newUrl) { //avoid infinite loop
window.location.replace(newUrl); // Use replace to avoid back button issues.
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment