油猴货币转换器 [英] greasemonkey currency converter

查看:100
本文介绍了油猴货币转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个greasmonkey脚本,以使用API​​将特定页面中的货币转换为INR. 我能够获得USD-INR的当前货币汇率,也能够将货币符号替换为INR,但无法将货币值转换为当前汇率.我正在使用此脚本:

I m making a greasmonkey script to convert currency in a specific page to INR using API. I am able to get the current currency rate of USD-INR and also able to replace currencies symbols to INR but m not able to convert the currency value to current rate. I am using this script:

$(function(){
    GM_xmlhttpRequest({
        method: "GET",
        url: "http://www.google.com/ig/calculator?hl=en&q=1usd=?inr",
        onload: function(d){
            d=JSON.stringify(eval("(" + d.responseText + ")"));
            d=$.parseJSON(d);
            p=Math.round(d.rhs.replace(/[^\d\.]/g, ''));
            var replaced=$('body').html().replace(/\$(?:\s+)*(\d+\,\.)?/g, '₹$1');
            $('body').html(replaced);
        }
    });
});

上面的脚本将$ s的所有出现替换为Rs.在类似这样的页面中:

The above script replace all the occurrences of $s to Rs. in a page like:

$0.50, $1.00, $20.00, $200.00

₹0.50, ₹1.00, ₹20.00, ₹200.00

但是我想要的是也用汇率将货币转换为:

but what i want is to convert the currency also with exchange rate like:

₹29.5, ₹59, ₹1180, ₹11800

我不明白这一点.

请帮助.

**OR SOMEONE HAVE BETTER IDEA TO DO THIS CONVERSION. PLZ SUGGEST**

推荐答案

您只需要递归或遍历具有美元值的节点即可.切勿在.html()innerHTML上使用replace()或RegExp.这不仅会破坏目标页面,而且还会使您恶魔般地获得预期的结果.

You need to recurse or loop through just the nodes that have the dollar values. Never use replace() or RegExp on .html() or innerHTML. Not only will this trash the target page, but you will have a devil of a time getting the desired results.

使用DOM方法遍历页面.请注意,货币值有多种格式,因此转换它们会变得很复杂.

Recurse through the page using DOM methods. Note that currency values come in many formats, so converting them can get complex.

以下是整个页面的适度健壮代码(无iframe) 您可以在jsFiddle上看到它的实际运行情况 :

Here's moderately robust code for the whole page (sans iframes) You can see it in action at jsFiddle:

// ==UserScript==
// @name     _Global currency converter, dollars to rupees
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant    GM_xmlhttpRequest
// ==/UserScript==

GM_xmlhttpRequest ( {
    method:     "GET",
    url:        'http://rate-exchange.appspot.com/currency?from=USD&to=INR',
    //Google sends malformed response, not JSON.
    //url:      'http://www.google.com/ig/calculator?hl=en&q=1usd=?inr',

    onload:     function (rsp){
        var rspJSON     = JSON.parse (rsp.responseText);
        var convRate    = rspJSON.rate;
        console.log (rspJSON, convRate);

        changeDollarsToRupees (document.body, convRate);
    }
} );

function changeDollarsToRupees (node, convRate) {
    if (node.nodeType === Node.TEXT_NODE) {
        if (/\$/.test (node.nodeValue) ) {
            processTextNode (node, convRate);
        }
    }
    else if (node.nodeType === Node.ELEMENT_NODE) {
        for (var K = 0, numNodes = node.childNodes.length;  K < numNodes;  ++K) {
            changeDollarsToRupees (node.childNodes[K], convRate);
        }
    }
}

function processTextNode (node, convRate) {
    /*-- Results like:
        ["Three values: ", "$1.10", " ", "$2.20", " ", "$3.00.", ""]
    */
    var moneySplit  = node.nodeValue.split (/((?:\+|\-)?\$[0-9.,]+)/);
    if (moneySplit  &&  moneySplit.length > 2) {
        /*-- Money values will be odd array index, loop through
            and convert all.
        */
        for (var J = 1, L = moneySplit.length;  J < L;  J += 2) {
            var dolVal = parseFloat (moneySplit[J].replace (/\$|,|([.,]$)/g, "") );

            if (typeof dolVal === "number") {
                //var rupVal = "Rs" + Math.round (dolVal * convRate);
                var rupVal = "Rs" + (dolVal * convRate).toFixed (2);
            }
            else {
                var rupVal = moneySplit[J] + " *Err*";
            }
            moneySplit[J] = rupVal;
        }
        //-- Rebuild and replace the text node with the changed value (s).
        var newTxt      = moneySplit.join ("");
        node.nodeValue  = newTxt;
    }
}



如果仅用于几页,请使用jQuery或document.querySelectorAll()仅处理您感兴趣的元素.例如:



If this is just for a few pages, use jQuery or document.querySelectorAll() to process just the elements you are interested in. For example:

var targElements = document.querySelectorAll ("div.priceTable");

for (var J = targElements.length - 1;  J >= 0;  --J) {
    changeDollarsToRupees (targElements[J], convRate);
}

这篇关于油猴货币转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆