2

我想创建一个扩展程序,它将在社交网络中切换音乐播放的状态。我在 popup.html 中有一个“播放/暂停”按钮,并且我在每个页面中都注入了一个脚本(injected.js,内容脚本)。当有人点击 popup.html 中的“播放/暂停”时,社交网络的页面必须调用 headPlayPause() 函数,但它不起作用。我应该怎么做才能修复它?

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)
            });
    }
}

注入.js:

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

对不起我的英语不好 :)

4

1 回答 1

3

用于获取当前选项卡 ID:chrome.tabs.query({active:true, currentWindow: true}, callback);

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);
            }
        });
    });
};

要获得合理的响应,您必须调用第三个参数 ( sendResponse):

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

您可以在消息传递教程中阅读有关在扩展程序中发送消息的更多信息。

于 2013-03-19T20:30:43.187 回答