我正在尝试创建一个新的扩展程序。我之前能够使用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"
]
}
}
感谢任何帮助:)
谢谢!
答案 0 :(得分:2)
您需要更改代码,以便在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可以用作即时反馈而不是计算结果。
答案 1 :(得分:0)
根据https://developer.chrome.com/extensions/messaging#simple末尾的文本,如果从background.js中的onMessage
处理程序返回true,则可以异步调用sendResponse。