gpt4 book ai didi

google-chrome-extension - 从弹出窗口发送消息到内容脚本 - Chrome 扩展

转载 作者:行者123 更新时间:2023-12-02 14:06:17 25 4
gpt4 key购买 nike

当我通过浏览器操作按钮打开 popup.html 时,我想更新 popup.html 中的 html。 popup.js 应向当前选项卡上运行的内容脚本发送一条消息,并应接收响应并更新 html。但是,内容脚本没有收到任何消息,因此没有发送正确的响应。

内容.js

var text = "hello";
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse) {
switch(message.type) {
case "getText":
sendResponse(text);
break;
}
}
);

Popup.js

chrome.tabs.getCurrent(function(tab){
chrome.tabs.sendMessage(tab.id, {type:"getText"}, function(response){
alert(response)
$("#text").text(response);
});
});

Manifest.json

{
"manifest_version": 2,
"name": "It's Just A Name",
"description": "This extension is able to",
"version": "1.0",
"permissions" : ["tabs"],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html",
"default_title": "Click here!"
},
"content_scripts": [
{
"matches": ["https://*/*"],
"js": ["jquery.min.js","content.js"]
}]
}

弹出.html

<!doctype html>
<html>
<head>
<title>Title</title>
<style>
body {
font-family: "Segoe UI", "Lucida Grande", Tahoma, sans-serif;
font-size: 100%;
}
#status {
white-space: pre;
text-overflow: ellipsis;
overflow: hidden;
max-width: 400px;
}
</style>
<script src="popup.js"></script>
</head>
<body>
<p id="text"></p>
</body>
</html>

最佳答案

chrome.tabs.getCurrent 用于:

Gets the tab that this script call is being made from

您的popup.js应该是:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {type:"getText"}, function(response){
alert(response)
$("#text").text(response);
});
});

关于google-chrome-extension - 从弹出窗口发送消息到内容脚本 - Chrome 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45179138/

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