LoginSignup
1
5

More than 3 years have passed since last update.

Chrome拡張機能を作ってみよう①

Last updated at Posted at 2021-01-22

背景

Chromeの拡張機能を作ってみたが、どこかにアウトプットしないと絶対に忘れると思ったため
基本的に自分用メモなのでよくわからなかったらすみません。

作るもの

① Chrome拡張機能からWeb上のファイルをダウンロードする。
② ダウンロードしたファイルをC#で作ったexeに連携する。
③ exeでファイル内容を受け取りChrome拡張機能に返す。
④ exeから受け取ったURLと同じURLを開いた場合にメッセージを表示する。
補足)Chrome拡張機能をChromeウェブストアを介さずにインストールさせる

準備するもの

・テキストエディタ
・visual studio
・xampp(ファイルダウンロード用)

Chrome拡張機能からファイルのダウンロード

今回はc:\extensionSample\extensions
というフォルダを作って、この中に作っていきます。

extensionsの中はこんな感じです
[css]
  popup.css - popup.htmlのスタイル
[images]
  abnormal.png - Chrome拡張機能エラー時のアイコン
  success.png - Chrome拡張機能正常時のアイコン
  icon16.png
  icon48.png
  icon128png
[js]
  background.js - 動作するファイル
  jquery-3.4.1.js
  jquery.binarytransport.js
  popup.js - popup.htmlにて動作する
  message.js - メッセージを表示するファイル
manifest.json - 設定ファイル
popup.html - Chrome拡張機能をクリックした際に表示する画面

この構成で作っていきます。

まず、manifest.json_から

manifest.json
{
  "manifest_version": 2,
  "name": "message表示",
  "version": "1.0",
  "description" : "Chrome拡張機能のサンプル",
  "permissions": [
    "nativeMessaging"
  ],
  "icons": {
    "16": "images/icon16.png",
    "48": "images/icon48.png",
    "128": "images/icon128.png"
  },
  "browser_action" : {
    "default_icon" : "images/abnormal.png",
    "default_title" : "Chrome拡張機能のサンプル",
    "default_popup": "popup.html"
  },
  "background": {
    "scripts": [
      "js/jquery-3.4.1.js",
      "js/jquery.binarytransport.js",
      "js/background.js"
    ],
    "persistent": false
  },
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "js": [
        "js/jquery-3.4.1.js",
        "js/jquery.binarytransport.js",
        "js/message.js"
      ]
    }
  ]
}

permissionsにはコンピューターにインストールされたアプリケーションと拡張機能との間のメッセージ交換をするためnativeMessagingを指定します。

URLを監視するのでmatchesはall_urlsを指定します。

次にbackground.js

background.js
/*
  初期起動時の処理
*/
// インストール時かバージョンアップ時
chrome.runtime.onInstalled.addListener(function() {
  initialize();
});

// ブラウザ起動時
chrome.runtime.onStartup.addListener(function() {
  initialize();
});


function initialize() {
  var dlFileName = "http://localhost/sample.txt";
  $.ajax({
    url: dlFileName,
    type: "GET",
    dataType: 'binary',
    responseType:'arraybuffer',
    timeout: 500
  })
  // 成功時
  .done(errorHandle(function (response) {
    var data = response;
    // ArrayBufferで取得するので
    var textfiledata = String.fromCharCode(...new Uint8Array(data));
    console.log(textfiledata);
    // 成功した場合は拡張機能のアイコンを切り替える
    chrome.browserAction.setIcon({path:"images/success.png"});
    // localStorageにステータスを保存
    localStorage.setItem('Status', 'ok');
  }))
  // 失敗時
  .fail(errorHandle(function () {
    // localStorageにステータスを保存
    localStorage.setItem('Status', 'ng');
  }));
  return true;
}
/**
 * 例外をまとめて処理する
 */
function errorHandle(process) {
  return function(){
    try {
      return process.apply(this, arguments);
    } catch (e) {
      chrome.browserAction.setIcon({path:"images/abnormal.png"});
      console.error(e);
    }
  };
}

あとはpopup系です

popup.js
$(function() {
  /*** localStorageからステータスを取得。 ***/
  var Status = localStorage.getItem('Status');
  if(Status == 'ok'){
    $('#status').html('<b>正常</b>');
  }else{
    $('#status').html('<b>異常</b>');
  }
});
popup.html
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-Control" content="no-cache">

    <link href="../css/popup.css" rel="stylesheet">

    <script src="../js/jquery-3.4.1.js" ></script>
    <script src="../js/popup.js" ></script>
  </head>

  <body id="body">
  <div class="box">
    <div class="header">
      <h3 style="margin: 5px 0">動作状況</h3>
    </div>
    <div class="content">
      <p id="status"></p>
    </div>
  </div>

  </body>
</html>
popup.css
body {
  font-family: sans-serif;
  width: 300px;
  height: 180px;
  background-color: lightgray;
}
p {
  margin: 0px;
}
.box {
  border: solid 1px;
  width: 95%;
  height: 90%;
  padding: 5px;
}

message.jsはとりあえず空でファイルだけ作っておきます。

動かしてみよう

ここまで出来たら動かしてみよう

Chromeのアドレスバーに
chrome://extensionsを入力して拡張機能を表示する

右上の「デベロッパー モード」をONにして「パッケージ化されていない拡張機能を読み込む」から
c:\extensionSample\extensionsを選択する。

一覧に出てきたら、右上の「拡張機能」から確認してみます。

http://localhost/sample.txt
が存在すれば正常表示、無ければ異常表示になると思います。

sample.txtの内容は以下のようにしています。
{"1" : "http://localhost/ap1/","2" : "http://localhost/ap2/"}


今回はここまで
次回はローカルプログラムとの連携について書こうかと思います。

(確認してないけどerrorHandleはちゃんと動いているかな・・・)

1
5
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
1
5