title: How to prevent script injection that was pasted to input
body: <p>Recently I've met the XSS problem. I've searched and read a lot of related questions and articles. I've noticed that all answers are focused on how to prevent untrusted data to be passed to server. And in front-end, escape special codes seems the only way to prevent scripts execute. </p>
  
  <p>But what if a user just input a piece of code(such as <code>&lt;script&gt;alert("hi");&lt;/script&gt;</code>) to an input, when will this code executes? And is there a way to prevent it? </p>
  
  <p>I've listened the <code>keydown</code> <code>keyup</code> event, but this can only prevent normal input, it has no effort when user copy and paste directly into input, it'll show my warning message when user input a piece of script, but the script still executed! </p>
  
  <pre><code>$("input").on("keyup", function (e) {
      var value = $(this).val() || "";
      var regex = /&lt;(\/?\w+[^\n&gt;]*\/?)&gt;/ig;
      if(regex.test(value)){
          layer.msg("Invalid characters!");
          $(this).val(value.replace(regex, "&amp;lt;$1&amp;gt;"));
          e.preventDefault();
          return false;
      }
  });
  </code></pre>
  
  <p>I don't understand why the script in an input's value is executed by browser, and when it is executed ? Is there any articles that can explain this mechanism or is related ? Did I have something unnoticed ?
  If there any articles that you think will help, please let me know.
  Thanks.</p>
  
  <p>Thanks for all the answers and comments. Maybe I didn't describe it clear. I've test that <strong>when I copied <code>&lt;script&gt;alert("hi");&lt;/script&gt;</code> and paste it into an input, the browser did prompt an alert window and showed the "hi".</strong></p>
  
  <p>I've also just use <code>$("input").val('&lt;script&gt;alert("hi");&lt;/script&gt;')</code>, it won't prompt alert window, but if I trigger the input's <code>focus</code> and <code>blur</code> event, it will prompt the alert window too.</p>
  
  <p>So, why the codes are executed ?</p>