简体   繁体   中英

How to prevent cross-site scripting using javascript

I want to stop cross-site scripting on a text area. The code below as input data will be vulnerable for the text area:

<script>alert("Hello")</script>

Can anybody help on this to prevent the cross-site scripting with a sample code??

Cross side scripting attack is much bigger than you think and definetly not limited to code you mentioned <script>alert("Hello")</script> .So strictly confined to your question these type of XSS attacks can be prevented by so many php libraries.I will mention a few below.

  • HTML Purifier
  • PHP AntiXSS
  • xssprotect
  • XSS HTML Filter
  • xss_clean.php filter
  • Updating php version

Lets talk about the most prominant method to prevent XSS attack which is Php AntiXss

PHP Anti-XSS Library developing for prevent the XSS(Cross Site Scripting) vulnerabilities on the web applications. PHP Anti-XSS Library automatically detect the encoding of the data that you want filter and if you wish its encoding your data again. Also there are 3 type of filtering option.

3 Types of filtering options here

  1. Blacklist Filtering
  2. Whitelist Filtering
  3. Graylist Filtering

Usage:

Method 1: Setting the encoding of the data

$data = AntiXSS::setEncoding($data, "UTF-8");

Method 2:

Setting the filter for the data

$data = AntiXSS::setFilter($data, "whitelist", "string");

Popular Usage:

Xssescape is a package used to prevent cross site scripting (xss) attack in cross brower.

Usage :

npm install xssescape

app.js

var xs = require('xssescape')
var htmlStr = "<script> alert(document.cookie); </script>";
   xs.strictEscape(htmlStr);

or

var htmlStr = "<script> alert(document.cookie); </script>";
   xs.unescape(htmlStr);

or

var browserURL = "http://example.com/?<script> document.cookie </script>";
   xs.unSafeUrl('/home');   // eg. you can keep what ever you want as a path name.

   // it will reload/refresh the page  with /home after the default url.

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