|
1 | 1 | (function() { |
2 | | - console.log('content script loaded'); |
3 | | - |
4 | | - const usdRegex = /\$( ?[0-9]+)/g; |
5 | | - const usdToRupeeRatio = 69.58; |
6 | | - |
7 | | - document.body.innerHTML = document.body.innerHTML.replace(usdRegex, (_, val) => { |
8 | | - const numval = Number(val); |
9 | | - return Number.isNaN(numval) ? `$ ${val}` : `₹ ${usdToRupeeRatio * numval}`; |
| 2 | + function replace($node, regex, replaceMethod) { |
| 3 | + const queue = [$node]; |
| 4 | + while (queue.length) { |
| 5 | + let top = queue.shift(); |
| 6 | + if (top.childNodes.length) { |
| 7 | + queue.push(...top.childNodes); |
| 8 | + continue; |
| 9 | + } |
| 10 | + |
| 11 | + // If a text node is only child then replace currency using innerHTML |
| 12 | + if (top.nodeType === Node.TEXT_NODE && top.parentElement.childNodes.length === 1) { |
| 13 | + top = top.parentElement; |
| 14 | + } |
| 15 | + |
| 16 | + if (top.nodeType === Node.ELEMENT_NODE && regex.test(top.innerHTML)) { |
| 17 | + top.innerHTML = top.innerHTML.replace(regex, replaceMethod.bind(top)); |
| 18 | + } |
| 19 | + else if (top.nodeType === Node.TEXT_NODE && regex.test(top.nodeValue)) { |
| 20 | + top.nodeValue = top.nodeValue.replace(regex, replaceMethod.bind(top)); |
| 21 | + } |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + const toRupeeRatio = { |
| 26 | + '$': 69.58, |
| 27 | + '€': 77.82, |
| 28 | + }; |
| 29 | + const currencySymbols = ['\\$', '€']; |
| 30 | + const currencyRegex = new RegExp(`(${currencySymbols.join('|')})\\s?(\\d+(?:,\\d{2,3})*(?:\\.\\d+)?)`, 'g'); |
| 31 | + |
| 32 | + const INR = new Intl.NumberFormat('en-IN', {style: 'currency', currency: 'INR'}); |
| 33 | + |
| 34 | + const spanStyle = 'background: rgba(220, 220, 220, 0.7); color: #333; padding: 2px 5px; border-radius: 3px'; |
| 35 | + const format = price => `<span style="${spanStyle}">${INR.format(price)}</span>`; |
| 36 | + |
| 37 | + replace(document.body, currencyRegex, function (_, currency, val) { |
| 38 | + const numval = Number(val.replace(/,/g, '')); |
| 39 | + if (Number.isNaN(numval)) return `${currency} ${val}`; |
| 40 | + |
| 41 | + return this.nodeType === Node.ELEMENT_NODE ? |
| 42 | + format(toRupeeRatio[currency] * numval) : |
| 43 | + INR.format(toRupeeRatio[currency] * numval); |
10 | 44 | }); |
11 | 45 | })(); |
0 commit comments