【问题标题】:Unable to trigger chrome.browserAction.onClicked.addListener with google chrome extensions无法使用谷歌浏览器扩展触发 chrome.browserAction.onClicked.addListener
【发布时间】:2013-09-16 23:52:06
【问题描述】:

我有点卡在这里,想知道是否有人可以指出我可能错在哪里。

我只是想在点击应用图标时将主体颜色变为红色。

manifest.json

{
    "name": "Bagde",
    "description": "",
    "version": "1",
    "manifest_version": 2,
    "background": {
        "scripts": [
            "background.js"
        ]
    },
    "browser_action": {
        "default_title": "Test",
        "default_popup": "popup.html"
    }
}

popup.html

<html>

    <head>
        <script src="popup.js"></script>
    </head>

    <body>
        <p>Some Content ..</p>
    </body>

</html>

popup.js

document.addEventListener("DOMContentLoaded", function () {
    //Get Reference to Functions
    backGround = chrome.extension.getBackgroundPage();
    //Call Function
    backGround.updateIcon();
  });

background.js

var i = 1;

function updateIcon() {
    i = 1;
    chrome.browserAction.setBadgeText({
        text: 'Test'
    });
    chrome.browserAction.setPopup({
        popup: "popup.html"
    });
}


chrome.browserAction.setBadgeBackgroundColor({
    color: [200, 0, 0, 100]
});

window.setInterval(function () {
    chrome.browserAction.setBadgeText({
        text: String(i)
    });
    i++;
}, 4000);

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(null,
        {code:"document.body.bgColor='red'"});
});

任何想法我可能做错了什么?感谢您抽出宝贵时间阅读本文。

【问题讨论】:

    标签: google-chrome google-chrome-extension google-chrome-app


    【解决方案1】:

    如果您定义default_popup,则您不能拥有browserAction.onClicked 的侦听器。在这种情况下,您只需将处理程序中的代码添加到您的popup.js

    编辑:也就是说,将以下内容添加到popup.js

    chrome.tabs.executeScript(null, {code:"document.body.bgColor='red'"});
    

    【讨论】:

    • 嗨@rsanchez你是说删除我在popup.js中的所有内容并将其替换为 chrome.browserAction.onClicked.addListener(function(tab) { chrome.tabs.executeScript(null, {code:"document.body.bgColor='red'"}); });?因为这样做仍然不会使我的页面在点击时变红
    • @BaconJuice 不,只是处理函数中的代码。查看我的更新。
    • 将其添加到我的 popup.js 不会使我的页面在点击时呈现红色。有任何想法吗?谢谢你的帮助!
    • @BaconJuice 您还需要将您希望能够变为红色的页面的网址添加到权限中。如果您希望它在任何页面上工作,请添加&lt;all_urls&gt;
    • "你不能拥有 browserAction.onClicked 的监听器" 这是验证这一点的文档:developer.chrome.com/extensions/browserAction#event-onClicked
    猜你喜欢
    • 1970-01-01
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    相关资源
    最近更新 更多