Cross-site scripting (XSS) attacks occur when malicious scripts are injected into otherwise benign websites. There are three main types of XSS attacks: reflected XSS, stored XSS, and DOM-based XSS. XSS attacks are dangerous because they can access cookies and session tokens, potentially exposing sensitive user information. To prevent XSS, user input should be escaped, validated against a whitelist of allowed characters, and sanitized to remove potentially harmful HTML markup.