The primary defense against cross site scripting attacks in web applications is the use of sanitization, the practice of filtering untrusted inputs. We analyze sanitizer use in a shipping web application with over 400,000 lines of code, one of the largest applications studied to date. Our analysis reveals two novel problems: inconsistent sanitization and inconsistent multiple sanitization. We formally define these problems and propose ScriptGard: a system for preventing such problems automatically matching the correct sanitizer with the correct browser context. While command injection techniques are the subject of intense prior research, none of the previous approaches consider both server and browser context, none of them achieve the same degree of precision, and many other mitigation techniques require major changes to server side code. Our approach, in contrast, can be incrementally retrofitted to legacy systems.We show how to provide an aid to testers during development. Finally we sketch how ScriptGard can be used as a runtime mitigation technique.