Chrome扩展:如何响应从"弹出"在内容脚本中

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

本文关键字:quot 弹出 脚本 扩展 何响应 响应 Chrome      更新时间:2023-09-26

我想创建一个扩展,将在社交网络中切换音乐播放的状态。我有一个按钮'播放/暂停'在一个弹出窗口。html,我已经注入到每个页面的脚本(注入.js,内容脚本)。当有人点击pop .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)
            });
    }
}

injection.js:

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

对不起我的英语:)

使用chrome.tabs.query ({active:true, currentWindow: true}, callback);获取当前标签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);
            }
        });
    });
};
要获得合理的响应,您必须调用第三个参数(sendResponse):
chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) {
        // Send a response back. For example, the document's title:
        sendResponse(document.title);
    } 
);

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