Preventing HTML and Script injections in Javascript

后端 未结 7 1791
粉色の甜心
粉色の甜心 2020-12-04 13:12

Assume I have a page with an input box. The user types something into the input box and hits a button. The button triggers a function that picks up the value typed into the

相关标签:
7条回答
  • 2020-12-04 13:29

    A one-liner:

    var encodedMsg = $('<div />').text(message).html();
    

    See it work:

    https://jsfiddle.net/TimothyKanski/wnt8o12j/

    0 讨论(0)
  • 2020-12-04 13:29

    I use this function htmlentities($string):

    $msg = "<script>alert("hello")</script> <h1> Hello World </h1>"
    $msg = htmlentities($msg);
    echo $msg;
    
    0 讨论(0)
  • 2020-12-04 13:32

    Use this,

    function restrict(elem){
      var tf = _(elem);
      var rx = new RegExp;
      if(elem == "email"){
           rx = /[ '"]/gi;
      }else if(elem == "search" || elem == "comment"){
        rx = /[^a-z 0-9.,?]/gi;
      }else{
          rx =  /[^a-z0-9]/gi;
      }
      tf.value = tf.value.replace(rx , "" );
    }
    

    On the backend, for java , Try using StringUtils class or a custom script.

    public static String HTMLEncode(String aTagFragment) {
            final StringBuffer result = new StringBuffer();
            final StringCharacterIterator iterator = new
                    StringCharacterIterator(aTagFragment);
            char character = iterator.current();
            while (character != StringCharacterIterator.DONE )
            {
                if (character == '<')
                    result.append("&lt;");
                else if (character == '>')
                    result.append("&gt;");
                else if (character == '\"')
                    result.append("&quot;");
                else if (character == '\'')
                    result.append("&#039;");
                else if (character == '\\')
                    result.append("&#092;");
                else if (character == '&')
                    result.append("&amp;");
                else {
                //the char is not a special one
                //add it to the result as is
                    result.append(character);
                }
                character = iterator.next();
            }
            return result.toString();
        }
    
    0 讨论(0)
  • 2020-12-04 13:39

    From here

    var string="<script>...</script>";
    string=encodeURIComponent(string); // %3Cscript%3E...%3C/script%3
    
    0 讨论(0)
  • 2020-12-04 13:44

    Try this method to convert a 'string that could potentially contain html code' to 'text format':

    $msg = "<div></div>";
    $safe_msg = htmlspecialchars($msg, ENT_QUOTES);
    echo $safe_msg;
    

    Hope this helps!

    0 讨论(0)
  • 2020-12-04 13:46

    You can encode the < and > to their HTML equivelant.

    html = html.replace(/</g, "&lt;").replace(/>/g, "&gt;");
    

    How to display HTML tags as plain text

    0 讨论(0)
提交回复
热议问题