Skip to content

Instantly share code, notes, and snippets.

@hidao80
Last active September 5, 2023 09:45
Show Gist options
  • Save hidao80/658177e67bc5c6bf48b9c694ffe205da to your computer and use it in GitHub Desktop.
Save hidao80/658177e67bc5c6bf48b9c694ffe205da to your computer and use it in GitHub Desktop.
Amazon URL Shortener
/**
* @fileoverview
* This script copies the short URL of the Amazon product page to the clipboard.
* A short URL is a URL that contains only the product ID.
*
* Copyright (c) 2023 hidao80
* Released under the MIT license
* https://opensource.org/licenses/mit-license.php
*/
(async v => {
// When copying to the clipboard, the document must have focus.
document.body.click();
const inputUrl = location.href;
const fields = inputUrl.split("/");
let shortUrl = "";
if (inputUrl.includes('r.html?')) {
// for gift voucher url
shortUrl = decodeURIComponent(inputUrl).split('&').filter(field => field.match(/U=/) !== null)[0]
.slice('U='.length, shortUrl.indexOf('?'));
} else {
const productId = fields.slice(-1).pop();
const withoutPrams = productId.replace(/\?.+$/, '');
if(withoutPrams != productId) {
// If there is a query parameter, it is not a product ID.
fields.push(withoutPrams);
}
shortUrl = fields.filter(field => field.match(/([%=-]|^$)/) === null).join('/')
// Delete query parameters
.replace(/(\/[\d-]+|(hz|ls)\/|www\.|\.co)/g, "")
.replace(/(\/gp\/product\/|\/dp\/)/, "/d/")
// Add the beginning of the url
.replace(/:\//, '://');
}
// Copy to clipboard
await navigator.clipboard.writeText(shortUrl);
alert(shortUrl);
})()
javascript:(()%3D%3E%7B(async%20e%3D%3E%7Bdocument.body.click()%3Bconst%20l%3Dlocation.href%2Cc%3Dl.split(%22%2F%22)%3Blet%20t%3D%22%22%3Bif(l.includes(%22r.html%3F%22))t%3DdecodeURIComponent(l).split(%22%26%22).filter((e%3D%3Enull!%3D%3De.match(%2FU%3D%2F)))%5B0%5D.slice(%22U%3D%22.length%2Ct.indexOf(%22%3F%22))%3Belse%7Bconst%20e%3Dc.slice(-1).pop()%2Cl%3De.replace(%2F%5C%3F.%2B%24%2F%2C%22%22)%3Bl!%3De%26%26c.push(l)%2Ct%3Dc.filter((e%3D%3Enull%3D%3D%3De.match(%2F(%5B%25%3D-%5D%7C%5E%24)%2F))).join(%22%2F%22).replace(%2F(%5C%2F%5B%5Cd-%5D%2B%7C(hz%7Cls)%5C%2F%7Cwww%5C.%7C%5C.co)%2Fg%2C%22%22).replace(%2F(%5C%2Fgp%5C%2Fproduct%5C%2F%7C%5C%2Fdp%5C%2F)%2F%2C%22%2Fd%2F%22).replace(%2F%3A%5C%2F%2F%2C%22%3A%2F%2F%22)%7Dawait%20navigator.clipboard.writeText(t)%2Calert(t)%7D)()%3B%7D)()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment