LoginSignup
3
3

More than 5 years have passed since last update.

Chrome extensionのcontent_scriptsから設定情報を読み込むことを試しました

Last updated at Posted at 2014-06-18

背景

もう一つのChrome extensionを作りました。これは何が出来るというと、Githubのウェブページでソースを閲覧するとき、空白(Space、Tab、Enter)などを特別の符号で表示してくれます。こういう感じです。

Screen Shot 2014-06-18 at 下午5.15.45.png

また、入替え符号もカスタマイズできるように、Options画面を追加しlocalStorageに保存することで実装しました。

// manifest.js
  "options_page": "options.html",

設定画面はこんな感じ

Screen Shot 2014-06-18 at 下午5.18.35.png

問題発生

でも、実際に動作すると、content_scriptsからその設定が読み込めないです。

〜〜〜〜調べたところ、content_scriptsはTabページのコンテキストの中に動いているので、Extentionとは別のコンテキストです。

GoogleのDoc( https://developer.chrome.com/extensions/messaging#simple )によりますと、メッセージでデータを受け渡すことができます。

実装も簡単、

1. background.jsを追加(常に動くページが必須)

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

メッセージの受信を用意

  chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
      if (request.action == "get_conf"){
        var conf = getConf();
        sendResponse(conf);
      }
    });

2. content_scriptからメッセージを送る

  chrome.runtime.sendMessage({action: "get_conf"}, function(response) {
   // response はbackground.jsからのデータが格納されています。
  });

全ソースはこち https://github.com/liubin0329/github-source-view-plugin

3
3
0

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
3
3