Skip to content

Instantly share code, notes, and snippets.

@uupaa
Last active August 7, 2022 08:28
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save uupaa/9e702be2d085b330fbda to your computer and use it in GitHub Desktop.
Save uupaa/9e702be2d085b330fbda to your computer and use it in GitHub Desktop.
Chrome Extension send message

Chrome Extension の Messaging 機能でハマったのでメモ

content script から event page(background script) にメッセージを送る方法

content ▶ event page の方向で送る場合は、tab id が不要

// content script
function send() {
    chrome.runtime.sendMessage({ message: "hello" }, function(response) {
        console.log("content script got a response" + response.message);
    });
}
// event page
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    sendResponse({ message: "world" });
});

これで、メッセージが届く。メッセージは クローン可能なものならなんでも良く、文字列やJSONが渡せる

event page から content script にメッセージを送る方法

event page ▶ content の方向でメッセージを送る場合は、tab id が必要になる。

間違えて、event page からの送信で chrome.runtime.sendMessage を使うと Could not establish connection. Receiving end does not exist で叱られる

ここを参考に http://stackoverflow.com/questions/20917905/sending-message-to-content-script-on-onclick-event-of-background-page-of-chrome

// even page
function send(tabid) {

    chrome.tabs.sendMessage(tab.id, "hello", function(response) {
        if (chrome.runtime.lastError) {
            alert("chrome.runtime.lastError" + chrome.runtime.lastError.message);
        }
        console.log("event page got a response" + response); // console.log は出ないので…
        alert("event page got a response" + response); // alert で確認
    });
}

chrome.contextMenus.onClicked.addListener(function(info, tab) {
    send(tab.id);
});
// content script
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log("content script got a message" + request);
    sendResponse("world");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment