dortonway
dortonway

Reputation: 439

Chrome extension: How to respond to the action from "popup" in the content script?

I want to create an extension which will switch a state of a music playback in a social network. I have a button 'play/pause' in a popup.html and I've injected a script into each page (injected.js, content script). When someone clicks the 'play/pause' in the popup.html, a page of the social network has to call the headPlayPause() function, but it doesn't work. What should I do to fix it?

popup.html:

<script src = 'popup.js'></script>
<input type = 'button' value = "Play/Pause" id = 'stopper' />

popup.js:

window.onload = function() {
    document.getElementById('stopper').onclick = function() {
        // i don't know how correctly get tabId
        chrome.tabs.sendMessage(241, { greeting: "hello" },
            function(res) {
                // returns "sendMessage callback.. undefined"
                alert('callback of sendMessage: ' + res)
            });
    }
}

injection.js:

chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) {
        headPlayPause();
    } 
);

Sorry for my english :)

Upvotes: 2

Views: 650

Answers (1)

Rob W
Rob W

Reputation: 349252

Use chrome.tabs.query({active:true, currentWindow: true}, callback); to get the current tab ID:

document.getElementById('stopper').onclick = function() {
    chrome.tabs.query({
        active: true,
        currentWindow: true
    }, function(tabs) {
        var tabId = tabs[0].id; // A window has only one active tab..
        chrome.tabs.sendMessage(tabId, { greeting: "hello" },
            function(res) {
                alert('callback of sendMessage: ' + res);
            }
        });
    });
};

To get a sensible response, you have to invoke the third parameter (sendResponse):

chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) {
        // Send a response back. For example, the document's title:
        sendResponse(document.title);
    } 
);

You can read more about sending messages within an extension at the message passing tutorial.

Upvotes: 3

Related Questions