tinymce “codesample” plugin execute HTML tag

2022-08-30 22:26:53

我正在使用tinymmce的代码样本插件,这在我的自定义门户中 https://www.tinymce.com/docs/plugins/codesample/ 这里提到。

一切正常,直到我必须“重新编辑”存储在数据库中的数据。

当我去编辑时,所有数据存储在数据库中

<pre><code>&lt;html&gt; &lt;p&gt;Text&lt;/p&gt; &lt;/html&gt; </code></pre>

被剥离并显示为仅

<pre><code>Text </code></pre>

从“工具>源”中查看时

我已经在我的文本区域中使用了“htmlentities”,比如:-

<textarea><?php echo htmlentities($content); ?></textarea>

它仍然会剥离插件创建的标签内使用的所有html标签。codesample

常见问题解答 : 1.首次添加数据时,一切正常。2.问题仅在我去编辑页面时。Tinymce仅从插件中剥离HTML代码。其余所有使用代码样本(如“css,python,php”等)添加的代码都显示在编辑器中。codesample


答案 1

将数据插入tinymmce的正确方法不是将其打印出来,甚至不使用。请考虑以下代码htmlentities

<div class="editor" id="editor">
</div>
<script>
    tinymce.init({
      selector: 'div.editor',
      theme: 'inlite',
      plugins: 'image table link paste contextmenu textpattern autolink',
      insert_toolbar: 'quickimage quicktable',
      selection_toolbar: 'bold italic | quicklink h1 h2 h3 blockquote',
      inline: true,
      paste_data_images: true,
      automatic_uploads: true,
      init_instance_callback : function(ed) {
        // ed.setContent("<h1>Title</h1><p>Content...</p>");
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
           if (xhttp.readyState == 4 && xhttp.status == 200) {
              ed.setContent(xhttp.responseText);
           }
        };
        xhttp.open("GET", "content.php", true);
        xhttp.send();
      },
      content_css: [
        '//www.tinymce.com/css/codepen.min.css'
      ]
    });
</script>

文件应该只是简单地打印html内容content.php

<?php
    $content = ''; // Fetch from database
    print $content;
?>

注意在我初始化tinymce时的函数。这是在 tinymce 初始化后调用的函数。现在,直接在编辑器内部使用,在内部进行ajax调用并在那里呈现它。我已经放入了一个示例注释行,只是为了帮助您解决相同的问题。这也将负责安全验证(如果有的话,则不执行脚本标记)。init_instance_callbackprintinit_instance_callback

同时获取编辑器的内容,同时将其保存到数据库是

var content = tinyMCE.get('editor').getContent();

然后,您可以发出ajax post请求以将数据保存到数据库。

现在我为什么使用ajax很重要。我尝试了很多其他方法,我可以直接打印它。但这会导致安全漏洞,因为脚本标签可以在编辑器初始化之前运行。

我在此示例中使用了 div,但即使对于文本区域也是如此。也不要使用htmlentities,因为这会转义html内容,并且你希望看到在tinymmce中呈现的内容,而不是转义版本。


答案 2

好吧,经过大量研究,我发现这是一个编码问题。需要对每个实体进行编码,如 :- 、 to 、 .<>&lt;&gt;

而标记内的字符为 ,则表示在标记内变为 。&<code>&amp;&lt;<code></code>&amp;lt;

因此,代码如下:-

<pre><code>&lt;html&gt; &lt;p&gt;Text&lt;/p&gt; &lt;/html&gt; </code></pre>

应该像

&lt;pre&gt;&lt;code&gt;&amp;lt;html&amp;gt; &amp;lt;p&amp;gt;Text&amp;lt;/p&amp;gt; &amp;lt;/html&amp;gt; &lt;/code&gt;&lt;/pre&gt;

因此,对于所有正在寻找解决方案的用户。这就是解决方案。

请记住,内部标记只能转换为 。注意内部标签是&<code> &amp;lt; </code>&amp;&lt;<code>&amp;lt;

干杯


推荐