LoginSignup
23
14

More than 5 years have passed since last update.

【Chrome Extension】Browser Actionsでcontent scriptの任意の関数を呼び出す

Last updated at Posted at 2016-01-04

自作のChrome ExtensionのBrowser Actionsにて,アイコンクリック時に任意の関数の呼び出し方で躓いたのでメモ.

やりたいこと

Browser Actionsのアイコンをクリックしたときに,content_scriptsで指定したscript.jsの関数hogehoge()を呼びたい.
マニフェストは以下の通り.

manifest.json

{
  "manifest_version": 2,
  "name": "Test app",
  "description": "test",
  "version": "1.0",
  "icons": {
    "image": "image.png"
  },
  "content_scripts": [{
    "matches": ["<all_urls>"],
    "js": ["script.js"]
  }],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_icon": "image.png",
    "default_title": "test"
  },
  "permissions": [
    "tabs",
    "background",
    "http://*/*",
    "https://*/*"
  ]
}

backgraound.js

backgraound.jsの記述.
以下のようにClick Listenerを定義する.

backgraound.js

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.sendMessage(tab.id, "myAction");
});

ポイントは,addListener内で


chrome.tabs.sendMessage(tab.id, "myAction");

としてsendMessage関数を呼び出す.引数の文字列は何でもOK.

次にscript.jsの記述.

script.js

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    if (request == "myAction") {
        hogehoge();
    }
}); 

function hogehoge() {
    console.log("hogehoge");
}

chrome.extension.onMessage.addListenerを定義してやって,その中で目的の関数を呼び出せばアイコンクリックと同時に実行できる.
その際に,backgraound.js内のchrome.tabs.sendMessageの第二引数の文字列をトリガーとしている.

23
14
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
23
14