foldrr's weblog

旧ブログ http://d.hatena.ne.jp/foldrr/

Amazon で2個以上注文したらアラートを出す

環境

問題

Amazon で同じ商品を2つ以上注文してしまう間違いを避けたい。

解決

Firefox へ以下のスクリプトを登録しておく。

// ==UserScript==
// @name           Amazon Order Checker
// @namespace      http://example.com/amazon_order_checker
// @include        http*://amazon.co.jp/*
// ==/UserScript==

(function (){
    var message = "2つ以上注文している商品があります。\n" +
        "二重注文していないか数量を確認してください。";
    var pages = [
        {
            // カートに入れた直後の画面
            href: "http://www.amazon.co.jp/gp/product/handle-buy-box/",
            xpath: "//span[@class='tiny']",
            getter: function (node){
                return node.firstChild.nodeValue;
            },
            pattern: "数量[::  ]*(\\d+)",
        },
        {
            // カートを見る
            href: "http://www.amazon.co.jp/gp/cart/view.html/",
            xpath: "//form[@id='cartViewForm']//input[@type='text']",
            getter: function (node){
                return node.value;
            },
            pattern: "(\\d+)",
        },
        {
            // 注文確定直前
            href: "https://www.amazon.co.jp/gp/checkout/pay/select.html/",
            xpath: "//span[@class='tiny']",
            getter: function (node){
                return node.firstChild.nodeValue;
            },
            pattern: "数量[::  ]*(\\d+)",
        },
    ];
    
    
    amazon_order_checker(document);

    
    function amazon_order_checker(context){
        var href = context.location.href;
        for(var i = 0, n = pages.length; i < n; i++){
            if(! order_checker(href, pages[i])){
                return;
            }
        }
    }
    
    
    function order_checker(href, page){
        if(href.indexOf(page.href) == 0){
            var re = new RegExp(page.pattern);
            
            var texts = $X(page.xpath);
            for(var i = 0, n = texts.length; i < n; i++){
                var text = page.getter(texts[i]);
                var counter = (re.exec(text) || [])[1];
                if(counter){
                    if(2 <= counter){
                        alert(message);
                        return false;
                    }
                }
            }
        }
        
        return true;
    }
    
    
    function $X(query, doc){
        if(! doc){
            doc = document;
        }
        var r = new Array();
        var ns = doc.evaluate(query, doc, null,
            XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
        for(var i = 0, n = ns.snapshotLength; i < n; i++){
            r.push(ns.snapshotItem(i));
        }
        return r;
    }
})();

2009/08/28 追記

作り終わった後で、既に同じ機能のスクリプトがあることを知ったorz
しかも、たった2行。

ま、まぁ自分の作ったやつはカート画面(数量変更画面)でもアラート出す版ってことでいいよね?と、言い訳。

2011/02/26 追記

Userscripts.org に投稿しました。
http://userscripts.org/scripts/show/96644