gpt4 book ai didi

javascript - chrome 扩展中的消息传递不起作用

转载 作者:行者123 更新时间:2023-11-28 02:18:24 25 4
gpt4 key购买 nike

我是 Chrome 扩展新手,在入门时遇到了一些困难。

首先,我的总体目标是能够单击弹出窗口中的按钮并在 DOM 中进行某些更改。如果我理解正确,执行此操作的方法是加载内容脚本并向该内容脚本发送消息。这是我从 Chrome 开发者页面中看到的内容,但我在控制台日志中没有看到任何内容:

list .json

{
"manifest_version": 2,

"name": "Test",
"version": "1.0",

"permissions": [
"tabs", "http://*/*"
],

"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["content.js"]
}
],

"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
}
}

popup.html

<html>
<body>
<script src="popup.js"></script>
</body>
</html>

popup.js

document.addEventListener('DOMContentLoaded', function () {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
});

内容.js

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});

很多代码直接来自文档,所以我不知道我做错了什么。

最佳答案

我刚刚将您的代码复制到我的机器上并按原样运行,它按您的预期工作。不过,我认为您可能对您期望的 console.log 输出将出现在哪里感到困惑。

打开任意网页并打开该页面的控制台。单击您的浏览器操作,将显示弹出窗口,并且果然出现了 from a content script:chrome-extension://fndmlopghajebfadeabnfnfmhalelokm/popup.html 行。

不过,您看不到 goodbye 行出现在那里 - 因为它是从 popup.js 注销的,而不是从选项卡的内容脚本注销的。让我们打开弹出窗口的检查器并在其中查找 goodbye 消息。右键单击浏览器操作图标并选择“检查弹出窗口”菜单项。您的(空)弹出窗口显示,并且出现一个新的检查器窗口;选择“控制台”选项卡,您将在其中看到再见消息。

有关其他信息,请参阅 Chrome Extension Debugging tutorial .

PS. chrome.tabs.getSelected 已弃用; you should use chrome.tabs.query反而。我同意方觉 - 你应该考虑使用编程注入(inject)来更改 DOM。

关于javascript - chrome 扩展中的消息传递不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16066317/

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