Javascript does not run on local page

前端 未结 1 1259
醉话见心
醉话见心 2021-01-20 00:52

I have a very simple webextension that is supposed to open a local page in a new window when a button is clicked:

function openMyPage() {
    var popupURL =          


        
相关标签:
1条回答
  • 2021-01-20 01:27

    Inline scripts don't work with the Default Content Security Policy

    You are probably running into the Default Content Security Policy which is:

    "script-src 'self'; object-src 'self';"
    

    Which means that Inline JavaScript won't run. In other words things like following are not permitted in your HTML:

    <script type="text/javascript"> document.write("JS executed")</script>
    

    or

    <script>console.log("foo");</script>
    

    or

    <div onclick="console.log('click')">Click me!</div>
    

    Normal solution:
    The normal solution is to move all your JavaScript into one, or more, separate files and include them with something like:

    <script type="text/javascript" src="my-page.js"></script>
    

    Using inline scripts:
    If you desire to use inline scripts, you can use the content_security_policy key in your manifest.json file. However, you will need to supply a "hash of the script in the "script-src" directive."

    Unless, for some reason, you really need to use inline scripts, you will probably find it much easier to move all of your script content to an external file rather than include scripts inline with your HTML (which would require you to recompute the hash for any change to the script).

    Implemented in Firefox 48:
    This Content Security Policy was implemented in Firefox 48. That blog post regarding Firefox 48 makes sure to mention:

    Please note: this will be a backwards incompatible change for any Firefox WebExtensions that did not adhere to this CSP. Existing WebExtensions that do not adhere to the CSP will need to be updated.

    Your specific case:

    It will work if you change your script to (whitespace counts when creating the hash):

    <script type="text/javascript">document.write("JS executed");</script>
    

    And, add the following line to your manifest.json:

    "content_security_policy": "script-src 'self' 'sha256-Z4nYjltJ/RciFs77n2n91dzwoz1Qg/1JFwU5ODwWPC8='; object-src 'self';"
    
    0 讨论(0)
提交回复
热议问题