我正尝试创建一个新扩展。我可以在后面使用chrome.runtime.sendMessage函数,但现在我已经尝试了一切,但它仍然无法将消息发送到后台脚本。该控制台得到填充了content-script.js
的日志消息而不是从background.js
chrome.runtime.sendMessage在Chrome扩展中不起作用
内容的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!!!")
}
}
);
清单。 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"
]
}
}
任何帮助表示赞赏:)
谢谢!
就是这样!它像一个魅力。现在,你能解释一下为什么你使用''chrome.tabs''?我无法正确理解代码示例中的数据流。是这样吗? 内容脚本(生成事件) - >后台脚本(进程事件) - >后台脚本(创建响应事件) - >内容脚本(进程响应事件)? 难道没有其他方法可以做到吗?抱歉挑剔,但由Google提供的文档不好:( –
@PranavJituri通常我会写扩展名,以便我的背景只与当前标签进行通信,如果此标签符合我的兴趣,否则我不注入jquery,js,。 ...我不惜一切代价来重载Chrome浏览器,是的,您正确理解了我的流程,并且我建议您查看Chrome扩展程序[Message Passing](https://developer.chrome.com/extensions/messaging) – gaetanoM
非常感谢你帮忙解释代码背后的概念:) –