javascript - 使用弹出 html 的 Chrome 扩展解决方法

标签 javascript google-chrome google-chrome-extension

我的项目是一个 Chrome 扩展程序,它将执行以下操作。

  • 按扩展程序图标。
  • 将出现弹出窗口(来自 popup.html)
  • 5 个按钮将出现在弹出窗口中。
  • 当您点击四个按钮之一时,将执行一段 javascript 代码。
  • 关闭弹出窗口。

所以取决于这里的这篇帖子的答案

Detect a button click in the browser_action form of a Google Chrome Extension

(感谢迈克尔的巨大帮助)

这个例子只针对一个按钮。仅使用我的一个 javascript 代码创建它并且工作完美。 但是当涉及到放置所有 5 个按钮时,我尝试进行这种编码,但它根本不起作用(我是 javascript 代码的新手,所以不要讨厌)

代码如下

list .JSON

{
   "background": {
      "scripts": [ "background.js" ]
   },
   "browser_action": {
      "default_icon": "img/icon.png",
      "default_title": "TITLE",
      "default_popup": "popup.html"
   },
   "icons": {
      "128": "img/icon_128.png",
      "19": "img/icon19.png",
      "38": "img/icon38.png",
      "48": "img/icon_48_2.png"
   },
   "manifest_version": 2,
   "name": " NAME",
   "description": " DESCR ",
   "permissions": [ "activeTab" ],
   "version": "2.0"
}

POPUP.HTML

<html>
    <head>
        <script src="popup.js"></script>
        <style type="text/css" media="screen">
            body { min-width:250px; text-align: center; }
            #click-me-l { font-size: 20px; }
            #click-me-f { font-size: 20px; }

        </style>
    </head>
    <body>
        <button id='click-me-l'>Click1</button>
        <button id='click-me-f'>Click2</button>

    </body>
</html>

POPUP.JS

    function clickHandler(e) {
        chrome.extension.sendMessage({directive: "popup-click-l"}, function(response) {
            this.close(); // close the popup when the background finishes processing request
        });
    }


 document.addEventListener('DOMContentLoaded', function () {
        document.getElementById('click-me-l').addEventListener('click', clickHandler);

    })


     function clickHandler(e) {
        chrome.extension.sendMessage({directive: "popup-click-f"}, function(response) {
            this.close(); // close the popup when the background finishes processing request
        });
    }


document.addEventListener('DOMContentLoaded', function () {
        document.getElementById('click-me-f').addEventListener('click', clickHandler);

    })

BACKGROUND.JS

chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) {
        switch (request.directive) {

             case 1 "popup-click-l":
            // execute the content script
            chrome.tabs.executeScript(null, { // defaults to the current tab
                file: "script1.js", // script to inject into page and run in sandbox
                allFrames: true // This injects script into iframes in the page and doesn't work before 4.0.266.0.
            });

        case 2 "popup-click-f":
            // execute the content script
            chrome.tabs.executeScript(null, { // defaults to the current tab
                file: "script2.js", // script to inject into page and run in sandbox
                allFrames: true // This injects script into iframes in the page and doesn't work before 4.0.266.0.
            });
            sendResponse({}); // sending back empty response to sender
            break;
        default:
            // helps debug when request directive doesn't match
            alert("Unmatched request of '" + request + "' from script to background.js from " + sender);
        }
    }
);

因此链接中的代码仅适用于 1 个按钮。 在这个例子中,我试图让它适用于 2 个按钮,但我找不到我做错了什么。如果有人有任何想法,我将不胜感激。

非常感谢您的宝贵时间!!!

(更新 2。更新了 2 个按钮的代码但不起作用。)

最佳答案

您定义了两次 clickHandler,所以只有第二次才算数。一种解决方法是:

function clickHandler(e) {
    chrome.extension.sendMessage({"directive": e.target.id}, function(response) {
        this.close(); // close the popup when the background finishes processing request
    });
}

总的来说,您重复的太多了。您可以将 DOMContentLoaded 事件合并为一个:

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('click-me-l').addEventListener('click', clickHandler);
    document.getElementById('click-me-f').addEventListener('click', clickHandler);
})

但更好的办法是将所有按钮放入一个数组中,这样 popup.js 现在是:

function clickHandler(e) {
    chrome.extension.sendMessage({"directive": e.target.id}, function(response) {
        this.close(); // close the popup when the background finishes processing request
    });
}

document.addEventListener('DOMContentLoaded', function () {
    var buttons = document.getElementsByTagName("button");
    for ( var i = 0 ; i < buttons.length ; i++ ) {
        buttons[i].addEventListener('click',clickHandler);
    }
})

(我建议在您的样式中使用 button { font-size: 20px; } 而不是五个单独的 id。)

最后,您的 switch 语句有问题。一旦你开始一个案例,你将继续前进,直到你到达一个 break,这样 case "popup-click-l" 会同时命中这两个案例。您可以为每种情况使用单独的 executeScript,但更好的方法是根据情况分配给 fileName,并在最后进行一次注入(inject)。或者最好的办法是让一个 javascript 对象定义哪些文件与哪些 id,这样 background.js 现在是:

chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) {
        var injected = {
            "click-me-l": "script1.js",
            "click-me-f": "script2.js"
        };
        chrome.tabs.executeScript(null, {
            "file": injected[request.directive],
            "allFrames": true
        });
        sendResponse({});
    }
);

从根本上说,这又回到了我在评论中提出的观点:浏览器扩展是学习 javascript 的糟糕方式,因为您同时在学习两个不同的东西。您在 switch{} 以及通常遵循代码方面遇到的困难是 javascript 问题。看不到控制台何时告诉您有关语法错误更多的是浏览器扩展问题。你最大的问题是你看不到哪个错误是哪个。

关于javascript - 使用弹出 html 的 Chrome 扩展解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28960773/

相关文章:

javascript - "' 长度 ' in Object(obj)"在js中是如何工作的?

android - Android 上的 Chrome,系统字体不考虑字体粗细

google-chrome-extension - 我可以允许扩展用户选择匹配的域吗?

google-chrome-extension - 如何找到用于开发 chrome 扩展的 Google 的 OAuth 2.0 客户端 key ?

javascript - 使用 Javascript 的 Flowtype 解释泛型

javascript - 由于 Bootstrap 和 Google map 之间存在冲突,div 变灰

javascript - 使用 Node.js 和 Cheerio 抓取公司名称

html - 在Google Chrome中播放AVI视频

javascript - Chrome 中的时态

javascript - 无法在 Google Chrome 扩展程序中获取正确的 Ace 编辑器文本