Yado_tech

旅館+ITとはなんぞ

web extensions書き直した。

どうにも昨日作ったweb extensionがきもちわるいかったので書き直した。

popup.jsでどうこうするやつはスコープの生き死にがわかりづらかった。

てことで現在はpopup.jsではなくbackground scriptsで管理するようにした。

f:id:devilmakelie:20180430235606p:plain

async/awaitとfetchAPIを使って書き直した。

非同期はわかりづらいけど最終的には各スクリプトにイベントリスナを追加する形で受ければ上手くいった。
イベントリスナで受けるのは思い付きだったけどうまくいった。よかった。

popup.js

//background scriptにリクエストを送る。
browser.runtime.sendMessage({text:''},function(response){
  document.getElementById('title').innerText = `you have selected ${response.artist}`
})

//background script からリクエストが来たらその通りにレンダリングする。
browser.runtime.onMessage.addListener(function(request,sender,sendResponse){
  console.log(request)
  render(request)
  sendResponse({text:'message received'})
})

function render(request){
  const similar_artist = request.state.similar_artist
  console.log(similar_artist)
  document.getElementById('title').innerText = `you have selected ${request.artist}`
  let html = ''
  for (key in similar_artist){
    html += `<br /><div><img src = ${similar_artist[key].image[1]['#text']}>${similar_artist[key].name}</div>`
  }
  document.getElementById('artist').innerHTML=html
}

background.js

//初期値の設定、選んだアーティストと似ているアーティスト

console.log('background start!')

//まずはAPIを叩くFunctionを作る。asyncなやつ
async function getSimilarArtist(artist) {
  var state = {
    artist_name: artist,
    status: "none",
    similar_artist: "",
  }
  const api_key = '6365215872671c325787a220ef38ae1c'
  var url = `http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&artist=${artist}&api_key=${api_key}&limit=10&format=json`
  fetch(url).then(async(response) =>  {
    var results = await response.json()
    state.status = "fetched"
    state.similar_artist = results.similarartists.artist
    //console.log(state)
    //最後にmessageをpopupに送る
    browser.runtime.sendMessage({
      artist: artist,
      state: state
    })
  })
}

browser.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  //現在のタブを取得する
  browser.tabs.query({
    currentWindow: true,
    active: true
  }, function(tab) {
    browser.tabs.sendMessage(tab[0].id, {
      text: ''
    }).then(function(response) {
      getSimilarArtist(response.str)
    })

  })
})

content-script.js

//単純にメッセージが来たらそこにレスポンスを返すだけ
browser.runtime.onMessage.addListener(function(msg,sender,sendResponse){
    title = document.title
    str = document.getSelection().toString()
    console.log(str)
    sendResponse({title:title,str:str})
})