【问题标题】:Content Script is not executing..(it is not receiving the message sent by background)内容脚本未执行..(它没有收到后台发送的消息)
【发布时间】: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


【解决方案1】:

此代码适用于我,当我打开开发人员工具时,console.log 语句会显示在页面的 Javascript 控制台中。确保刷新目标选项卡以注入内容脚本,并注意此脚本不会注入本地 HTML 文档,因为“file:///*”不是为内容脚本。

【讨论】:

  • 感谢尝试了我的代码,现在它可以工作了。 IDK y 它以前不工作
  • @Casey 我有预感。看看this answer。你的情况是这样吗?
猜你喜欢
  • 2014-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-27
  • 1970-01-01
  • 2013-06-26
  • 2014-11-23
  • 1970-01-01
相关资源
最近更新 更多