LoginSignup
17
15

More than 5 years have passed since last update.

ClojureScriptでChrome Extensionを作る

Posted at

まずはleiningenのプロジェクトを作る。

lein new chrome-ex-sample

続いて、chrome-ex-sample/project.cljを編集する。

project.cljはこんな感じ。

(defproject chrome-ex-sample "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :dependencies [[org.clojure/clojure "1.5.1"]
                 [org.clojure/clojurescript "0.0-2234"]]
  :plugins [[lein-cljsbuild "1.0.3"]
            [lein-resource "0.3.6"]
            [no-man-is-an-island/lein-eclipse "2.0.0"]]
  :resource {
             :resource-paths ["resources"],
             :target-path "target/chrome-ex-sample"
            }
  :cljsbuild {
    :builds [{
        ; The path to the top-level ClojureScript source directory:
        :source-paths ["src-cljs"]
        ; The standard ClojureScript compiler options:
        ; (See the ClojureScript compiler documentation for details.)
        :compiler {
          ; :optimizations :whitespace
          :output-to "target/chrome-ex-sample/js/main.js"
          :pretty-print true}}]})

上記の設定ではClojureScriptのファイルはchrome-ex-sample/src-cljsに配置することになる。

作成したClojureScriptのコンパイルは

lein cljsbuild once

で行う。

ClojureScript自体はClojureで書くのだけれども、拡張子はcljではなくcljsにする。cljでClojureScriptを書いた場合は、上記のコマンドでJavaScriptにコンパイルしてくれないので注意。

続いて、chrome-ex-sample/src-cljs/main.cljsを作成する。

(ns chrome_ex_sample)

(defn ^:export hello []
  (js/alert "Hello World!!!"))
(set! (.-onload js/window) hello)

さらに、resourcesディレクトリ以下に下記のようにファイルを配置する。

chrome-ex-sample
└─resources
  │  manifest.json
  │
  └─icons
          icon.png

manifest.jsonは以下のようにする。

{
  "manifest_version": 2,
  "name": "chrome-ex-sample",
  "version": "0.1",
  "description": "Hello World!",
  // icon
  "icons": {
    "16": "icons/icon.png",
    "48": "icons/icon.png",
    "128": "icons/icon.png"
  },
  "content_scripts": [{
    "matches": ["http://www.yahoo.co.jp/"],
    "js": ["js/main.js"]
  }]
}

matchesにはextensionが作用するサイトのURLを正規表現で指定するので、上記の設定ではYahooのトップページを開いたときに"Hello World!"が表示される。

一通りファイルを作成した後で、コマンドラインから

lein do resource, cljsbuild once

と入力すると、target/chrome-ex-sampleにChromeのExtensionに必要なファイルが一式作成される。その後、Chromeの拡張機能の画面から「パッケージ化されていない拡張機能を読み込む」(デベロッパーモードの場合のみ表示される)を押下し、target/chrome-ex-sampleを選択すると、作成したextensionがブラウザに組み込まれる。

パッケージングの仕方とかはまた調べよう。

参考にしたWEBページ
* https://github.com/clojure/clojurescript
* http://www.casleyconsulting.co.jp/blog-engineer/chrome/chrome%E6%8B%A1%E5%BC%B5%E6%A9%9F%E8%83%BD%E3%81%AE%E4%BD%9C%E6%88%90%E6%96%B9%E6%B3%95-2/
* https://github.com/m0smith/lein-resource

17
15
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
17
15