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拡張機能でContent ScriptでMessage Passingする方法

Posted at

Content Scriptは特定のURLを開いたときに開いたページを操作するのに使用しますが、
[こちら](https://qiita.com/plumfield56/items/92a3656d6b24aa5e9f7e)
でも書いたように使用できるAPIが限定されるので、
runtime, storage以外のAPIを使用する場合はMessage Passingをする必要があります。

この記事では下記画像のように開いたページのリンクの数を
タブに表示するコードを載せています。

2020-05-19_13h22_40.png
フォルダ構造
フォルダ
 ├ manifest.json
 └ content.js // Content Scriptを動かすJavaScript
 └ event.js // Content Scriptを動かすJavaScript
manifest.json
{
  "manifest_version": 2,
  "name": "Link Count",
  "version": "1.0",

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ],

  "background": {
    "scripts": ["event.js"],
    "persistent": false
  },

  "browser_action": {
    "defalt_icon": {
      "16": "icon.png"
      }
  }
}
content.js
(function(){
  'use strict'; 
    const links = document.getElementsByTagName('a');
    // sendMessageでcountをキーにしたテキストを送付
    chrome.runtime.sendMessage({count: links.length}, () => {
        console.log('massage sent');
      });
})();
event.js
'use strict';
{
  // onMessageで受け取る
  chrome.runtime.onMessage.addListener(function(message, sender, callback) {
    chrome.browserAction.setBadgeText({text: message.count + ''});
  });
}

この記事はChrome拡張機能の作り方の一部のコンテンツです。

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?