LoginSignup
18
12

More than 5 years have passed since last update.

Chrome Extensionのevent pageでAPI通信をおこなう

Posted at

Chrome Extensionを作成する際に、API通信を行いたい時はしばしばあると思います。
API通信などのModel的な部分は、event page(backgroundページのpersistentがfalseのもの)を使うのがいいらしいので、試してみました。
あるページ(path)に紐づく情報をAPIで取得するアプリケーションを想定しています。

1. 【失敗例】sendMessageとonMessageを使う

公式ページでbackgroundページとcontentScript間の通信はMessage Passingを使うよと書いてあるのでその通りにやってみました。

contentScript.js
chrome.runtime.sendMessage({path: "/1111"}, function(response) {
  console.log("receive");
  var datas = response.datas;
  console.log(datas);
});
background.js
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    var path = request.path;
    $.ajax({
      type: "GET",
      url: "APIのurl",
      dataType: "json",
      data: {path: path},
      success: function(datas){
        console.log("send");
        sendResponse({datas: datas});
      }
    });
  }
);

すると、background.jsconsole.log("send")は実行されるのに、cotentScript.jsのconsole.log("receive")は実行されません。
どうやら、API通信してる間に、contentScript.jsとbackground.js間の接続が切れてるらしいです。

(成功例)postMessageとonConnectを使う

接続が切れるなら、接続時間の長いものを使えばいいじゃん!ということで、公式ページのlong-lived connectionsの章を参考に以下のように書き換えました。

contentScript.js
  var port = chrome.runtime.connect({name: "test"});
  port.postMessage({path: path});
  port.onMessage.addListener(function(response) {
    console.log("receive");
    var datas = response.datas;
    console.log(datas);
  });
background.js
chrome.runtime.onConnect.addListener(function(port){
  port.onMessage.addListener(function(request){
    var path = request.path;
    $.ajax({
      type: "GET",
      url: "APIのurl",
      dataType: "json",
      data: {path: path},
      success: function(datas){
        console.log("send");
        port.postMessage({datas: datas});
      }
    });
  });
});

無事、cotentScript.jsのconsole.log("receive")も実行されるようになりました

18
12
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
12