我如何在popup.html中执行JavaScript

时间:2017-04-13 22:28:03

标签: javascript html google-chrome google-chrome-extension

它在普通的HTML网页上效果很好,但在我的Chrome扩展程序上无法正常工作。

我收到此错误:

Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

清单:

{
  "name": "script",
  "version": "1.3.2",
  "manifest_version": 2,
  "description": "script",
    "icons": {
    "16": "assets/immagine.png",
    "128": "assets/immagine.png"
  },
  "permissions":[
    "tabs", "storage"
   ],
  "browser_action": {
          "default_icon": {               
            "16": "assets/immagine.png",        
            "24": "assets/immagine.png",       
            "32": "assets/immagine.png"            
          },
         "default_popup": "popup.html",
         "scripts": ["calculator.js"]
   }

}

popup.html:

<html>
    <head>
        <script>

        var ammontare = 0 ;
        var npack = 0;
        var nprel = 0;
        var minprelievo = 0;

        function c(val)
        {
            document.getElementById("d").value=val;

        }

        function math(val)
        {
            document.getElementById("d").value+=val;
        }
        function e(pack)
        {   
            ammontare = document.getElementById("e").value;

            if (pack == 20) nprel = 5;
            if (pack == 30) nprel = 4;
            if (pack == 50) nprel = 6;
            if (pack == 70) nprel = 2;
            if (pack == 100) nprel = 3;
            var fut = (Number(ammontare)+Number(ammontare/4));

            var npack = (Number(ammontare)/Number(pack));
            nprel = (npack*nprel)+5;

            var minprelievo = (fut*nprel);
            var minprelievo = minprelievo.toFixed( 2 );

            try
            {
              c(minprelievo)
            }
            catch(e)
            {
              c('Error')
            }
        }


        </script>
    </head>

<body>
        INSERT Value:   
    <p><div class="display"><input type="number" size="15.75" id="e" > $</div></p>
        PRESS BUTTON: 
    <p>
        <input type="button" class="button gray" value="BUTTON1" onclick='e(20)'>
        <input type="button" class="button gray" value="BUTTON2" onclick='e(30)'>
        <input type="button" class="button gray" value="BUTTON3" onclick='e(50)'>
        <input type="button" class="button gray" value="BUTTON4" onclick='e(70)'>
        <input type="button" class="button gray" value="BUTTON5" onclick='e(100)'>  
     </p>


    <p>RESULTS:</p>
    <p><div class="display"><input type="number" readonly size="15.75" id="d"> $</div></p>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

将Javascript代码放在文件代码popup.js上,并将其放在与popup.html相同的文件夹中

然后加载:<script src="popup.js"></script>

这是因为内容安全政策: https://developer.chrome.com/extensions/contentSecurityPolicy