我创建了一个自定义 HTML、CSS 和 JS 代码编辑器。我注意到编辑器可以运行 HTML 和 CSS 文件,但不能运行 JS 文件。这是代码:
const html_code = document.querySelector('.html-code textarea');
const css_code = document.querySelector('.css-code textarea');
const js_code = document.querySelector('.js-code textarea');
const result = document.querySelector('#result');
function run() {
// Storing data in Local Storage
localStorage.setItem('html_code', html_code.value);
localStorage.setItem('css_code', css_code.value);
localStorage.setItem('js_code', js_code.value);
// Executing HTML, CSS & JS code
result.contentWindow.eval(localStorage.html_code);
result.contentDocument.body.innerHTML = `<style>${localStorage.css_code}</style>` + localStorage.html_code;
result.contentWindow.eval(localStorage.js_code);
}
// Checking if user is typing anything in input field
html_code.onkeyup = () => run();
css_code.onkeyup = () => run();
js_code.onkeyup = () => run();
每当我将如下代码粘贴到 HTML 文本编辑器区域时,它将显示具有 Bootstrap 样式的按钮,但不会加载 Javascript JQuery,这使得下拉按钮不起作用。
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container">
<div class="dropdown">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
Dropdown button
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">Link 1</a>
<a class="dropdown-item" href="#">Link 2</a>
<a class="dropdown-item" href="#">Link 3</a>
</div>
</div>
</div>
</body>
</html>
我认为问题出在 eval 函数上。由于 CSP 问题,浏览器正在阻止它。除了 Eval 函数之外,我还有什么选择。