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?

Firefox拡張機能でコンテンツスクリプトのログを出力する方法

Posted at

概要

ブラウザ拡張機能でコンテンツスクリプトからコンソールへログを出力するための方法を記載します。

そのままだとコンテンツスクリプトからログが出力されないため、
コンテンツスクリプトからバックグラウンドスクリプトへログを送信します。

使用する関数

browser.tabs.sendMessageとbrowser.runtime.onMessageを使います。

構文 使う場所
browser.tabs.sendMessage Background script
browser.runtime.onMessage Background script, Content script

サンプルコード

コンテンツスクリプト

以下のコンテンツスクリプトを作ります。
main.jsとして保存します。

main.js
// コンテンツスクリプト
function sendError() {
  browser.runtime.sendMessage("send content error");
}

sendError();

バックグラウンドスクリプト

以下のバックグラウンドスクリプトを作成します。
background.jsとして保存します。

background.js
// バックグラウンドスクリプト
browser.runtime.onMessage.addListener(getMessage);

function getMessage(message) {
    console.log(message);
}

このようにすることで、コンテンツスクリプトで生成された文字列が
バックグラウンドスクリプトへ送られ、バックグラウンドスクリプトが
出力することで開発ツールにも表示されます。

参考

tabs.sendMessage()

runtime.onMessage

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?