简体   繁体   中英

encoding/decoding html using javascript

I am using Tinymce editor for formatting articles in my ASP.NET page.
here is my code:-

 <asp:TextBox runat="server" ID="textarea" Height="70px" 
        Width="324px" TextMode="MultiLine"></asp:TextBox><br />
    <asp:Button ID="submit" runat="server" Text="Button" 
    OnClientClick="encodeMyHtml()" onclick="submit_Click" CausesValidation="False"/>
</div>

and this is what i have find on the web for encoding html here and tried to use it.

function encodeMyHtml() {
    var htmlToEncode = document.getElementById("textarea").value;
    // save content after encoding
    alert(htmlToEncode);
    var encodedHtml = escape(htmlToEncode);
    alert(encodedHtml);
    // Later when displaying it back, decode it.
    var ohtml = unescape(encodedHtml);
    alert(ohtml);
}

and this also

   function encodeMyHtml() {
      var htmlText = document.getElementById('textarea').value;
      htmlText = htmlText.replace(/\</g, "&lt;");
      //alert("hello2");
      htmlText = htmlText.replace(/\>/g, "&gt;");
      alert(htmlText);
 }

but it's not working for me and it doesn't even display htmlToEncode value in alert() function. Everytime I click submit button, it display the following error

A potentially dangerous Request.Form value was detected from the client and etc..

Please help to figure out the Problem. I want to encode the HTML content and then store it into the database and then to retrieve it on another page.

var text = document.getElementById("myTextarea").value;

// temporary element has all the native encoding capability you need
var p = document.createElement('p');

// set text and get back HTML
p.appendChild( document.createTextNode(text) );
var html = p.innerHTML;

// add line breaks to display in elements that don't preformat (like textarea does)
html = html.replace(/(\r\n|\n|\r)/g, '<br />' );

// set html and get back text
p.innerHTML = html;
text = p.textContent||p.innerText;

TinyMCE editor already encode tags written by user.

To decode those tags, you can use the following line

    var decodedHtml = $('<div/>').html(yourText).text();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM