将iframe注入网页时,如何处理内容安全策略(CSP)?

时间:2019-01-10 16:13:08

标签: javascript angular google-chrome-extension content-security-policy

我正在尝试构建一个chrome浏览器扩展程序,无论何时单击chrome-extension图标,都会将iframe注入到当前页面,然后将其呈现在内部的角度应用程序打包到chrome扩展程序本身(即而不是外部来源)。除了无法克服CSP违规之外,我已经可以正常工作了。

manifest.json

  {
      "manifest_version": 2,
      "name": "My Extension",
      "description": "injects iframe in all pages on command",
      "version": "1.0",
      "permissions": ["storage", "tabs", "debugger", "*://*.google.com/*", "http://*/*", "https://*/*", "notifications"],
      "browser_action": {
        "default_icon": "icon.png",
        "defualt_title": "My Extension"
      },
      "background": {
        "scripts": ["background.js"]
      },
      "content_security_policy": "script-src 'self' https://*.googleapis.com/*; object-src 'self' https://*.googleapis.com/*",
      "web_accessible_resources": [
        "index.html",
        "assets/css/*",
        "assets/js/*",
        "assets/fonts/*"
      ]
    }

background.js

chrome.browserAction.onClicked.addListener(function(activeTab) {
    chrome.tabs.executeScript(null, {file: "contentScript.js"});
});

contentScript.js

'use strict';
var iframe = document.createElement('iframe');
iframe.src = chrome.extension.getURL("index.html");
iframe.id = 'myExtension';
document.body.appendChild(iframe);

console.log('content script has executed');

然后,您将拥有典型的index.html for和vanilla Angular应用程序:

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <!-- <meta http-equiv="Content-Security-Policy" content="script-src 'self' https://*.googleapis.com/* 'unsafe-eval'; object-src 'self' https://*.googleapis.com/*"> -->
  <title>My Extension</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
    crossorigin="anonymous">
</head>

<body>
  <div class="container-fluid" style="height: 400px; overflow: hidden;">
    <app-root></app-root>
  </div>

  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
    crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
    crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
    crossorigin="anonymous"></script>
</body>

</html>

在浏览器中构建和测试扩展后,出现以下错误:

enter image description here

我已经进行了研究,但发现的答案似乎都不适合我的特定用例,或者CSP对我来说太细微了,无法理解这些解决方案的适用性。解决这个问题的任何帮助都是传奇!

0 个答案:

没有答案