未捕获的SyntaxError:插入CDATA

时间:2016-08-29 15:47:21

标签: javascript jquery

我试图在我的页面上复制jsfiddle的行为,这意味着用户可以提交一些javascript,它将在iframe中呈现。但是,我的测试代码失败了,js正在jsfiddle上运行。任何帮助都非常感谢!!!

我页面上的错误消息:

VM16741:2 Uncaught SyntaxError: Invalid or unexpected token

当我点击VM16741:2时,我得到以下内容:

\\<![CDATA[
    window.onload=function() {
document.querySelector('.test').style.backgroundColor="rgb(21, 160, 249)";
}//]]>

检查jsfiddle的输出,您会在头部看到:

<script type="text/javascript">
 //<![CDATA[
 window.onload=function(){
 document.querySelector('.test').style.backgroundColor="rgb(21, 160, 249)"; 
 }//]]> 
</script>

这是我的代码(我认为除了空格外相同):

  <script type="text/javascript">
\\<![CDATA[
    window.onload=function() {
document.querySelector('.test').style.backgroundColor="rgb(21, 160, 249)";
}//]]>
</script>

以下是我网页测试中iframe的输出:

<html>
 <head>
  <style>
    .test { display:inline-flex; padding:40px; background-color:#cccccc }
  </style>
  <script type="text/javascript">
\\<![CDATA[
    window.onload=function() {
document.querySelector('.test').style.backgroundColor="rgb(21, 160, 249)";
}//]]>
  </script>
</head>
<body>
  <div class="test">test</div>
</body></html>

以下是用于将css,html和js插入iframe的js:

$(document).ready(function() {


  var html = //some html here - works
  var css = //some css here - works
  var js = //some js here - fails

  var sandbox = $('.sandboxed');
  sandbox.ready(function() {
    var htmlContainer = document.createElement('div');
    var cssContainer = document.createElement('style');
    var jsContainer = document.createElement('script');
    jsContainer.setAttribute('type', 'text/javascript');
    var head = sandbox.contents().find('head');
    var body = sandbox.contents().find('body');
    $(head).append(cssContainer);
    $(head).append(jsContainer);
    $(html).append(htmlContainer);
    $(cssContainer).append('\n\t'+css+'\n');
    $(jsContainer).text('\n\\\\<![CDATA[\n\twindow.onload=function() {\n'+js+'\n}//]]>\n');
    body.prepend(html);
  });

});

如果我展开错误,我会收到以下消息:

(anonymous function)    @   jquery.min.js:3
each    @   jquery.min.js:2
each    @   jquery.min.js:2
(anonymous function)    @   jquery.min.js:3
S   @   jquery.min.js:2
text    @   jquery.min.js:3
(anonymous function)    @   sandbox.js:20
j   @   jquery.min.js:2
k   @   jquery.min.js:2

0 个答案:

没有答案
相关问题