I am trying to add a code editor (using CodeMirror) to a Google Chrome Extension. However, because of the Content Security Policy, I'm unable to have an inline <script> tag or reference to a local blob file.
What's the best approach to getting JavaScript code to run? Also preferably it would be in its own environment so it can't interact with the popup HTML or more.
popup.html
<html>
<head>
<script src="codemirror/lib/codemirror.js"></script>
<link rel="stylesheet" href="codemirror/lib/codemirror.css">
<script src="codemirror/mode/javascript/javascript.js"></script>
<script src="codemirror.js" defer></script>
</head>
<body>
<input id="run-code" type="button" value="Run Code">
<textarea name="script-field" id="script-field" rows="5"></textarea>
</body>
</html>
codemirror.js
const editor = CodeMirror.fromTextArea(document.getElementById('script-field'), {
mode: 'javascript',
theme: 'mbo',
lineNumbers: true,
tabSize: 2,
lineWrapping: true,
autoCloseBrackets: true,
foldGutter: true,
gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"]
});
document.getElementById('run-code').onclick = () => {
runCode(editor.getValue());
}
function runCode(code) {
var file = new File([code], 'code.js');
var script = document.createElement('script');
script.src = URL.createObjectURL(file);
document.body.appendChild(script); // Does not work
}
codemirror.js:47 Refused to load the script 'blob:chrome-extension://...' because it violates the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.