gpt4 book ai didi

javascript - Chrome 扩展 : How to respond to the action from "popup" in the content script?

转载 作者:行者123 更新时间:2023-11-30 18:07:21 25 4
gpt4 key购买 nike

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

popup.html:

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

弹出.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)
});
}
}

注入(inject).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);
}
);

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

关于javascript - Chrome 扩展 : How to respond to the action from "popup" in the content script?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15508650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com