Last active
April 23, 2025 02:01
-
-
Save 3110/78ee3c08cc929f07e1e10e99f919cdc4 to your computer and use it in GitHub Desktop.
Amazon.co.jpのURLを短くするTampermonkey用UserScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ==UserScript== | |
| // @name Amazon URL Shortener | |
| // @namespace http://tampermonkey.net/ | |
| // @version 0.4 | |
| // @description Shorten Amazon URLs to minimal form | |
| // @match https://www.amazon.co.jp/* | |
| // @grant none | |
| // ==/UserScript== | |
| (() => { | |
| const shorten = () => { | |
| const url = location.href; | |
| // 複数のパターンでASINを抽出 | |
| let asin = null; | |
| // dp/ASIN パターン | |
| const dpMatch = url.match(/\/dp\/([A-Z0-9]{10})(?:\/|\?|$)/); | |
| if (dpMatch) asin = dpMatch[1]; | |
| // /ASIN/ パターン | |
| if (!asin) { | |
| const asinMatch = url.match(/\/([A-Z0-9]{10})(?:\/|\?|$)/); | |
| if (asinMatch) asin = asinMatch[1]; | |
| } | |
| // exec/obidos/ASIN/ パターン | |
| if (!asin) { | |
| const obidosMatch = url.match(/\/exec\/obidos\/ASIN\/([A-Z0-9]{10})/); | |
| if (obidosMatch) asin = obidosMatch[1]; | |
| } | |
| // gp/product/ASIN パターン | |
| if (!asin) { | |
| const gpMatch = url.match(/\/gp\/product\/([A-Z0-9]{10})/); | |
| if (gpMatch) asin = gpMatch[1]; | |
| } | |
| // URLからASINを直接抽出できない場合、ページ内の要素から探す | |
| if (!asin) { | |
| // data-asin属性を持つ要素を探す | |
| const asinElements = document.querySelectorAll('[data-asin]'); | |
| if (asinElements.length > 0) { | |
| const dataAsin = asinElements[0].getAttribute('data-asin'); | |
| if (dataAsin && dataAsin.length === 10) asin = dataAsin; | |
| } | |
| // amzn1.sym.xxxx などのコンテンツIDからは抽出しない(これはASINではない) | |
| } | |
| if (!asin) { | |
| console.log('Amazon URL Shortener: ASIN not found'); | |
| return; | |
| } | |
| const isbn10 = [...document.querySelectorAll('#detailBullets_feature_div li, #productDetails_detailBullets_sections1 tr, #detailsBaseTable tr, #productDetails_detailBullets_sections1 tr')] | |
| .find(el => el.textContent.includes('ISBN-10')) | |
| ?.textContent.match(/\d{10}/)?.[0]; | |
| const shortUrl = `/dp/${isbn10 || asin}`; | |
| if (!url.endsWith(shortUrl)) { | |
| history.replaceState(null, '', shortUrl); | |
| console.log('Amazon URL Shortener: URL shortened to', shortUrl); | |
| } | |
| }; | |
| // ページ読み込み後に実行 | |
| setTimeout(shorten, 2000); | |
| // ページ内容変更時にも実行 | |
| let lastUrl = location.href; | |
| new MutationObserver(() => { | |
| const url = location.href; | |
| if (url !== lastUrl) { | |
| lastUrl = url; | |
| setTimeout(shorten, 2000); | |
| } | |
| }).observe(document, {subtree: true, childList: true}); | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment