Döviz Kurunu Hesaplayan Chrome Eklentisi Geliştirme

Bu yazıda Chrome İnternet Tarayıcısı için geliştirdiğim Döviz kurunu Türk Lirasına çevirme eklentisini anlatacağım.

Ziyaret edilen web sitesinde seçilen dolar değerini güncel kur değeri ile TL’ ye çeviren eklenti aşağıdaki resimdeki gibi çalışmaktadır. Bu eklenti özellikle satın alacağımız ürünlerde fiyat değerlendirmesi yaparken oldukça faydalı olacaktır.

Aşağıdaki resimde projenin dosya yapısı yer almaktadır.

proje yapısı

Projenin manifest.json dosyası; Options.html ve popup.html dosyaları bu projede kullanılmadı. Daha sonraki projelerde kullanılmak üzere template olarak bırakıldı.

{
  "name": "Convert value",
  "version": "1.0.0",
  "manifest_version": 2,

  "description": "Convert values",

  "minimum_chrome_version": "35",

  "icons": {
    "16": "icons/icon16.png",
    "48": "icons/icon48.png",
    "128": "icons/icon128.png"
  },

  "options_page": "options.html",

  "background": {
    "scripts": ["./background/background.js"],
    "persistent": false
  },

  "browser_action": {
    "default_popup": "./popup.html"
  },

  "content_scripts": [
    {
      "matches": ["*://*/*"],
      "js": [
        "script.js"
      ],
      "css": [
        "style.css"
      ],
      "all_frames": true
    }
  ],

  "permissions": [
    "contextMenus",
    "notifications",
    "clipboardWrite",
    "tabs",
    "activeTab"
  ]
}

background.js dosyası aşağıdaki gibidir. API’ den elde edeceğimiz güncel kur bilgisini CORS’ a takılmamak için background.js’ de fetch apisi ile çektik.

chrome.runtime.onMessage.addListener(
    function(url, sender, onSuccess) {
        fetch(url)
            .then(response => response.json())
            .then(responseText => onSuccess(responseText))
        
        return true;  // Will respond asynchronously.
    }
);

style.css dosyasında, ziyaret edilen sayfada döviz tutarı seçildikten sonra çıkacak popup’ ın style bilgilerini tanımladık.

#popup_converter8255 {
    background-color: #FFF;
    width: 170px;
    height: 90px;
    color: #8f9cb5;
    font-size: 18px;
    display: inline-block;
    padding-top: 5px;
    padding-right: 5px;
    padding-bottom: 5px;
    padding-left: 5px;
    border: 3px solid;
    border-color: #9AD3DE;
    border-radius: 5px;
    display: none;
  }

script.js dosyasında popup’ ın çalışma lojiğini koda döktük.

function getSelectedText() {
  var text = "";
  if (typeof window.getSelection != "undefined") {
    text = window.getSelection().toString();
  } else if (
    typeof document.selection != "undefined" &&
    document.selection.type == "Text"
  ) {
    text = document.selection.createRange().text;
  }
  return text;
}

function doSomethingWithSelectedText(e) {
  var selectedText = getSelectedText();
  if (!selectedText.toString().trim().length) {
    removePopup();
    return;
  }

  if (selectedText && isNumeric(selectedText)) {
    const x = e.clientX;
    const y = e.clientY;
    const currencyVal = getCurrency();
    const calculatedCurrency = calculateCurrency(currencyVal, selectedText); 

    placePopup(x, y, calculatedCurrency);
  }
}

let currValueofFetchData;

function getCurrency() {
    const url = "http://hasanadiguzel.com.tr/api/kurgetir";// free currency rate api
    
    chrome.runtime.sendMessage( //goes to bg_page.js
        url,
        data => {
          currValueofFetchData = data.TCMB_AnlikKurBilgileri[0].BanknoteSelling;
        }
    );
    currValueofFetchData = parseFloat(currValueofFetchData);
    return currValueofFetchData;
}

function calculateCurrency(currencyVal, selectedText) {
    return currencyVal*selectedText;
}

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function placePopup(x_pos, y_pos, calculatedCurrency) {
  const d = document.getElementById("popup_converter8255");
  d.style.position = "fixed";
  d.style.left = x_pos + "px";
  d.style.top = y_pos + "px";
  d.innerText = calculatedCurrency.toFixed(2) + " TL";
  d.style.display = "block";

}

function removePopup() {
  const d = document.getElementById("popup_converter8255");
  d.style.display = "none";
}

function createPopupElement() {
  const popup8255 = document.createElement("div");
  if (popup8255.length < 0) {
    return;
  }
  popup8255.setAttribute("id", "popup_converter8255");
  document.body.appendChild(popup8255);
}

setTimeout(createPopupElement, 1000);

document.onmouseup = doSomethingWithSelectedText;

Sizde web sitelerini gezerken verimliliğinizi artıracak böyle eklentiler geliştirebilirsiniz.

Başarılar dilerim…