我正在尝试将消息从弹出式JavaScript发送到内容脚本。当我尝试从回调中读取属性时,响应对象始终是未定义的。我是Java语言的新手,所以我不确定我的错误在哪里。我的代码在下面。
popup.js
var elementPickerInjected = false;
var elementPickerRunning = false;
var button = document.getElementById("pickElement");
button.onclick = function() {
if (!elementPickerInjected) {
chrome.runtime.sendMessage("injectElementPicker");
}
var message = elementPickerRunning ? "stopElementPicker" : "runElementPicker";
console.log(message);
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, message, function(response) {
//elementPickerRunning = response.running;
alert(chrome.runtime.lastError.message);
});
});
}
elementPicker.js(内容脚本)
$("body").wrap("<div class='grey_out'></div>");
screenDimmed = false;
var oldColor;
var oldElem = null;
var currentElem = null;
chrome.runtime.onMessage.addListener(
function (message, sender, sendResponse) {
if (message == "runElementPicker") {
runElementPicker();
sendResponse({running: true});
} else if (message == "stopElementPicker") {
stopElementPicker();
sendResponse({running: false});
}
}
);
function runElementPicker() {
dimScreen();
document.addEventListener("mousemove", highlightElement(event));
}
function stopElementPicker() {
undimScreen();
document.removeEventListener("mousemove", highlightElement);
}
function highlightElement(event) {
var x = event.clientX;
var y = event.clientY;
currentElem = document.elementFromPoint(x, y);
if (currentElem != oldElem) {
if (oldElem) {
oldElem.style.backgroundColor = oldColor;
}
oldColor = currentElem.style.backgroundColor;
oldElem = currentElem;
currentElem.style.backgroundColor = "#FDFF47";
}
}
function dimScreen() {
$(".grey_out").css("display", "none");
//$(".grey_out").css("display", "none");
screenDimmed = true;
}
function undimScreen() {
$(".grey_out").css("display", "block");
screenDimmed = false;
}
manifest.json
{
"name": "Image Gallery Viewer",
"description": "This is a description",
"version": "1.0",
"manifest_version": 2,
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_popup": "popup.html",
"default_icon": {
"16": "images/icon16.png",
"32": "images/icon32.png"
},
"default_title": "Start a gallery"
},
"permissions": [
"activeTab",
"<all_urls>",
"debugger"
]
}
当我单击弹出窗口上的“ pickElement”按钮时,elementPicker.js确实收到了消息,因为屏幕变暗了。但是,当我尝试读取发送回的响应对象的“运行”属性时,出现错误-“(未知的)事件处理程序中的错误:TypeError:无法读取未定义的属性” running”。 lastError.message显示为“无法建立连接。接收端不存在。”