【发布时间】:2015-04-18 02:20:46
【问题描述】:
我正在开发将页面上所有 div 的背景颜色更改为红色但控件不会传递给内容脚本的扩展。使用开发人员工具,我可以在 background.js 和 popup.js 中设置断点,但不能在 content.js 中设置断点,所以我使用了 console.log,但它没有执行 plz help
popup.html
<!DOCTYPE html>
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
<button id="change-btn">Change color of Divs</button>
</body>
</html>
popup.js
window.onload=init;
function init(){
var btn=document.getElementById("change-btn");
btn.onclick = function(){
chrome.runtime.sendMessage({type:"color-div" });
}
};
background.js
chrome.runtime.onMessage.addListener(function(request, sender, response){
if(request.type==="color-div"){
colordiv();
}
});
function colordiv(){
chrome.tabs.query({ active:true, currentWindow:true} , function(tab){
chrome.tabs.sendMessage( tab[0].id, {type: "colors-div", color: "#F00"});
});
};
content.js
chrome.runtime.onMessage.addListener(function(request, sender, response){
if(request.type==="colors-div"){
var divs= document.querySelectorAll("div");
if(divs.length===0)
alert("There r no divs on this page ");
else{
console.log("Before for loop");
for(var i=0; i<divs.length; i++)
{
divs[i].style.backgroundColor=request.color;
}
console.log("After for loop");
}
}
});
manifest.json
{
"name": "BrowserExtension",
"version": "0.0.1",
"manifest_version": 2,
"description" : "Description ...",
"content_scripts": [{
"matches": ["http://*/*", "https://*/*"],
"js": ["content.js"]
}],
"browser_action": {
"default_icon": "icon.png",
"default_title": "That's the tool tip",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"],
"persistent": false
},
"permissions":["tabs"]
}
【问题讨论】:
-
您知道您需要选择特定于扩展的控制台吗?就在左侧控制台上方是您想要的下拉菜单。
-
@Teepeemm 执行语句需要,但读取日志不需要(从所有上下文中显示)
-
如果您说您无法设置断点 - 您是否正在寻找正确的开发工具?如果应该是页面自己的开发工具。
-
乍一看,您的代码对我来说是正确的。但是,如果您在单独的窗口中运行调试器,则您的活动选项卡查询可能会返回 DEBUGGER 窗口(内容脚本未注入到该窗口)
标签: google-chrome google-chrome-extension