gpt4 book ai didi

javascript - chrome.runtime.sendMessage 在 Chrome 扩展程序中不起作用

转载 作者:数据小太阳 更新时间:2023-10-29 04:20:25 29 4
gpt4 key购买 nike

我正在尝试创建一个新的扩展。不久前我能够使用 chrome.runtime.sendMessage 函数,但现在,我已经尝试了所有方法,但它仍然无法将消息发送到后台脚本。控制台正在填充来自 content-script.js 但不是来自 background.js

的日志消息

content-script.js

console.log("Hello World!s");
$(document).ready(function() {
console.log("DOM READY!");
$(document.documentElement).keydown(function (e) {
console.log("Key Has Been Pressed!");
chrome.runtime.sendMessage({Message: "getTextFile"}, function (response) {
if (response.fileData) {
alert("Contents Of Text File = ");
}
else {
console.log("No Response Received");
}
})

})
});

background.js

console.log("Atleast reached background.js")
chrome.runtime.onMessage.addListener (
function (request, sender, sendResponse) {
console.log("Reached Background.js");
if (request.Message == "getTextFile") {
console.log("Entered IF Block");
$.get("http://localhost:8000/quicklyusercannedspeechbucket/helloWorld1", function(response) {
console.log(response);
sendResponse({fileData: response})
})
}
else {
console.log("Did not receive the response!!!")
}
}
);

list .json

{
"manifest_version": 2,
"name": "My Cool Extension",
"version": "0.1",
"content_scripts": [ {
"all_frames": true,
"js": [ "jquery-2.1.4.min.js", "content-script.js" ],
"matches": [ "http://*/*", "https://*/*", "file://*/*" ]
} ],
"permissions": [ "http://*/*", "https://*/*", "storage" ],
"background": {
"scripts": [
"jquery-2.1.4.min.js",
"background.js"
]
}
}

感谢任何帮助:)

谢谢!

最佳答案

您需要更改您的代码,以便在 background.js 中您必须更改行为:

console.log("Atleast reached background.js")
chrome.runtime.onMessage.addListener (
function (request, sender, sendResponse) {
console.log("Reached Background.js");
if (request.Message == "getTextFile") {
console.log("Entered IF Block");
$.get("http://localhost:63342/Projects/StackOverflow/ChromeEXT/helloWorld1", function(response) {
console.log(response);

// to send back your response to the current tab
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {fileData: response}, function(response) {
;
});
});


})
}
else {
console.log("Did not receive the response!!!")
}
}
);

对于 contentscript 你需要做的:

console.log("Hello World!s");
$(document).ready(function() {
console.log("DOM READY!");
$(document.documentElement).keydown(function (e) {
console.log("Key Has Been Pressed!");
chrome.runtime.sendMessage({Message: "getTextFile"}, function (response) {
;
})

})
});


// accept messages from background
chrome.runtime.onMessage.addListener (function (request, sender, sendResponse) {
alert("Contents Of Text File = " + request.fileData);
});

sendResponse 可以用作即时反馈,而不是计算结果。

关于javascript - chrome.runtime.sendMessage 在 Chrome 扩展程序中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34550886/

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