Javascript 不在本地页面上 运行

Javascript does not run on local page

我有一个非常简单的网络扩展程序,它应该在单击按钮时在新 window 中打开本地页面:

function openMyPage() {
    var popupURL = chrome.extension.getURL("my-page.html");

    chrome.windows.create({
      url: popupURL,
      type: "popup",
      height: 200,
      width: 200
    });
}

chrome.browserAction.onClicked.addListener(openMyPage);

在我的-page.html 里面,我想 运行 一些 javascript 但我无法让它工作。连个简单的脚本都不执行:

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

打开页面的 URL 与 moz-extension://8974747a-3aa7-4654-93e5-ad60d3de0cc5/my-page.html 类似。我试过禁用 NoScript 等插件,但无济于事。

如何在这个页面执行JS?我究竟做错了什么?感谢您的帮助。

编辑:manifest.json 根据要求:

{

  "description": "Adds browser action icon to toolbar to open packaged web page. See https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Examples#open-my-page-button",
  "manifest_version": 2,
  "name": "open-my-page",
  "version": "1.0",
  "homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/open-my-page-button",
  "icons": {
    "48": "icons/page-48.png"
  },

  "applications": {
    "gecko": {
      "id": "open-my-page-button@mozilla.org",
      "strict_min_version": "45.0"
    }
  },

  "background": {
    "scripts": ["background.js"]
  },

  "browser_action": {
    "default_icon": "icons/page-32.png"
  }

}

它直接取自 Mozilla 的示例之一。

内联脚本不适用于默认内容安全策略

您可能 运行 进入 Default Content Security Policy 即:

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

也就是说Inline JavaScript won't run。换句话说,您的 HTML:

中不允许出现以下内容
<script type="text/javascript"> document.write("JS executed")</script>

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

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

正解:
正常的解决方案是将所有 JavaScript 移动到一个或多个单独的文件中,并将它们包含在类似以下内容中:

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

使用内联脚本:
如果你想使用内联脚本,你可以使用 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."

除非出于某种原因,您确实需要使用内联脚本,否则您可能会发现非常更容易移动所有您的脚本内容到外部文件,而不是包含与您的 HTML 内联的脚本(这将要求您重新计算哈希以对脚本进行任何更改)。

在 Firefox 48 中实现:
此内容安全策略是 implemented in Firefox 48。关于 Firefox 48 的博客 post 一定要提到:

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.

您的具体情况:

如果您将脚本更改为(创建哈希时空格计数),它将起作用:

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

然后,将以下行添加到您的 manifest.json:

"content_security_policy": "script-src 'self' 'sha256-Z4nYjltJ/RciFs77n2n91dzwoz1Qg/1JFwU5ODwWPC8='; object-src 'self';"