The Chrome extension popup is not working, click events are not handled

后端 未结 2 1859
北恋
北恋 2020-11-22 02:51

I have created a JavaScript variable and when I click on the button it should increment by 1, but its not happening.

Here\'s manifest.json.



        
相关标签:
2条回答
  • 2020-11-22 03:23

    Change your onclick:

    onclick="count"
    

    Or change your count function to something like this:

    function count()
    {
    
        var demo = document.getElementById("demo");
        return function() {
            demo.innerHTML = ++a;
        }
    
    }
    

    Here is a nice demo I put together:

    Code (this assumes that you add id="the_button" to your button):

    window.onload = function () {
        var button = document.getElementById("the_button");
        button.onclick = count();
    
        function count() {
            var a = 0;
            var demo = document.getElementById("demo");
            return function () {
                demo.innerHTML = ++a;
            }
        }
    }
    

    Demo: http://jsfiddle.net/maniator/ck5Yz/

    0 讨论(0)
  • 2020-11-22 03:35

    Your code is not working because it violates the default Content Security Policy. I've created a screencast of one minute to show what's wrong:

    First, I've shown how to debug the problem. Right-click on your popup button, and click on "Inspect popup". After doing that, you will see the following error message:

    Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".

    This explains that your code is not working, because it violates the default CSP: Inline JavaScript will not be executed. To solve the problem, you have to remove all inline JavaScript from your HTML file, and put it in a separate JS file.

    The result is shown below:

    hello.html (popup page)

    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
    <p id="demo">=a</p>
    <button type="button" id="do-count">Count</button>
    <script src="popup.js"></script>
    </body>
    </html>
    

    popup.js

    var a=0;
    function count() {
        a++;
        document.getElementById('demo').textContent = a;
    }
    document.getElementById('do-count').onclick = count;

    Note that I've replaced innerHTML with textContent. Learn to use textContent instead of innerHTML when you intend to change the text. In this simple example it does not matter, but in more complex applications, it might become a security issue in the form of XSS.

    0 讨论(0)
提交回复
热议问题