0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

chrome拡張機能の開発について少し理解できた

Posted at

最近chrome拡張機能について調べていてサンプロを見たりしているが、いまいちcontent_scriptやbackground.js、chrome.*APIの挙動がよくわからなかったが、なんとなくつかめた気がするので備忘録としてメモ

content_script

特徴

  • DOMにはアクセスできる
  • 開いているページのディベロッパーツールでデバッグができる
  • chrome.*APIには色々制限があり、使えないものがある

Background-Page

特徴

  • chrome.*APIが全て使える
  • 常にバックグラウンドで動くのでメモリを常に消費してしまう。そのためEvent-Pageを使うことが推奨される。manifest.jsondで"persistent": falseを書くことでEvent-Pageになる。

content_scriptとBackground-Pageの連携

この2つのファイルの連携をchrome.*APIが行う

例としては以下

メッセージを送信する

content_ascript
//変数sendをメッセージで送る
chrome.runtime.sendMessage(send, function(response) {
   console.log(response);//メッセージの受け手がレスを返したときキャッチできる
});

参考:Chromeブラウザの拡張機能を作ってみたい初心者向けに開発方法を紹介!【サンプルあり】

メッセージを受け取る

background-page
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
  console.log(msg);//送られたメッセージをキャッチ
  sendResponse(response);//sendResponseでmsgを送ったスクリプト側にレスを返せる
});

参考:Chromeブラウザの拡張機能を作ってみたい初心者向けに開発方法を紹介!【サンプルあり】

何をしているか

またこのコードではcontent_script→background-pageへメッセージを送信している。
そして、変数sendの内容がbackgroundのコールバック関数の引数msgに渡される
そして関数sendResponseの引数へ渡したものがメッセージの送信元へ送られることで双方の連携ができている。

chrome.runtimeではコンテンツスクリプトへ送信できない

またこのコードではcontent_script→background-pageへメッセージを送信するのに
**chrome.runtime.sendMessage()を使用しているが、逆をやりたい場合、
つまりbackground-page→content_scriptへメッセージを送信したい場合は
chrome.tabs.sendMessage()**を使用する。

参考:https://developer.chrome.com/extensions/tabs

**chrome.tabs.sendMessage()**を使用する際にはどのcontent-scriptに送信するかを決めるためにtabIdなるものが必要になる。
参考:https://developer.chrome.com/apps/runtime

デバッグ関連

種類 説明
content-script 通常のデベロッパーツール
background-page 拡張機能の管理画面から
popup ポップアップを出して右クリック→検証

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?