LoginSignup
148
140

More than 5 years have passed since last update.

Chrome拡張開発: 拡張からページにJavaScriptを送り込みたい

Last updated at Posted at 2014-08-11

ゴール

Google Chrome拡張から、閲覧中のページにJavaScriptを送り込んで、そのページのWindowオブジェクトにオブジェクトを追加する拡張を作る。なお、今回の成果物はGitHubで見ることができる。

1. 拡張を作る

ファイル構成は、マニフェスト、アイコン画像、2つのJavaScriptからなる。

├── content-script.js
├── embeded-script.js
├── icons
│   ├── icon128.png
│   ├── icon16.png
│   ├── icon19.png
│   └── icon48.png
└── manifest.json

content-script.js

ページを開いた時に実行するスクリプト。このスクリプトはChrome拡張の閉じた環境で実行されるので、ページの Windowオブジェクトにオブジェクトを追加することはできない。そのため、ページに <script> タグを描画することで、Window オブジェクトを変更するスクリプトを送り込む。

content-script.js
var injectScript;

injectScript = function(file, node) {
  var s, th;
  th = document.getElementsByTagName(node)[0];
  s = document.createElement('script');
  s.setAttribute('type', 'text/javascript');
  s.setAttribute('src', file);
  return th.appendChild(s);
};

injectScript(chrome.extension.getURL('/embeded-script.js'), 'body');

embeded-script.js

送り込まれるスクリプト。このスクリプトは Window オブジェクトを操作できる。

embeded-script.js
window.MyEmbededProgram = {
  helloWorld: function() {
    alert("Hello World!")
  }
};

注意点として、送り込まれたスクリプトは拡張から提供されたと言え、ただのJavaScriptになるので、直接拡張の機能やAPIをコールすることはできない。これを解決する方法は次回で紹介するので、ここでは割愛する。

manifest.json

ページにスクリプトを送り込みたいので、それができる設定を manifest.json に宣言する必要がある。まず、すべてのページで content-script.js が実行されるように matches<all_urls> にする。permissions についても <all_urls> を設定しておく。次に、ページ上で拡張のJSを読み込めるようにするために、 web_accessible_resourcesembeded-script.js を設定する。

manifest.json
{
  "name": "Example 1: Embed Scripts to All Web Pages",
  "version": "0.0.1",
  "manifest_version": 2,
  "description": "This is an example to embed scripts to all web pages",
  "icons": {
    "16": "icons/icon16.png",
    "48": "icons/icon48.png",
    "128": "icons/icon128.png"
  },
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "js": [
        "content-script.js"
      ]
    }
  ],
  "web_accessible_resources": [
    "embeded-script.js"
  ],
  "permissions": [
    "<all_urls>"
  ]
}

2. 実行してみる

適当なウェブサイトに行き、インスペクタを開いたら、そこで MyEmbededProgram.helloWorld() を実行してみる。すると、「Hello World!」とアラートが出てくるはずだ。

Example_Domain.png

Chrome拡張開発シリーズ

前回: Hello Worldするだけの拡張を作りたい
次回: ???

148
140
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
148
140