Chrome拡張でポップアップとコンテンツのスクリプト間でデータのやり取りをするサンプル


manifest.json

{
  "manifest_version": 2,
  "name": "Test",
  "version": "1.0.2",
  "description": "Test",
  "browser_action": {
    "default_icon": "icon_128.png",
    "default_popup": "uis/popup.html"
  },
  "background": {
    "scripts": [
      "scripts/background.js"
    ],
    "persistent": false
  },
  "permissions": [],
  "icons": {
    "128": "icon_128.png"
  },
  "content_scripts": [
    {
      "matches": [
        "file:///*"
      ],
      "js": [
        "scripts/contents.js"
      ]
    }
  ]
}

uis/popup.html

<html>
<head>
    <title>Test</title>
</head>
<body>
    <button id="send">send</button>
    <button id="log">log</button>
</body>
<script src="../scripts/popup.js"></script>
</html>

scripts/popup.js

// backgroundで受け取った値をコンソールに表示
function logBackgroundValue () {
    var test = chrome.extension.getBackgroundPage().test_value;
    console.log(test);
    return;
}

// 現在アクティブなタブにデータを送信
function sendToContents(){
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, 
            JSON.stringify({ contents: "test value from popup" }),
            function (response) {
            });
    });    
}

document.getElementById('log').addEventListener('click', logBackgroundValue);
document.getElementById('send').addEventListener('click', sendToContents);

scripts/background.js

var test_value;

// contents.jsで送信した値を受信
chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        test_value = request.value;
    }
);

scripts/contents.js

// 送信側 contents -> background
chrome.runtime.sendMessage(
    { value: { contents: "test value from contents" } }
);

// 受信側 other tab -> contents(popup/option -> contents)
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    console.log(message);
    return;
});

Chrome拡張を実行させるページそのもの

<html>
<head>
    <title>Test</title>
</head>
<body>
    <button id="contents_button">Test</button>
</body>
</html>