📜  创建一个加密货币价格跟踪 Chrome 扩展(1)

📅  最后修改于: 2023-12-03 14:50:14.766000             🧑  作者: Mango

创建一个加密货币价格跟踪 Chrome 扩展

简介

加密货币价格的波动性很大,所以有时我们需要快速和方便地了解当前市场的变化情况。因此,我们可以创建一个 Chrome 扩展来跟踪一个或多个加密货币的当前价格。

功能
  • 添加加密货币进行跟踪,包括显示加密货币的名称和价格在 Chrome 扩展栏上。
  • 使用 CoinGecko 公开 API 获取实时加密货币价格。
  • 支持自由选择货币价格的货币符号。
  • 支持设置刷新时间间隔。
开始
创建一个 Chrome 扩展
  1. 创建一个文件夹,并命名它为 crypto-ticker
  2. crypto-ticker 文件夹中创建一个 manifest.json 文件,并添加以下代码:
{
  "manifest_version": 2,
  "name": "Crypto Ticker",
  "version": "1.0.0",
  "description": "Track the real-time prices of popular cryptocurrencies",
  "icons": {
    "16": "icons/icon16.png",
    "32": "icons/icon32.png",
    "48": "icons/icon48.png",
    "128": "icons/icon128.png"
  },
  "browser_action": {
    "default_icon": {
      "16": "icons/icon16.png",
      "32": "icons/icon32.png",
      "48": "icons/icon48.png",
      "128": "icons/icon128.png"
    },
    "default_title": "Crypto Ticker",
    "default_popup": "popup.html"
  },
  "permissions": [
    "http://localhost/",
    "https://api.coingecko.com/"
  ]
}

这里的 manifest.json 告诉 Chrome 扩展的名称、版本、描述、图标和浏览器动作。权限部分包括允许从本地主机和 CoinGecko API 获取数据。

  1. crypto-ticker 文件夹中创建一个 popup.html 文件,并添加以下代码:
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="popup.css">
    <title>Crypto Ticker</title>
  </head>
  <body>
    <div class="container">
      <h1>Crypto Ticker</h1>
      <form>
        <input type="text" placeholder="Enter the coin name" id="coin">
        <select id="currency">
          <option value="USD">USD</option>
          <option value="EUR">EUR</option>
          <option value="GBP">GBP</option>
          <option value="JPY">JPY</option>
          <option value="CNY">CNY</option>
        </select>
        <button type="submit" id="add">Add</button>
      </form>
      <div id="coinList">
      </div>
    </div>
    <script src="popup.js"></script>
  </body>
</html>

这里的 popup.html 文件是扩展的主要 UI 部分。其中包含一个表单用于添加要跟踪的加密货币代币名称,以及用于显示所有加密货币的列表。

  1. crypto-ticker 文件夹中创建一个 popup.css 文件,并添加以下代码:
h1 {
  font-size: 28px;
  font-weight: bold;
}

.container {
  width: 300px;
  margin: 20px;
  padding: 10px;
  border: 2px solid #ccc;
  border-radius: 5px;
}

form {
  display: flex;
  flex-direction: row;
}

input[type=text] {
  width: 60%;
  padding: 12px 20px;
  margin: 8px 0;
  box-sizing: border-box;
  border: 2px solid #ccc;
  border-radius: 4px;
}

select {
  width: 20%;
  padding: 12px 20px;
  margin: 8px 0;
  box-sizing: border-box;
  border: 2px solid #ccc;
  border-radius: 4px;
}

button {
  width: 20%;
  background-color: #4CAF50;
  color: white;
  padding: 14px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.button {
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.button:hover {
  background-color: #57b846;
}

.coin {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  margin: 10px;
}

.coinName {
  font-size: 20px;
  font-weight: bold;
}

.coinPrice {
  font-size: 20px;
}

.remove {
  color: red;
  cursor: pointer;
}

这里的 popup.css 文件用于调整表单、列表和按钮的外观以及 UI 细节。

  1. crypto-ticker 文件夹中创建一个 popup.js 文件,并添加以下代码:
const coinList = document.getElementById('coinList');
const form = document.querySelector('form');
const input = document.getElementById('coin');
const select = document.getElementById('currency');
const interval = document.getElementById('interval');
let coins = [];

function fetchData() {
  fetch(`https://api.coingecko.com/api/v3/coins/markets?vs_currency=${select.value}&ids=${coins.map(coin => coin.id).join(',')}&order=market_cap_desc&per_page=100&page=1&sparkline=false`)
    .then(response => response.json())
    .then(data => {
      coins.forEach((coin, index) => {
        const updatedCoin = data.find(item => item.id === coin.id);
        if (updatedCoin) {
          coin.price = updatedCoin.current_price;
        }
        const coinElement = document.getElementById(`coin${index}`);
        if (coinElement) {
          coinElement.querySelector('.coinPrice').textContent = `${select.value} ${coin.price}`;
        }
      });
    });
}

function addCoin(event) {
  event.preventDefault();
  const coin = {
    id: '',
    name: '',
    price: 0
  };
  fetch(`https://api.coingecko.com/api/v3/coins/list?include_platform=false`)
    .then(response => response.json())
    .then(data => {
      const result = data.find(item => item.name === input.value);
      if (result) {
        coin.id = result.id;
        coin.name = result.name;
        fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${coin.id}&vs_currencies=${select.value}`)
          .then(response => response.json())
          .then(data => {
            coin.price = data[coin.id][select.value];
            coins.push(coin);
            populateList();
          });
      }
    });
}

function removeCoin(index) {
  coins.splice(index, 1);
  populateList();
}

function populateList() {
  coinList.innerHTML = '';
  coins.forEach((coin, index) => {
    const div = document.createElement('div');
    div.setAttribute('class', 'coin');
    div.setAttribute('id', `coin${index}`);
    const name = document.createElement('div');
    name.setAttribute('class', 'coinName');
    name.textContent = coin.name;
    const price = document.createElement('div');
    price.setAttribute('class', 'coinPrice');
    price.textContent = `${select.value} ${coin.price}`;
    const remove = document.createElement('div');
    remove.setAttribute('class', 'remove');
    remove.textContent = 'X';
    remove.addEventListener('click', () => removeCoin(index));
    div.appendChild(name);
    div.appendChild(price);
    div.appendChild(remove);
    coinList.appendChild(div);
  });
  fetchData();
}

form.addEventListener('submit', addCoin);

setInterval(() => {
  fetchData();
}, 60000);

这里的 popup.js 文件主要是 JavaScript 逻辑。它定义了用于添加、删除和显示跟踪的加密货币的函数。

结论

现在,在 Chrome 地址栏中输入 chrome://extensions/ 就可以加载扩展了。点击“Crypto Ticker”图标,输入要跟踪的加密货币名称并选择货币符号。点击“Add”按钮即可开始跟踪。现在,您可以在 Chrome 扩展栏中看到所有跟踪的加密货币的时时价格了!