【问题标题】:Can't get content_security_policy to work in my extension [duplicate]无法让 content_security_policy 在我的扩展程序中工作 [重复]
【发布时间】:2020-09-23 18:45:51
【问题描述】:

我有一个简单的扩展只是为了练习,但我无法让我的清单中的内容安全策略起作用。

将来我希望我的扩展程序将某些内容保存到本地存储中,以检查复选框是否已选中。如果是则执行脚本,否则不执行。

那么您能帮我让我的内容安全策略发挥作用吗?


错误信息:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-y41ZtWjHQFuEU+QTE3BHhHgUC/osK4XMOpRmws6llyQ='), or a nonce ('nonce-...') is required to enable inline execution.

manifest.json

    {
        "name": "no-name",
        "version": "0.0.01",
        "description": "non yet",
        "permissions": ["storage"],
        "content_scripts": [
            {
                "matches": [
                    "<all_urls>"
                ],
                "js": ["content-script.js"]
            }
        ],
        "browser_action": {
            "default_popup": "popup.html"
        },
        "content_security_policy": "???",
        "manifest_version": 2
    }

popup.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <script>
            window.addEventListener('DOMContentLoaded', (event) => {
                function click() {
                    let switchPopup = document.getElementById('ex_switchPopup');
            
                    if(switchPopup.checked == true) {
                        console.log('It\'s checked');
                    }
                }
            });
        </script>
    </head>
    <body>
        <label class="switch">
            <input type="checkbox" id="ex_switchPopup" checked onclick="click()">
            <span class="slider round"></span>
        </label>
    </body>
    </html>

【问题讨论】:

    标签: html json google-chrome-extension


    【解决方案1】:

    您必须将 javascript 代码从 html 移动到 js 文件。 Chrome 政策不允许内联脚本。检查documentation

    创建popup.js 文件

    window.addEventListener('DOMContentLoaded', (event) => {
      document.getElementById('ex_switchPopup').addEventListener('click', YOUR_LISTENER);
    })
    

    在你的 html 中添加链接

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

    【讨论】:

    • 我试试,但我想我已经尝试过你的答案。它仍然说我不能做内联js
    猜你喜欢
    • 1970-01-01
    • 2010-10-07
    • 2018-03-09
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    相关资源
    最近更新 更多