简体   繁体   English

Chrome扩展程序的弹出HTML变通办法

[英]Chrome Extension workaround with popup html

My project is a Chrome extension that will do the following. 我的项目是一个Chrome扩展程序,它将执行以下操作。

  • Push the extension icon. 按下扩展程序图标。
  • Popup will appear (from popup.html) 弹出窗口将出现(来自popup.html)
  • 5 buttons will be in the popup. 5个按钮将出现在弹出窗口中。
  • When you click one of the four buttons, one javascript code will be executed. 当您单击四个按钮之一时,将执行一个javascript代码。
  • close popup window. 关闭弹出窗口。

So depending on the answer of this post over here 因此,根据这里的帖子答案

Detect a button click in the browser_action form of a Google Chrome Extension 在Google Chrome扩展程序的browser_action表单中检测按钮单击

(big ups to Michael for his enormous help) (感谢Michael的大力帮助)

This example is only for one button. 本示例仅适用于一个按钮。 Created it with only one of my javascript code and works perfect. 仅使用我的一个JavaScript代码创建了它,并且效果完美。 But when it comes to put all of the 5 buttons i 've tried to make this kind of coding but it didnt work at all (im new at javascript code so dont hate) 但是,当涉及到所有5个按钮时,我尝试过进行这种编码,但它根本没有用(我对JavaScript代码是新的,所以不要讨厌)

Here are the codes 这是代码

MANIFEST.JSON 的manifest.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 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 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 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);
        }
    }
);

So the codes in the link are working PERFECT for only 1 button. 因此,链接中的代码仅对1个按钮有效。 in this example i am trying to make it work for 2 buttons but i cant find what im doing wrong. 在这个例子中,我试图使它适用于2个按钮,但我找不到我做错了什么。 If anyone has any idea i would appreciate it. 如果有人有任何想法,我将不胜感激。

Thanks a lot for your time!!! 非常感谢您的宝贵时间!!!

(UPDATE 2. Updated codes for 2 buttons but not working.) (更新2。更新了2个按钮的代码,但不起作用。)

You're defining clickHandler twice, so only the second one counts. 您要定义clickHandler两次,因此只有第二个才有意义。 One fix would be: 一种解决方法是:

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

In general, you're repeating yourself too much. 通常,您重复的次数太多。 You could combine your DOMContentLoaded events into one: 您可以将DOMContentLoaded事件合并为一个:

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

but even better would be to put all the buttons into an array, so that popup.js is now: 但更好的方法是将所有按钮放入数组中,这样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);
    }
})

(And I'd recommend button { font-size: 20px; } in your style instead of five separate ids.) (并且我建议您以自己的样式使用button { font-size: 20px; } ,而不要使用五个单独的ID。)

Finally, your switch statement is buggy. 最后,您的switch语句有错误。 Once you start a case, you'll keep going until you get to a break , so that case "popup-click-l" hits both cases. 一旦启动一个案例,您将继续进行直到break ,这样该case "popup-click-l"击中这两个案例。 You could have a separate executeScript for each case, but even better would be to assign to fileName based on the case, and have a single injection at the end. 对于每种情况,您可以有一个单独的executeScript ,但更好的做法是根据大小写分配给fileName ,并在末尾进行一次注入。 Or best of all would be to have a javascript object define which files go with which ids, so that background.js is now: 或最好的办法是让一个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({});
    }
);

Fundamentally, this comes back to a point I made in a comment: browser extensions are a bad way to learn javascript, because you're learning two separate things at the same time. 从根本上讲,这可以回到我在评论中提到的观点:浏览器扩展是学习javascript的一种不好的方法,因为您正在同时学习两个不同的东西。 Your difficulties with switch , {} , and generally following the code is a javascript problem. 您在switch{}和通常遵循代码方面的困难是一个JavaScript问题。 Not seeing when the console tells you about syntax errors is more of a browser extension problem. 当控制台告诉您语法错误时,看不到内容更多是浏览器扩展问题。 And your biggest problem is that you're not seeing which error is which. 而最大的问题是您看不到哪个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM