前言

因為有關注匯率的需求,但是又不想每天手動瀏覽臺銀官網,臺銀也沒提供通知匯率的手機 App。

求人不如求己,那就自己動手解決問題吧!分析後需求如下:

  1. 獲取臺銀匯率網頁資訊
  2. 傳送通知至手機上顯示

第一點,爬蟲,不論是 Python 還是 JS,很容易辦得到。

第二點,通知,還要再寫個手機 App 專門接受通知嗎?好像有點小題大作了。

況且,蘋果遠端推送通知的工作機制複雜繁瑣,如果有成本更低的解決方案更好。

於是我將目光放進已經安裝於手機上的社群軟體,找到了臉書的 Messenger。

如果能讓伺服器端定時抓匯率資訊下來,並透過臉書的即時通功能傳給我自己。

既不用多開發安裝 App,通知推送也不需我操勞,簡直雙贏。

經過評估,我最後決定使用 Chrome 擴充功能來實現。


實作過程

獲取臺銀匯率網頁資訊

因為是針對特定網頁執行,所以使用內容腳本(content_scripts)即可。

先是使用Date()函式取得當下時間,我希望以銀行下班後的匯率當作當日匯率。

所以當小時大於 16 時,使用querySelector獲取網頁指定位置的數值。

為防止同日重複通知,將日期當成參數放入網址,當rate_date變更時才觸發通知機制,簡單但實用。

當確認日期發生改變時,透過網址傳值將訊息傳給fb_url並開啟新分頁。

最後,更新網址中的日期,每十分鐘重新整理,周而復始。

window.addEventListener("load", function()
{
  let full_date = new Date()
  let hour = full_date.getHours()

  if(hour >= 16)
  {
    let fb_url = "https://m.facebook.com/messages/read/?tid=cid.c.100000749************************"
    let rate_USD = document.querySelector(".table > tbody > tr:nth-child(1) > td:nth-child(5)").textContent
    let rate_CNY = document.querySelector(".table > tbody > tr:nth-child(19) > td:nth-child(4)").textContent
    let rate_date = document.querySelector(".time").textContent.substr(0,10)
    let url_params = new URLSearchParams(window.location.search)

    if(url_params.get("rate_date") != rate_date)
    {
      let msg = rate_date + "\n美金匯率為:" + rate_USD + "\n人民幣匯率為:" + rate_CNY
      window.open(fb_url + "&msg=" + encodeURI(msg), "_blank")
      document.location.href = "https://rate.bot.com.tw/xrt?rate_date=" + rate_date
      return
    }
  }

  setTimeout(function() { document.location.href = document.location.href }, 600000)

})

傳送通知至手機上顯示

臉書即時通網頁也是使用內容腳本。

為了加快載入速度及降低自動化難度,手機版 https://m.facebook.com/ 是個不錯的選擇。

從網址中解析出要傳送的文字後,填入composerInput並按下傳送按鈕。

最後,window.location.href = "about:blank"``window.close()是用 JS 關閉分頁的特殊方法。

window.addEventListener("load", function()
{
  let url_params = new URLSearchParams(window.location.search)
  let msg = url_params.get("msg")

  document.querySelector("#composerInput").value = msg
  document.querySelector('button[name="send"]').disabled = false
  document.querySelector('button[name="send"]').click()
  window.location.href = "about:blank"
  window.close()
})