chrome.runtime.sendMessage在Chrome扩展程序中无效

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

内容的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!!!") } } ); 

的manifest.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!!!") } } ); 

而对于内容脚本,您需要做:

 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可以用作即时反馈而不是计算的结果。

根据https://developer.chrome.com/extensions/messaging#simple末尾的文本,如果从background.js中的onMessage处理程序返回true,则可以异步调用sendResponse。