1. What is the most effective way to prevent Cross-Site Scripting (XSS) attacks?

A) Disabling JavaScript in the browser
B) Using alert() to warn users of attacks
C) Properly escaping and sanitizing user inputs
D) Allowing all HTML and JavaScript input

Answer: C) Properly escaping and sanitizing user inputs
Explanation: Escaping and sanitizing user input prevents malicious scripts from executing. Disabling JavaScript isn’t a feasible defense, and allowing unrestricted input invites XSS.


2. Which security measure is the best way to prevent DOM-based XSS?

A) Always use innerHTML to update the DOM
B) Sanitize and validate input before inserting into the DOM
C) Allow users to execute JavaScript in forms
D) Store user input directly in cookies

Answer: B) Sanitize and validate input before inserting into the DOM
Explanation: Using safe functions like textContent or innerText instead of innerHTML prevents execution of injected scripts in DOM-based XSS.


3. Which HTTP security header helps mitigate reflected and stored XSS attacks?

A) Content-Security-Policy (CSP)
B) X-Frame-Options
C) HTTP Strict Transport Security (HSTS)
D) Cache-Control

Answer: A) Content-Security-Policy (CSP)
Explanation: CSP restricts the sources from which scripts can be executed, reducing the risk of XSS attacks.


4. What is a common mistake when implementing output encoding?

A) Encoding only certain user inputs
B) Using HTML entities to encode special characters
C) Encoding all dynamic data before rendering it in the UI
D) Escaping data properly before sending it to the frontend

Answer: A) Encoding only certain user inputs
Explanation: Output encoding should be applied universally to prevent XSS, not just on selected inputs.


5. Which JavaScript function is the most vulnerable to XSS attacks?

A) document.getElementById().innerText
B) document.querySelector().textContent
C) document.write()
D) console.log()

Answer: C) document.write()
Explanation: document.write() executes scripts directly in the DOM, making it highly vulnerable to XSS.


6. Which is the safest way to handle user-generated HTML in a web application?

A) Use innerHTML to insert user input
B) Use a sanitization library such as DOMPurify
C) Store user-generated HTML directly in the database
D) Allow all user inputs without restrictions

Answer: B) Use a sanitization library such as DOMPurify
Explanation: DOMPurify helps remove malicious scripts while preserving safe HTML elements.


7. Which backend validation approach best prevents stored XSS?

A) Validating input length only
B) Using allowlists and encoding output
C) Allowing all input data to be stored directly
D) Using regex to allow all special characters

Answer: B) Using allowlists and encoding output
Explanation: Allowlists restrict input to expected formats, and encoding prevents script execution.


8. What does the HttpOnly flag on cookies prevent?

A) SQL Injection
B) Cross-Site Scripting (XSS)
C) Cross-Site Request Forgery (CSRF)
D) Brute Force Attacks

Answer: B) Cross-Site Scripting (XSS)
Explanation: HttpOnly prevents JavaScript access to cookies, reducing the risk of XSS stealing session tokens.


9. Which framework feature can help prevent XSS in modern web applications?

A) Client-side rendering without sanitization
B) Server-side output encoding
C) Storing user input as JavaScript variables
D) Using template literals without escaping

Answer: B) Server-side output encoding
Explanation: Frameworks that encode output (e.g., React’s JSX auto-escaping) prevent execution of injected scripts.


10. What is the best practice for preventing XSS in stored user comments?

A) Allow all HTML and JavaScript in comments
B) Sanitize and encode user input before storing and displaying it
C) Execute JavaScript submitted in comments for testing
D) Save raw input and escape it only when retrieving

Answer: B) Sanitize and encode user input before storing and displaying it
Explanation: Storing and displaying unsanitized input allows attackers to inject malicious scripts.


11. Which of the following is an example of an XSS payload?

A) <script>alert('XSS')</script>
B) DROP TABLE users;
C) ../etc/passwd
D) https://example.com

Answer: A) <script>alert('XSS')</script>
Explanation: This JavaScript executes an alert when injected into a vulnerable page.


12. Which Content Security Policy (CSP) directive blocks inline scripts?

A) script-src 'unsafe-inline'
B) script-src 'self'
C) frame-ancestors 'none'
D) default-src *

Answer: B) script-src 'self'
Explanation: This CSP directive restricts script execution to trusted sources.


13. Which function is safe to use for setting text inside an HTML element?

A) element.innerHTML = userInput;
B) element.textContent = userInput;
C) element.outerHTML = userInput;
D) element.insertAdjacentHTML('beforeend', userInput);

Answer: B) element.textContent = userInput;
Explanation: textContent ensures that inserted text is not treated as HTML or JavaScript.


14. Which method is best for securing API responses against XSS?

A) JSON encoding
B) Disabling JavaScript
C) Storing JSON as plaintext
D) Allowing all characters in responses

Answer: A) JSON encoding
Explanation: JSON encoding prevents execution of scripts embedded in API responses.


15. Which JavaScript event is often used in XSS attacks?

A) onclick
B) onload
C) onerror
D) All of the above

Answer: D) All of the above
Explanation: Attackers inject malicious scripts into these event handlers to trigger execution.


16. How does a Web Application Firewall (WAF) help prevent XSS?

A) By filtering out malicious scripts in HTTP requests
B) By blocking all JavaScript execution
C) By preventing all HTML responses
D) By encrypting user input

Answer: A) By filtering out malicious scripts in HTTP requests
Explanation: WAFs detect and block malicious input patterns associated with XSS.


17. Why is XSS particularly dangerous in single-page applications (SPAs)?

A) It affects only static sites
B) SPAs handle sensitive data client-side
C) SPAs don’t use JavaScript
D) XSS is not a concern for SPAs

Answer: B) SPAs handle sensitive data client-side
Explanation: Since SPAs execute JavaScript on the client side, injected scripts can manipulate API requests and responses.


18. Which input sanitization technique is recommended?

A) Blacklisting known bad characters
B) Allowlisting expected input patterns
C) Allowing all special characters
D) Converting input to uppercase

Answer: B) Allowlisting expected input patterns
Explanation: Allowlisting ensures only valid characters are accepted.


19. What is an effective way to prevent XSS in form fields?

A) HTML escaping all user input
B) Allowing JavaScript in all inputs
C) Disabling form validation
D) Accepting raw HTML

Answer: A) HTML escaping all user input
Explanation: Escaping prevents browsers from interpreting user input as HTML or JavaScript.


20. What should developers avoid to prevent XSS?

A) Storing raw user input
B) Using security headers
C) Validating input
D) Escaping output

Answer: A) Storing raw user input
Explanation: Storing raw input without sanitization allows stored XSS attacks.


21. Which of the following is NOT an effective XSS prevention measure?

A) Enabling HTTP-only cookies
B) Encoding user-generated content
C) Allowing all user inputs to contain JavaScript
D) Implementing Content Security Policy (CSP)

Answer: C) Allowing all user inputs to contain JavaScript
Explanation: Allowing JavaScript from users enables XSS attacks. Proper input validation and escaping are required.


22. What does setting the Secure flag on cookies do?

A) Encrypts the cookie value
B) Prevents JavaScript from accessing the cookie
C) Ensures cookies are only sent over HTTPS
D) Makes cookies expire instantly

Answer: C) Ensures cookies are only sent over HTTPS
Explanation: The Secure flag ensures cookies are transmitted only over encrypted HTTPS connections, preventing attackers from intercepting them.


23. Which of the following describes a stored XSS attack?

A) Malicious script is stored in a database and executed later
B) The attacker redirects users using phishing links
C) The victim manually executes JavaScript from a URL
D) The attacker modifies HTTP headers to inject scripts

Answer: A) Malicious script is stored in a database and executed later
Explanation: Stored XSS occurs when malicious code is saved in a database and executed when a user views the affected page.


24. Which browser feature prevents reflected XSS attacks by blocking scripts in URLs?

A) Same-Origin Policy (SOP)
B) X-XSS-Protection
C) CSP Level 3
D) CORS

Answer: B) X-XSS-Protection
Explanation: The X-XSS-Protection header blocks reflected XSS attacks by detecting script execution in URLs.


25. How can developers prevent XSS in user-uploaded file names?

A) Store filenames in plaintext
B) Sanitize and encode the filename before displaying it
C) Allow users to choose any filename
D) Rename files to the original user input

Answer: B) Sanitize and encode the filename before displaying it
Explanation: If filenames are not sanitized, an attacker could upload a file with a malicious name that gets executed when displayed.


26. What is the purpose of sandbox attribute in iframes?

A) Prevents external scripts from executing inside the iframe
B) Disables JavaScript execution globally
C) Prevents SQL Injection
D) Enables Flash content

Answer: A) Prevents external scripts from executing inside the iframe
Explanation: The sandbox attribute in iframes restricts JavaScript execution and interaction with the parent page, mitigating XSS.


27. Which type of input validation is most secure for preventing XSS?

A) Client-side validation only
B) Server-side validation only
C) Both client-side and server-side validation
D) Allowing unrestricted input

Answer: C) Both client-side and server-side validation
Explanation: Server-side validation ensures security, while client-side validation improves user experience but should not be relied upon solely.


28. How does a Web Application Firewall (WAF) help prevent XSS?

A) It encrypts all JavaScript on a page
B) It blocks malicious patterns in HTTP requests
C) It completely disables JavaScript execution
D) It replaces user input with hardcoded values

Answer: B) It blocks malicious patterns in HTTP requests
Explanation: A WAF inspects requests and filters out those that match known XSS payloads.


29. Which of the following CSP directives helps prevent XSS by restricting script execution?

A) frame-src 'self'
B) script-src 'self'
C) img-src 'none'
D) default-src *

Answer: B) script-src 'self'
Explanation: This directive ensures that JavaScript is only executed from trusted sources, reducing XSS risks.


30. What is the best approach to handling untrusted user input in backend applications?

A) Execute all input data as is
B) Encode and sanitize input before storing and displaying it
C) Store raw input without filtering
D) Only use client-side validation

Answer: B) Encode and sanitize input before storing and displaying it
Explanation: Sanitization prevents malicious code from executing, while encoding ensures safe display of user input.


31. Why is using JavaScript’s eval() function dangerous?

A) It reduces website performance
B) It allows execution of dynamically injected code
C) It disables HTML encoding
D) It restricts API calls

Answer: B) It allows execution of dynamically injected code
Explanation: eval() can execute untrusted user input, making it a common target for XSS attacks.


32. What does the X-Content-Type-Options: nosniff header do?

A) Blocks JavaScript execution in forms
B) Prevents MIME-type sniffing attacks
C) Encrypts JavaScript requests
D) Allows inline scripts to execute

Answer: B) Prevents MIME-type sniffing attacks
Explanation: This header ensures browsers respect declared content types, reducing XSS and injection risks.


33. How can JavaScript template engines prevent XSS?

A) By allowing raw HTML inside templates
B) By encoding all variables before rendering
C) By using innerHTML to insert templates
D) By executing all scripts inside a sandbox

Answer: B) By encoding all variables before rendering
Explanation: Encoding variables prevents them from being interpreted as executable scripts.


34. How does HTTP Content Security Policy (CSP) help prevent XSS?

A) Blocks all JavaScript on the page
B) Allows JavaScript execution from specific sources only
C) Converts user input into safe HTML
D) Disables AJAX requests

Answer: B) Allows JavaScript execution from specific sources only
Explanation: CSP restricts JavaScript execution to trusted origins, mitigating script injection.


35. Why is it important to escape data in SQL queries to prevent XSS?

A) SQL queries can contain JavaScript
B) Prevents execution of malicious HTML or JavaScript
C) Prevents stored XSS attacks via database input
D) Improves query performance

Answer: C) Prevents stored XSS attacks via database input
Explanation: Escaping data ensures that stored user input does not get executed as a script when retrieved.


36. What is one major downside of blacklisting certain characters to prevent XSS?

A) It blocks all special characters
B) Attackers can bypass it with different encoding methods
C) It removes all user input
D) It disables HTML parsing

Answer: B) Attackers can bypass it with different encoding methods
Explanation: Blacklists can be circumvented using encoded or obfuscated payloads.


37. Which of these frontend techniques reduces the risk of XSS?

A) Using innerHTML for updating DOM
B) Using textContent instead of innerHTML
C) Allowing all HTML inputs
D) Using JavaScript eval()

Answer: B) Using textContent instead of innerHTML
Explanation: textContent prevents HTML parsing, reducing the risk of XSS.


38. What is a security risk of using unescaped URL parameters in JavaScript?

A) It allows SQL Injection
B) It can execute attacker-controlled scripts
C) It disables JavaScript execution
D) It slows down page loading

Answer: B) It can execute attacker-controlled scripts
Explanation: Attackers can inject JavaScript into URL parameters if they are not properly sanitized.


39. Why is XSS dangerous in admin dashboards?

A) Attackers can steal user passwords
B) Admins have higher privileges, making XSS more impactful
C) It only affects frontend UI
D) It has no real security impact

Answer: B) Admins have higher privileges, making XSS more impactful
Explanation: An XSS attack on an admin account can lead to full system compromise.


40. Which security measure should be applied to JSON API responses to prevent XSS?

A) Escape output using HTML entities
B) Use JavaScript eval() to parse responses
C) Allow inline JavaScript execution
D) Encode responses before displaying them

Answer: D) Encode responses before displaying them
Explanation: Encoding API responses ensures that any included user-generated content is displayed safely.


41. Why is client-side input validation alone insufficient for preventing XSS?

A) It is too slow to process input
B) Attackers can bypass it by modifying requests
C) It requires additional browser plugins
D) It blocks all types of user input

Answer: B) Attackers can bypass it by modifying requests
Explanation: Client-side validation can be disabled or bypassed, so backend validation is also necessary.


42. What role does Referrer-Policy play in XSS prevention?

A) Blocks all JavaScript execution
B) Prevents browsers from sending sensitive referrer information
C) Disables user input fields
D) Encrypts JavaScript in web pages

Answer: B) Prevents browsers from sending sensitive referrer information
Explanation: Referrer-Policy helps reduce the risk of leaking sensitive information to untrusted sites.


43. What is a major risk of allowing user-generated JavaScript in web applications?

A) Users can customize their experience
B) Users can execute scripts that impact other users
C) It improves performance
D) It makes web pages load faster

Answer: B) Users can execute scripts that impact other users
Explanation: Allowing users to run JavaScript can lead to XSS attacks where scripts execute in other users’ browsers.


44. How does the noscript HTML tag help mitigate XSS risks?

A) Prevents JavaScript execution
B) Displays alternative content when JavaScript is disabled
C) Blocks XSS attacks entirely
D) Encrypts user input

Answer: B) Displays alternative content when JavaScript is disabled
Explanation: The noscript tag ensures that important content is available if JavaScript is disabled, but it does not prevent XSS directly.


45. Which method prevents XSS in React applications?

A) Using dangerouslySetInnerHTML
B) Directly inserting user input into the DOM
C) Encoding user input using JSX auto-escaping
D) Allowing all script execution

Answer: C) Encoding user input using JSX auto-escaping
Explanation: React automatically escapes user input, preventing XSS by default.


46. How does Cross-Origin Resource Sharing (CORS) relate to XSS attacks?

A) It blocks all JavaScript execution
B) It prevents malicious websites from making unauthorized requests
C) It encrypts API responses
D) It allows JavaScript to be executed globally

Answer: B) It prevents malicious websites from making unauthorized requests
Explanation: CORS restricts how web pages can request resources from other domains, reducing certain XSS risks.


47. What is a secure way to handle user input in a web application?

A) Allow all HTML elements
B) Validate, sanitize, and encode input
C) Disable JavaScript entirely
D) Store all input in a raw format

Answer: B) Validate, sanitize, and encode input
Explanation: This combination ensures that user input cannot be used to inject malicious scripts.


48. Which JavaScript function is considered insecure due to XSS risks?

A) console.log()
B) setTimeout(userInput, 1000)
C) document.querySelector()
D) Math.random()

Answer: B) setTimeout(userInput, 1000)
Explanation: If setTimeout() is used with untrusted user input, it can execute malicious scripts.


49. Why should innerHTML be avoided when displaying user input?

A) It is slow
B) It executes embedded JavaScript
C) It requires additional security plugins
D) It makes web pages look bad

Answer: B) It executes embedded JavaScript
Explanation: innerHTML interprets HTML content, allowing malicious scripts to execute if input is not sanitized.


50. How can developers test for XSS vulnerabilities in web applications?

A) Running automated security scanners
B) Manually injecting scripts into input fields
C) Reviewing code for unsafe functions
D) All of the above

Answer: D) All of the above
Explanation: A combination of manual testing, automated tools, and code review is necessary for effective XSS detection.


51. What is a common indicator of a reflected XSS attack?

A) Malicious script appears in the URL
B) Database corruption
C) Server crashes
D) Encrypted passwords are exposed

Answer: A) Malicious script appears in the URL
Explanation: In reflected XSS, the payload is often included in the URL and executed when the page loads.


52. How does X-Frame-Options help in XSS mitigation?

A) Blocks JavaScript execution
B) Prevents clickjacking attacks
C) Encrypts HTTP responses
D) Disables third-party scripts

Answer: B) Prevents clickjacking attacks
Explanation: X-Frame-Options prevents a website from being embedded in an iframe, reducing risks associated with UI redress attacks.


53. What is a key difference between CSP and X-XSS-Protection?

A) CSP prevents all XSS, while X-XSS-Protection only mitigates reflected XSS
B) CSP is used for encryption
C) X-XSS-Protection blocks all JavaScript
D) CSP only works on HTTPS sites

Answer: A) CSP prevents all XSS, while X-XSS-Protection only mitigates reflected XSS
Explanation: CSP restricts script execution sources, whereas X-XSS-Protection detects reflected XSS attempts.


54. Why should web applications avoid using user-controlled JavaScript event handlers?

A) They improve performance
B) Attackers can use them to inject malicious scripts
C) They make the website load faster
D) They disable JavaScript

Answer: B) Attackers can use them to inject malicious scripts
Explanation: Allowing user-controlled event handlers opens up vulnerabilities to XSS.


55. What is the best practice for logging user input?

A) Store raw input without filtering
B) Encode special characters before storing logs
C) Log all inputs in plaintext
D) Disable all logging

Answer: B) Encode special characters before storing logs
Explanation: Encoding prevents log-based attacks where injected scripts might be executed in log viewing tools.


56. What is one effective way to prevent stored XSS attacks?

A) Encrypt all input data
B) Sanitize and validate user input before storing
C) Store all data in plaintext
D) Allow all user input as-is

Answer: B) Sanitize and validate user input before storing
Explanation: Sanitization ensures that stored inputs do not contain executable scripts.


57. Which HTTP method is most commonly exploited in reflected XSS attacks?

A) GET
B) PUT
C) DELETE
D) HEAD

Answer: A) GET
Explanation: Reflected XSS often involves injecting malicious scripts via URL parameters, which are sent using GET requests.


58. What does self mean in a CSP policy?

A) Blocks all scripts
B) Allows scripts from the same origin
C) Enables JavaScript execution
D) Restricts inline styles

Answer: B) Allows scripts from the same origin
Explanation: self permits scripts to run only if they originate from the same domain.


59. Which of the following increases the risk of XSS?

A) Escaping HTML entities
B) Using JavaScript template literals with user input
C) Implementing CSP
D) Using allowlists for inputs

Answer: B) Using JavaScript template literals with user input
Explanation: Template literals (${userInput}) can allow direct execution of injected JavaScript.


60. How can regular expressions help in preventing XSS?

A) By blocking all special characters
B) By defining an allowlist for expected input formats
C) By automatically escaping scripts
D) By disabling JavaScript execution

Answer: B) By defining an allowlist for expected input formats
Explanation: Allowlisting ensures only valid input patterns are accepted, reducing the risk of malicious injections.


61. Why is escaping output important in preventing XSS?

A) It prevents all forms of hacking
B) It ensures user input is executed as JavaScript
C) It ensures user input is treated as data, not code
D) It allows users to modify backend scripts

Answer: C) It ensures user input is treated as data, not code
Explanation: Escaping ensures that user-supplied input is not executed as code but rather displayed safely as text.


62. What type of input should always be validated to prevent XSS?

A) Only numeric input
B) Only input fields containing special characters
C) Any user-supplied input
D) Only input with JavaScript keywords

Answer: C) Any user-supplied input
Explanation: All user input should be validated and sanitized to prevent malicious code execution.


63. What is the safest way to insert user-generated HTML content into a webpage?

A) Use innerHTML to directly insert user input
B) Use a sanitization library such as DOMPurify
C) Store and render input as JavaScript variables
D) Allow unrestricted HTML from users

Answer: B) Use a sanitization library such as DOMPurify
Explanation: DOMPurify removes malicious scripts while preserving safe HTML elements.


64. How does an attacker exploit a stored XSS vulnerability?

A) By injecting a script that gets stored in a database and executed later
B) By modifying HTTP headers to send requests
C) By performing a brute-force attack on login pages
D) By bypassing SSL/TLS encryption

Answer: A) By injecting a script that gets stored in a database and executed later
Explanation: Stored XSS occurs when a malicious script is stored in the database and executed when retrieved.


65. What does trusted types in CSP help prevent?

A) SQL Injection
B) Cross-Site Request Forgery (CSRF)
C) DOM-based XSS
D) Insecure Direct Object References (IDOR)

Answer: C) DOM-based XSS
Explanation: Trusted Types in CSP enforces strict rules on how JavaScript handles dynamic data, reducing the risk of DOM-based XSS.


66. Why should JavaScript’s document.cookie access be restricted?

A) To prevent slow page loads
B) To prevent JavaScript from stealing session cookies
C) To block SQL Injection
D) To improve SEO rankings

Answer: B) To prevent JavaScript from stealing session cookies
Explanation: If an attacker can access document.cookie, they can steal session tokens via XSS.


67. What is a common sign of a reflected XSS attack?

A) A script in the URL gets executed
B) Database tables get deleted
C) Server CPU usage spikes
D) The website loads significantly slower

Answer: A) A script in the URL gets executed
Explanation: Reflected XSS usually involves injecting a script into a URL parameter, which gets executed when clicked.


68. How does setting X-Frame-Options: DENY in HTTP headers help security?

A) It blocks XSS entirely
B) It prevents the site from being embedded in an iframe
C) It encrypts all JavaScript requests
D) It forces browsers to disable cookies

Answer: B) It prevents the site from being embedded in an iframe
Explanation: X-Frame-Options: DENY prevents clickjacking attacks by disallowing the site from being loaded in an iframe.


69. How can JavaScript template literals contribute to XSS vulnerabilities?

A) They execute JavaScript code if input is not sanitized
B) They improve script readability
C) They automatically escape special characters
D) They only work on modern browsers

Answer: A) They execute JavaScript code if input is not sanitized
Explanation: If user input is embedded inside template literals, it can execute JavaScript unless properly escaped.


70. What is the primary purpose of encodeURIComponent() in JavaScript?

A) To encode special characters in URLs
B) To prevent SQL Injection
C) To disable JavaScript execution
D) To hash user passwords

Answer: A) To encode special characters in URLs
Explanation: encodeURIComponent() ensures that special characters are safely encoded, preventing injection attacks.


71. Why should inline JavaScript be avoided in web applications?

A) It makes the code harder to debug
B) It prevents users from interacting with the page
C) It increases the risk of XSS attacks
D) It slows down web servers

Answer: C) It increases the risk of XSS attacks
Explanation: Inline JavaScript is more vulnerable to injection attacks and can be blocked using CSP.


72. What does sandbox in an iframe do?

A) Allows full script execution inside the iframe
B) Restricts script execution and access to parent pages
C) Disables all web content inside the iframe
D) Makes the iframe load faster

Answer: B) Restricts script execution and access to parent pages
Explanation: The sandbox attribute limits an iframe’s capabilities, reducing the risk of injected scripts affecting the parent page.


73. What is the primary defense against DOM-based XSS?

A) Validating input on the client-side only
B) Using innerHTML for DOM updates
C) Encoding user input before inserting it into the DOM
D) Storing user input in local storage

Answer: C) Encoding user input before inserting it into the DOM
Explanation: Encoding ensures user input is treated as text rather than executable JavaScript.


74. Why is the textContent property safer than innerHTML?

A) It prevents all types of XSS
B) It disables JavaScript execution globally
C) It treats input as text instead of executing HTML
D) It encrypts JavaScript

Answer: C) It treats input as text instead of executing HTML
Explanation: textContent prevents XSS by rendering input as text rather than executing it.


75. What does the same-origin policy protect against?

A) SQL Injection
B) Cross-Origin Script Execution
C) Server Misconfigurations
D) Brute Force Attacks

Answer: B) Cross-Origin Script Execution
Explanation: The same-origin policy prevents a script on one domain from accessing resources on another domain.


76. Why should JavaScript libraries be updated regularly?

A) To improve website speed
B) To patch known security vulnerabilities
C) To reduce network bandwidth
D) To allow more inline scripts

Answer: B) To patch known security vulnerabilities
Explanation: Outdated libraries can contain security flaws that attackers exploit.


77. How does a Web Application Firewall (WAF) detect XSS attacks?

A) By blocking all JavaScript requests
B) By filtering malicious patterns in HTTP requests
C) By disabling HTML parsing
D) By storing all scripts in a sandbox

Answer: B) By filtering malicious patterns in HTTP requests
Explanation: WAFs detect and block known XSS payloads based on attack patterns.


78. What is the main security risk of allowing JavaScript in user-generated content?

A) It slows down page loading
B) It enables XSS attacks that execute scripts in other users’ browsers
C) It requires extra CPU power
D) It prevents SQL Injection

Answer: B) It enables XSS attacks that execute scripts in other users’ browsers
Explanation: Attackers can insert malicious JavaScript that runs in the context of other users’ browsers.


79. What does script-src 'none' do in a CSP policy?

A) Blocks all JavaScript execution
B) Allows all JavaScript execution
C) Disables external scripts only
D) Enables only inline scripts

Answer: A) Blocks all JavaScript execution
Explanation: script-src 'none' prevents any scripts from running on the page.


80. Why is JSON.stringify() useful for preventing XSS?

A) It prevents SQL Injection
B) It converts objects into safe string format
C) It executes JavaScript dynamically
D) It removes all special characters

Answer: B) It converts objects into safe string format
Explanation: JSON.stringify() ensures that JavaScript objects are converted into text, preventing unintended execution.


81. Which JavaScript method should be avoided to prevent XSS when inserting user input into the DOM?

A) textContent
B) createElement()
C) innerHTML
D) setAttribute()

Answer: C) innerHTML
Explanation: innerHTML interprets input as HTML, which can execute embedded scripts if input is not sanitized.


82. What is a potential consequence of an XSS vulnerability in an admin panel?

A) Unauthorized access to user data
B) Unauthorized deletion of server files
C) Execution of malicious scripts that affect other users
D) All of the above

Answer: D) All of the above
Explanation: XSS in an admin panel could lead to a range of malicious actions, including stealing sensitive data and affecting other users.


83. What is the primary function of a Content Security Policy (CSP)?

A) To block all user-generated input
B) To define trusted content sources for scripts and styles
C) To encrypt all JavaScript on the page
D) To disable all JavaScript execution

Answer: B) To define trusted content sources for scripts and styles
Explanation: CSP is used to control the sources from which content (scripts, styles, images) can be loaded, reducing the risk of XSS.


84. What type of attack does the X-XSS-Protection HTTP header primarily protect against?

A) Stored XSS
B) Reflected XSS
C) CSRF
D) SQL Injection

Answer: B) Reflected XSS
Explanation: X-XSS-Protection is designed to block reflected XSS attacks by filtering out malicious scripts.


85. How does the SameSite cookie attribute help with XSS prevention?

A) It prevents cookies from being sent in cross-site requests
B) It encrypts cookies
C) It validates the cookie’s content
D) It allows cookies to be shared across all websites

Answer: A) It prevents cookies from being sent in cross-site requests
Explanation: The SameSite attribute prevents cookies from being sent in cross-origin requests, mitigating the risk of XSS attacks that rely on stolen cookies.


86. What is the best method for handling error messages to reduce XSS vulnerabilities?

A) Display all errors directly to users
B) Log all errors but show generic messages to users
C) Allow detailed stack traces to be visible
D) Disable error logging

Answer: B) Log all errors but show generic messages to users
Explanation: Showing detailed error messages may expose potential attack vectors. Instead, show general error messages to the user and log detailed errors for analysis.


87. Which JavaScript function should you avoid to mitigate XSS in untrusted data?

A) String.prototype.replace()
B) window.location.href
C) eval()
D) JSON.parse()

Answer: C) eval()
Explanation: eval() executes arbitrary JavaScript code, making it a common target for XSS attacks when it processes untrusted input.


88. What is one effective way to prevent DOM-based XSS when using JavaScript?

A) Always use document.write() for dynamic content
B) Use methods like textContent and setAttribute() instead of innerHTML
C) Use innerHTML with no validation
D) Enable inline JavaScript

Answer: B) Use methods like textContent and setAttribute() instead of innerHTML
Explanation: These methods avoid the execution of embedded scripts, reducing the risk of DOM-based XSS.


89. How does the nonce attribute in CSP help mitigate XSS?

A) It allows inline scripts to execute from trusted sources
B) It prevents JavaScript from loading on the page
C) It disables cookies for scripts
D) It automatically encrypts all script tags

Answer: A) It allows inline scripts to execute from trusted sources
Explanation: The nonce attribute ensures that only inline scripts with the correct nonce value can execute, blocking malicious ones.


90. What should a developer do before allowing user input in a script tag?

A) Use innerHTML to insert it directly
B) Sanitize and validate the input
C) Store it in a database without validation
D) Allow any input without restrictions

Answer: B) Sanitize and validate the input
Explanation: Input should be sanitized and validated to prevent malicious code from being executed.


91. What is a common way to bypass XSS defenses?

A) Using complex encoding techniques
B) Using only numbers and letters in input
C) Escaping all characters
D) Removing JavaScript from input

Answer: A) Using complex encoding techniques
Explanation: Attackers may encode payloads in ways that bypass simple input sanitization, such as encoding characters into different formats.


92. What does the Content-Type header control in terms of XSS mitigation?

A) It allows or blocks specific URLs
B) It defines which script types are allowed
C) It specifies the media type of the response data
D) It enables JavaScript execution

Answer: C) It specifies the media type of the response data
Explanation: Correctly setting the Content-Type header ensures that the browser treats data as the correct media type, preventing it from being interpreted as executable code.


93. How does Strict-Transport-Security (HSTS) relate to XSS?

A) It forces secure communication over HTTPS
B) It blocks malicious URLs
C) It encrypts all JavaScript on the page
D) It limits the use of cookies

Answer: A) It forces secure communication over HTTPS
Explanation: HSTS ensures that the website uses HTTPS, preventing downgrade attacks and making it harder for attackers to exploit XSS over unencrypted channels.


94. What is the benefit of using a secure session management mechanism in preventing XSS?

A) It ensures session tokens cannot be easily stolen by attackers
B) It prevents user login failures
C) It hides the source code from attackers
D) It disables all cookies

Answer: A) It ensures session tokens cannot be easily stolen by attackers
Explanation: Secure session management practices help prevent session hijacking, which can be exploited in XSS attacks.


95. How does the X-Permitted-Cross-Domain-Policies header help with XSS prevention?

A) It prevents cross-origin resource sharing
B) It restricts Flash and other plug-ins from executing malicious content
C) It blocks all JavaScript execution
D) It encrypts HTTP headers

Answer: B) It restricts Flash and other plug-ins from executing malicious content
Explanation: This header blocks certain plug-ins (like Flash) from interacting with the domain, reducing the attack surface for XSS.


96. What is the purpose of input filtering in XSS prevention?

A) To allow all user input
B) To block characters that are commonly used in XSS attacks
C) To convert all input into uppercase
D) To encrypt user input

Answer: B) To block characters that are commonly used in XSS attacks
Explanation: Filtering input prevents dangerous characters, like < and >, from being used to inject scripts.


97. What should be done when dynamic data is inserted into a URL in a web application?

A) Directly insert it into the URL without validation
B) Encode the data before using it in the URL
C) Allow any data to be used in the URL
D) Ignore dynamic data in URLs

Answer: B) Encode the data before using it in the URL
Explanation: URL encoding ensures that special characters in dynamic data are safely transmitted without executing scripts.


98. What is the best approach to protect against XSS when dealing with JSON data?

A) Directly insert JSON into HTML
B) Always validate and escape dynamic content from JSON
C) Use JSON.parse() without sanitizing the input
D) Allow all JSON responses without filtering

Answer: B) Always validate and escape dynamic content from JSON
Explanation: When dealing with JSON data, proper validation and escaping of dynamic content prevent injection and XSS attacks.


99. What is a major difference between stored and reflected XSS?

A) Stored XSS occurs when scripts are permanently stored on the server, while reflected XSS is executed immediately via URL parameters.
B) Reflected XSS involves direct database manipulation, while stored XSS only affects the client side.
C) Stored XSS always targets admins, while reflected XSS only targets regular users.
D) Reflected XSS is only possible with JavaScript enabled, while stored XSS works regardless.

Answer: A) Stored XSS occurs when scripts are permanently stored on the server, while reflected XSS is executed immediately via URL parameters.
Explanation: Stored XSS is persistent and stored on the server, while reflected XSS is delivered via HTTP request parameters and executed immediately.


100. How can developers reduce the impact of an XSS attack if it occurs?

A) By ensuring proper access control and session management
B) By hiding error messages from users
C) By using anti-virus software on the server
D) By validating input only on the client side

Answer: A) By ensuring proper access control and session management
Explanation: Proper session management and access control can help mitigate the impact of XSS attacks by limiting attacker access to sensitive parts of the application.


101. What is the primary danger of XSS in a financial web application?

A) It can slow down the website
B) It can lead to unauthorized financial transactions
C) It can disable JavaScript execution
D) It makes the application load faster

Answer: B) It can lead to unauthorized financial transactions
Explanation: XSS can allow attackers to steal session tokens or manipulate financial transactions on behalf of a user.


102. What is a major difference between DOM-based XSS and stored XSS?

A) DOM-based XSS is executed in the user’s browser, while stored XSS is executed on the server
B) Stored XSS does not execute JavaScript
C) DOM-based XSS occurs on the server side
D) Stored XSS does not affect web applications

Answer: A) DOM-based XSS is executed in the user’s browser, while stored XSS is executed on the server
Explanation: DOM-based XSS occurs when client-side scripts manipulate the DOM with untrusted input, while stored XSS is stored in a database and executed later.


103. Which JavaScript function can be exploited for XSS if used improperly?

A) parseInt()
B) setTimeout()
C) document.write()
D) JSON.stringify()

Answer: C) document.write()
Explanation: document.write() can be exploited if user-controlled data is inserted without proper sanitization.


104. How can an attacker execute a persistent XSS attack on a forum?

A) By modifying the HTTP headers
B) By injecting malicious JavaScript in a comment that is stored and displayed later
C) By using a strong password
D) By changing the browser’s cache settings

Answer: B) By injecting malicious JavaScript in a comment that is stored and displayed later
Explanation: Stored XSS occurs when malicious JavaScript is stored in a database and executed when users view the affected content.


105. What is the purpose of the X-Content-Type-Options: nosniff header in XSS prevention?

A) It prevents browsers from MIME-type sniffing
B) It blocks JavaScript execution
C) It disables cookies
D) It encrypts HTTP requests

Answer: A) It prevents browsers from MIME-type sniffing
Explanation: MIME-type sniffing can allow browsers to misinterpret content types, leading to security vulnerabilities.


106. What should a developer do before rendering JSON data inside an HTML document?

A) Use innerHTML to display the data directly
B) Escape and encode the JSON data properly
C) Allow all JSON inputs without filtering
D) Ignore validation for API responses

Answer: B) Escape and encode the JSON data properly
Explanation: Escaping and encoding ensure that JSON data is treated as text, preventing unintended script execution.


107. Which technique should be avoided to prevent JavaScript injection in URLs?

A) Encoding URL parameters
B) Using innerHTML with user input
C) Using encodeURIComponent()
D) Escaping output in templates

Answer: B) Using innerHTML with user input
Explanation: innerHTML can execute JavaScript if user input is not sanitized properly.


108. How does setting the Secure flag on cookies help prevent XSS attacks?

A) It prevents cookies from being stolen over insecure HTTP connections
B) It makes cookies expire faster
C) It allows all scripts to access cookies
D) It blocks JavaScript execution

Answer: A) It prevents cookies from being stolen over insecure HTTP connections
Explanation: The Secure flag ensures cookies are only transmitted over HTTPS, reducing the risk of interception.


109. What is the impact of allowing user-controlled JavaScript event handlers in web applications?

A) It improves user experience
B) It allows attackers to execute malicious scripts
C) It increases website performance
D) It helps block XSS attacks

Answer: B) It allows attackers to execute malicious scripts
Explanation: Event handlers (onclick, onmouseover) can be used to execute scripts if not properly sanitized.


110. How does CSP help mitigate XSS in web applications?

A) By blocking all external scripts
B) By restricting JavaScript execution to trusted sources
C) By disabling JavaScript in the browser
D) By allowing all scripts to execute freely

Answer: B) By restricting JavaScript execution to trusted sources
Explanation: CSP restricts the sources from which scripts can be executed, reducing the risk of XSS.


111. Which of the following is a valid XSS payload?

A) SELECT * FROM users;
B) <script>alert('XSS')</script>
C) ../../../etc/passwd
D) https://example.com

Answer: B) <script>alert('XSS')</script>
Explanation: This script will execute an alert when injected into a vulnerable web application.


112. What role does input validation play in preventing XSS?

A) It helps filter out malicious user input
B) It speeds up website performance
C) It disables JavaScript execution
D) It improves search engine ranking

Answer: A) It helps filter out malicious user input
Explanation: Validating input ensures that only expected data is processed, preventing XSS attacks.


113. What does the HttpOnly flag on cookies prevent?

A) SQL Injection
B) JavaScript access to cookies
C) Reflected XSS
D) Faster session expiration

Answer: B) JavaScript access to cookies
Explanation: HttpOnly prevents JavaScript from accessing cookies, mitigating the risk of XSS-based session hijacking.


114. Why is CSP considered an effective XSS mitigation technique?

A) It prevents all user input
B) It blocks inline scripts and untrusted sources
C) It allows unrestricted JavaScript execution
D) It encrypts user data

Answer: B) It blocks inline scripts and untrusted sources
Explanation: CSP helps prevent XSS by enforcing strict script execution policies.


115. What is an effective way to prevent XSS in HTML attributes?

A) Use single quotes (') around all attributes
B) Encode and escape attribute values properly
C) Use innerHTML to insert attributes dynamically
D) Allow all special characters in attributes

Answer: B) Encode and escape attribute values properly
Explanation: Encoding ensures that user input in attributes is not treated as executable JavaScript.


116. Why should user-generated content be sanitized before rendering?

A) To improve page load speed
B) To prevent XSS attacks
C) To disable JavaScript on the website
D) To make the page look better

Answer: B) To prevent XSS attacks
Explanation: Sanitizing user-generated content ensures that malicious scripts cannot be executed.


117. What is a risk of allowing users to input <script> tags in a web form?

A) It improves website performance
B) It enables XSS attacks
C) It allows users to debug their input
D) It makes the form load faster

Answer: B) It enables XSS attacks
Explanation: Allowing script tags in user input makes the application vulnerable to XSS.


118. How can developers prevent JavaScript execution from URL parameters?

A) Use encodeURIComponent() when processing URLs
B) Allow raw URL parameters without validation
C) Use innerHTML to insert user-provided URLs
D) Remove all URL parameters

Answer: A) Use encodeURIComponent() when processing URLs
Explanation: Encoding URL parameters prevents scripts from executing when inserted into the DOM.


119. How does a Web Application Firewall (WAF) help protect against XSS?

A) It detects and blocks known malicious payloads in requests
B) It encrypts JavaScript
C) It disables all HTML content
D) It removes user input

Answer: A) It detects and blocks known malicious payloads in requests
Explanation: WAFs analyze incoming traffic and filter out known attack patterns.


120. What should be done to prevent XSS in dynamically generated HTML content?

A) Allow unrestricted HTML input
B) Escape and sanitize all dynamic data
C) Use inline scripts without validation
D) Disable JavaScript

Answer: B) Escape and sanitize all dynamic data
Explanation: Escaping and sanitizing prevent user input from being executed as JavaScript.


121. Which of the following is the best method to prevent XSS when handling HTML input from users?

A) Allow users to insert any HTML they want
B) Use a library like DOMPurify to sanitize input
C) Convert all input to uppercase
D) Store input in plain text without processing

Answer: B) Use a library like DOMPurify to sanitize input
Explanation: Libraries like DOMPurify help sanitize user input, removing harmful scripts while preserving safe HTML elements.


122. Why is it dangerous to store user-generated content without validation?

A) It may break the application layout
B) It may allow execution of malicious scripts when displayed
C) It slows down website performance
D) It prevents users from submitting their input

Answer: B) It may allow execution of malicious scripts when displayed
Explanation: Storing user input without validation increases the risk of stored XSS, where the script executes when viewed later.


123. What is one major security risk of allowing user-generated inline styles?

A) It allows attackers to execute arbitrary JavaScript via expression()
B) It improves the page’s design
C) It increases load time for the page
D) It prevents SQL Injection

Answer: A) It allows attackers to execute arbitrary JavaScript via expression()
Explanation: Some browsers allowed JavaScript execution inside CSS via expression(), making inline styles a potential attack vector.


124. Which of the following can be a source of DOM-based XSS?

A) Using location.href without sanitization
B) Using textContent to display user input
C) Storing input in a backend database
D) Enabling CSP with strict policies

Answer: A) Using location.href without sanitization
Explanation: DOM-based XSS occurs when JavaScript dynamically updates the DOM using untrusted data (e.g., location.href) without proper encoding.


125. What is a key feature of CSP that makes it effective against XSS?

A) It disables JavaScript entirely
B) It restricts JavaScript execution to trusted sources
C) It only allows inline scripts
D) It prevents all HTTP requests

Answer: B) It restricts JavaScript execution to trusted sources
Explanation: CSP helps mitigate XSS by blocking scripts that originate from untrusted sources.


126. What should be done when rendering user-generated content in a React application?

A) Use dangerouslySetInnerHTML
B) Convert input to lowercase
C) Use JSX, which automatically escapes input
D) Allow users to include JavaScript in their comments

Answer: C) Use JSX, which automatically escapes input
Explanation: React’s JSX automatically escapes user input, preventing XSS unless dangerouslySetInnerHTML is used unsafely.


127. How does XSS differ from SQL Injection?

A) XSS targets the client-side, while SQL Injection targets the database
B) SQL Injection is more dangerous than XSS
C) XSS cannot steal user session cookies
D) XSS is only possible in JavaScript applications

Answer: A) XSS targets the client-side, while SQL Injection targets the database
Explanation: XSS exploits vulnerabilities in frontend code, whereas SQL Injection manipulates backend database queries.


128. Why should JavaScript template literals (${userInput}) be handled with caution?

A) They automatically sanitize input
B) They can execute JavaScript if user input is not escaped
C) They improve performance
D) They prevent SQL Injection

Answer: B) They can execute JavaScript if user input is not escaped
Explanation: Template literals allow JavaScript execution, so they should be properly escaped when handling user input.


129. Which of the following headers can be used to prevent MIME-type confusion, reducing XSS risks?

A) X-Permitted-Cross-Domain-Policies
B) X-Content-Type-Options: nosniff
C) Content-Encoding: gzip
D) X-XSS-Protection

Answer: B) X-Content-Type-Options: nosniff
Explanation: This header prevents browsers from interpreting non-JavaScript files as scripts, reducing the risk of unintended script execution.


130. How can XSS vulnerabilities be detected in a web application?

A) Using automated security scanners
B) Manually injecting <script> tags in input fields
C) Reviewing frontend code for unsafe DOM manipulation
D) All of the above

Answer: D) All of the above
Explanation: A combination of automated tools, manual testing, and code reviews is essential for detecting XSS vulnerabilities.


131. Why is it important to escape user input before displaying it in JavaScript event handlers?

A) To prevent users from submitting large inputs
B) To prevent XSS attacks where event handlers execute malicious scripts
C) To make input formatting easier
D) To improve performance

Answer: B) To prevent XSS attacks where event handlers execute malicious scripts
Explanation: Without escaping, user input in event handlers could execute arbitrary JavaScript.


132. What is the risk of dynamically creating <script> elements with user input?

A) It slows down script execution
B) It can allow attackers to execute arbitrary JavaScript
C) It improves application security
D) It prevents CSRF attacks

Answer: B) It can allow attackers to execute arbitrary JavaScript
Explanation: Dynamically injecting user-controlled scripts can lead to XSS vulnerabilities.


133. How does setting X-Frame-Options: SAMEORIGIN improve security?

A) It prevents the page from being loaded in iframes from different origins
B) It blocks JavaScript execution
C) It prevents SQL Injection
D) It improves website speed

Answer: A) It prevents the page from being loaded in iframes from different origins
Explanation: This helps prevent clickjacking attacks by disallowing embedding of pages in unauthorized iframes.


134. Why should output encoding be used even when input validation is implemented?

A) Because validation alone does not prevent XSS
B) Because encoding slows down the website
C) Because validation is only required for numeric inputs
D) Because encoding prevents SQL Injection

Answer: A) Because validation alone does not prevent XSS
Explanation: Input validation helps, but encoding ensures that user input is displayed as text, not executed as code.


135. How does setting sandbox on iframes help prevent XSS?

A) It disables all JavaScript execution inside the iframe
B) It restricts scripts and prevents access to the parent page
C) It prevents users from resizing the iframe
D) It disables all HTML content

Answer: B) It restricts scripts and prevents access to the parent page
Explanation: sandbox ensures that iframe content cannot interact with the parent page, mitigating XSS risks.


136. Why should URL parameters be properly encoded?

A) To prevent script execution from user input in URLs
B) To improve search engine optimization
C) To make URLs look shorter
D) To allow users to modify URL content freely

Answer: A) To prevent script execution from user input in URLs
Explanation: Encoding prevents script injection via URL parameters.


137. What is the main purpose of a Web Application Firewall (WAF) in XSS prevention?

A) To block malicious requests containing XSS payloads
B) To encrypt all HTML content
C) To disable JavaScript execution
D) To store logs of all user activity

Answer: A) To block malicious requests containing XSS payloads
Explanation: WAFs filter and block malicious input patterns to prevent XSS attacks.


138. How does a secure session cookie configuration help in mitigating XSS risks?

A) By setting HttpOnly and Secure attributes to prevent JavaScript access and enforce HTTPS
B) By making cookies expire instantly
C) By allowing cookies to be accessible in JavaScript
D) By disabling all cookies

Answer: A) By setting HttpOnly and Secure attributes to prevent JavaScript access and enforce HTTPS
Explanation: This prevents XSS-exploited scripts from stealing session cookies.


139. What is a risk of allowing unrestricted file uploads in a web application?

A) Attackers could upload scripts and execute them
B) It increases storage usage
C) It slows down the website
D) It prevents login issues

Answer: A) Attackers could upload scripts and execute them
Explanation: Unrestricted file uploads can lead to stored XSS or remote code execution.


140. What is the best way to mitigate XSS in search query results?

A) Escape and encode all user input before displaying it
B) Allow raw HTML in search results
C) Use innerHTML for displaying results
D) Allow users to execute JavaScript in search results

Answer: A) Escape and encode all user input before displaying it
Explanation: Encoding search queries prevents user input from being executed as scripts.


141. Which of the following JavaScript functions should be avoided to prevent XSS when inserting user input into the DOM?

A) appendChild()
B) createTextNode()
C) innerHTML
D) textContent

Answer: C) innerHTML
Explanation: innerHTML can execute scripts if user input is not sanitized, making it a common target for XSS attacks.


142. What is the impact of an attacker successfully exploiting a stored XSS vulnerability?

A) The server crashes immediately
B) The malicious script is executed whenever a user visits the affected page
C) The attacker gains direct database access
D) The attacker disables JavaScript for all users

Answer: B) The malicious script is executed whenever a user visits the affected page
Explanation: Stored XSS persists in the database and executes when loaded, affecting multiple users.


143. How can dynamically generated URLs in JavaScript lead to XSS vulnerabilities?

A) If user input is not encoded before being included in the URL
B) If JavaScript does not use inline scripts
C) If CSP is enabled
D) If URLs are hardcoded

Answer: A) If user input is not encoded before being included in the URL
Explanation: Attackers can inject scripts via unescaped dynamic URLs, leading to XSS execution.


144. Why should input sanitization be applied both on the client-side and server-side?

A) To ensure smooth UI experience
B) Because attackers can bypass client-side validation
C) To improve SEO ranking
D) To allow better CSS rendering

Answer: B) Because attackers can bypass client-side validation
Explanation: Server-side validation ensures security even if attackers disable or bypass client-side checks.


145. What does the unsafe-inline CSP directive do?

A) It blocks all inline scripts
B) It allows execution of inline scripts and styles
C) It enables automatic script sanitization
D) It prevents CSS injection

Answer: B) It allows execution of inline scripts and styles
Explanation: unsafe-inline weakens CSP by allowing inline JavaScript execution, increasing XSS risks.


146. What is the primary benefit of setting Strict-Transport-Security (HSTS)?

A) It ensures the website always loads over HTTPS
B) It prevents XSS attacks entirely
C) It encrypts JavaScript files
D) It disables cookies

Answer: A) It ensures the website always loads over HTTPS
Explanation: HSTS forces browsers to use secure connections, reducing the risk of MITM attacks that could inject XSS payloads.


147. How does sandbox in iframes improve security?

A) It allows unrestricted script execution
B) It prevents scripts inside the iframe from accessing the parent page
C) It disables iframe loading
D) It removes all images inside the iframe

Answer: B) It prevents scripts inside the iframe from accessing the parent page
Explanation: sandbox limits iframe interactions, reducing the risk of embedded malicious scripts affecting the main page.


148. How does innerText differ from innerHTML in terms of XSS prevention?

A) innerText prevents script execution, while innerHTML allows it
B) innerText executes inline scripts, while innerHTML does not
C) innerHTML prevents CSS injection, while innerText does not
D) Both innerText and innerHTML are equally vulnerable to XSS

Answer: A) innerText prevents script execution, while innerHTML allows it
Explanation: innerText treats input as plain text, preventing script execution.


149. Why should user-generated HTML content be sanitized before storing it in a database?

A) To reduce database storage usage
B) To improve query performance
C) To prevent stored XSS attacks
D) To allow JavaScript execution in all queries

Answer: C) To prevent stored XSS attacks
Explanation: Storing unsanitized user HTML can lead to stored XSS when that data is later displayed.


150. What is the risk of executing JavaScript from a third-party domain?

A) The script might contain malicious code injected by attackers
B) It slows down page performance
C) It disables browser caching
D) It prevents XSS attacks

Answer: A) The script might contain malicious code injected by attackers
Explanation: Third-party scripts can be compromised, leading to supply-chain attacks and XSS vulnerabilities.


151. What is the purpose of window.escape() in JavaScript?

A) It escapes user input to prevent XSS
B) It encrypts URL parameters
C) It disables JavaScript execution
D) It improves JavaScript performance

Answer: A) It escapes user input to prevent XSS
Explanation: escape() helps encode special characters to prevent them from being interpreted as executable scripts.


152. Why should developers avoid using eval() with user input?

A) It allows execution of arbitrary JavaScript code, leading to XSS risks
B) It improves code readability
C) It blocks SQL Injection attacks
D) It removes all cookies from the browser

Answer: A) It allows execution of arbitrary JavaScript code, leading to XSS risks
Explanation: eval() executes input as JavaScript, which can be exploited for XSS.


153. How does window.postMessage() introduce security risks related to XSS?

A) It allows cross-origin data exchange without validation
B) It prevents JavaScript execution
C) It blocks all form submissions
D) It disables browser caching

Answer: A) It allows cross-origin data exchange without validation
Explanation: postMessage() can be exploited if untrusted sources send malicious scripts to an iframe.


154. Why should the Content-Type header be correctly set in HTTP responses?

A) To prevent browsers from interpreting scripts incorrectly
B) To improve page load speed
C) To allow all JavaScript execution
D) To disable browser caching

Answer: A) To prevent browsers from interpreting scripts incorrectly
Explanation: A misconfigured Content-Type can allow browsers to execute unintended scripts.


155. Why should <script> tags never contain user-generated content?

A) To prevent XSS attacks from executing arbitrary JavaScript
B) To improve CSS rendering
C) To allow script execution globally
D) To make HTML parsing faster

Answer: A) To prevent XSS attacks from executing arbitrary JavaScript
Explanation: Allowing user input inside <script> tags enables XSS attacks.


156. How can developers secure JSON API responses against XSS?

A) Escape and encode all data before displaying it
B) Use eval() to parse JSON data
C) Allow raw user input to be stored as JSON
D) Ignore validation for API responses

Answer: A) Escape and encode all data before displaying it
Explanation: Proper encoding ensures that JSON content is not executed as JavaScript.


157. What is the main security risk of allowing users to embed <iframe> elements?

A) Clickjacking and XSS attacks
B) Improved browser performance
C) Increased website traffic
D) More responsive user interfaces

Answer: A) Clickjacking and XSS attacks
Explanation: Attackers can embed malicious iframes to steal user data or execute scripts.


158. How does an attacker exploit an XSS vulnerability in a login form?

A) By injecting malicious scripts into input fields that execute upon submission
B) By disabling JavaScript in the browser
C) By sending HTTP POST requests
D) By modifying CSS styles

Answer: A) By injecting malicious scripts into input fields that execute upon submission
Explanation: XSS payloads can be executed when the login form processes user input.


159. Why should inline JavaScript be avoided in modern web development?

A) It increases XSS risks and reduces security
B) It improves code readability
C) It speeds up script execution
D) It enables automatic script sanitization

Answer: A) It increases XSS risks and reduces security
Explanation: Inline scripts are harder to control and increase XSS exposure.


160. How can developers prevent XSS in user-generated tooltips or popups?

A) Escape and encode all user input before rendering
B) Allow users to execute JavaScript in tooltips
C) Use innerHTML to insert dynamic content
D) Disable popups entirely

Answer: A) Escape and encode all user input before rendering
Explanation: Encoding prevents JavaScript execution in tooltips and popups.


161. How does JavaScript’s setInterval() function create an XSS risk?

A) It automatically escapes user input
B) If used with untrusted input, it can execute malicious scripts repeatedly
C) It only affects backend operations
D) It blocks JavaScript execution

Answer: B) If used with untrusted input, it can execute malicious scripts repeatedly
Explanation: Using setInterval(userInput, 1000) without validation can lead to XSS, as it executes JavaScript at timed intervals.


162. What is a common way attackers inject XSS through URL parameters?

A) By adding a <script> tag in the query string
B) By modifying HTTP response headers
C) By using an HTTPS connection
D) By encrypting input fields

Answer: A) By adding a <script> tag in the query string
Explanation: If user input is not properly encoded, attackers can inject <script> tags into URL parameters that execute JavaScript.


163. Which of the following is a secure way to handle dynamic JavaScript execution?

A) Use eval() on all user input
B) Avoid using innerHTML and prefer textContent
C) Allow all JavaScript execution from user input
D) Disable script execution globally

Answer: B) Avoid using innerHTML and prefer textContent
Explanation: textContent prevents JavaScript execution by treating input as plain text.


164. How does the onerror event in images relate to XSS?

A) It cannot be used for XSS attacks
B) Attackers can inject JavaScript into an image’s onerror attribute to execute malicious code
C) It only affects CSS files
D) It prevents XSS

Answer: B) Attackers can inject JavaScript into an image’s onerror attribute to execute malicious code
Explanation: The onerror event can be abused to execute JavaScript when an image fails to load.


165. What security feature in modern browsers can help prevent reflected XSS?

A) X-XSS-Protection header
B) innerHTML sanitization
C) document.write() execution
D) window.open() method

Answer: A) X-XSS-Protection header
Explanation: This header blocks reflected XSS attacks by detecting script execution in user input.


166. Why is using JavaScript’s localStorage for sensitive data a bad practice in terms of XSS?

A) Data stored in localStorage is accessible to JavaScript and can be stolen by an XSS attack
B) It encrypts all stored data
C) It disables JavaScript execution
D) It improves website performance

Answer: A) Data stored in localStorage is accessible to JavaScript and can be stolen by an XSS attack
Explanation: Unlike cookies with the HttpOnly flag, localStorage is fully accessible via JavaScript and can be stolen by an attacker if XSS is present.


167. What is the main risk of using window.location.href = userInput without validation?

A) The page will refresh automatically
B) An attacker can inject JavaScript into the URL to execute malicious code
C) It prevents XSS
D) It improves performance

Answer: B) An attacker can inject JavaScript into the URL to execute malicious code
Explanation: If userInput contains JavaScript, it can execute when assigned to window.location.href.


168. How does using Content-Security-Policy: default-src 'none' help prevent XSS?

A) It blocks all script execution unless explicitly allowed
B) It allows unrestricted JavaScript execution
C) It prevents CSRF attacks
D) It disables CSP

Answer: A) It blocks all script execution unless explicitly allowed
Explanation: This CSP setting ensures that only explicitly defined sources can execute scripts, preventing XSS.


169. How does disabling browser autocomplete fields help prevent XSS?

A) It prevents the browser from storing malicious scripts in input fields
B) It stops JavaScript execution
C) It disables cookies
D) It prevents HTTPS connections

Answer: A) It prevents the browser from storing malicious scripts in input fields
Explanation: Disabling autocomplete reduces the chance of script injection through stored malicious values.


170. Which of the following input types is particularly vulnerable to XSS if not sanitized?

A) Plain text input
B) Email input
C) HTML-rich text input
D) Password input

Answer: C) HTML-rich text input
Explanation: HTML-rich text input allows for formatting but can be exploited to inject JavaScript if not properly sanitized.


171. How can an attacker exploit an input field with JavaScript event attributes?

A) By injecting JavaScript in onmouseover, onclick, or onerror attributes
B) By disabling JavaScript in their browser
C) By submitting empty form fields
D) By using HTTPS

Answer: A) By injecting JavaScript in onmouseover, onclick, or onerror attributes
Explanation: If user input is inserted into HTML attributes without encoding, attackers can inject event handlers that execute scripts.


172. What is the best way to prevent stored XSS in user-generated blog comments?

A) Sanitize and encode input before storing it in the database
B) Store all input in plain text
C) Allow users to input raw JavaScript
D) Use innerHTML to display comments

Answer: A) Sanitize and encode input before storing it in the database
Explanation: Encoding input prevents scripts from executing when retrieved and displayed.


173. How can an attacker use JavaScript’s console.log() to aid in an XSS attack?

A) By executing commands via the developer console after injecting scripts
B) By crashing the browser
C) By preventing page rendering
D) By automatically deleting cookies

Answer: A) By executing commands via the developer console after injecting scripts
Explanation: Attackers may use console.log() to inspect and debug malicious scripts injected into a page.


174. Why should JavaScript’s document.domain be used cautiously?

A) It can be manipulated by an attacker to allow unauthorized cross-origin access
B) It prevents XSS attacks
C) It encrypts HTTP headers
D) It disables inline scripts

Answer: A) It can be manipulated by an attacker to allow unauthorized cross-origin access
Explanation: Improper use of document.domain can lead to security issues by allowing scripts to access cookies and resources from different origins.


175. How can CAPTCHA help mitigate XSS risks?

A) It helps prevent automated script injection attempts
B) It disables JavaScript execution
C) It improves website loading speed
D) It prevents all forms of hacking

Answer: A) It helps prevent automated script injection attempts
Explanation: CAPTCHA helps reduce automated attacks, though it is not a direct XSS prevention measure.


176. How can HTTP response headers be used to prevent XSS?

A) By setting X-Content-Type-Options: nosniff and Content-Security-Policy
B) By allowing all user input to be executed
C) By disabling all cookies
D) By blocking HTTPS requests

Answer: A) By setting X-Content-Type-Options: nosniff and Content-Security-Policy
Explanation: These headers prevent browsers from misinterpreting content and executing malicious scripts.


177. What is the effect of enabling Referrer-Policy: no-referrer on security?

A) It prevents sending referrer information that could leak sensitive data
B) It disables JavaScript execution
C) It speeds up HTTP requests
D) It prevents CSRF attacks

Answer: A) It prevents sending referrer information that could leak sensitive data
Explanation: This setting enhances privacy and security by preventing referrer information from being shared.


178. Why should external scripts be loaded over HTTPS?

A) To prevent attackers from injecting malicious scripts via MITM attacks
B) To increase page load time
C) To improve SEO
D) To allow scripts to execute faster

Answer: A) To prevent attackers from injecting malicious scripts via MITM attacks
Explanation: Loading scripts over HTTPS prevents unauthorized code injection from network-level attackers.


179. What is a major risk of allowing users to modify website URLs via query parameters?

A) It can be used to inject malicious JavaScript via XSS
B) It increases website speed
C) It prevents data leaks
D) It improves page caching

Answer: A) It can be used to inject malicious JavaScript via XSS
Explanation: If query parameters are not properly sanitized, attackers can use them to inject JavaScript.


180. How does limiting input length help prevent XSS?

A) It reduces the likelihood of long malicious scripts being injected
B) It disables JavaScript
C) It encrypts all user input
D) It improves website layout

Answer: A) It reduces the likelihood of long malicious scripts being injected
Explanation: While not a complete solution, input length restrictions can reduce the impact of XSS attempts.


181. What is one way to prevent XSS attacks in search functionality?

A) Escape and encode all user input before displaying search results
B) Allow users to execute JavaScript within search queries
C) Store search queries in cookies
D) Disable search functionality altogether

Answer: A) Escape and encode all user input before displaying search results
Explanation: Escaping ensures user input is treated as plain text rather than executable JavaScript.


182. Why should <script> tags inside user-generated content be removed or sanitized?

A) They can execute malicious JavaScript in a user’s browser
B) They improve website performance
C) They help speed up rendering of pages
D) They allow users to add custom styling

Answer: A) They can execute malicious JavaScript in a user’s browser
Explanation: Allowing <script> tags in user input creates an entry point for XSS attacks.


183. How can JavaScript’s window.open() be misused in an XSS attack?

A) Attackers can use it to open phishing pages in new tabs
B) It automatically prevents script injection
C) It encrypts URL parameters
D) It forces all requests to use HTTPS

Answer: A) Attackers can use it to open phishing pages in new tabs
Explanation: Malicious JavaScript can open deceptive phishing pages in new tabs, tricking users into entering sensitive data.


184. What role does a Web Application Firewall (WAF) play in XSS prevention?

A) It filters and blocks malicious requests before they reach the application
B) It disables all JavaScript execution
C) It speeds up page loading times
D) It prevents all forms of SQL Injection

Answer: A) It filters and blocks malicious requests before they reach the application
Explanation: A WAF detects and blocks requests containing known XSS payloads.


185. Why should dynamically created iframe elements be handled carefully?

A) Attackers can use them to inject malicious content from external sources
B) They make a website look outdated
C) They improve JavaScript performance
D) They prevent phishing attacks

Answer: A) Attackers can use them to inject malicious content from external sources
Explanation: If an attacker controls an iframe’s source, they can load malicious scripts or phishing content.


186. How does disabling inline JavaScript improve security?

A) It prevents XSS attacks by blocking execution of injected scripts
B) It slows down page loading
C) It removes all JavaScript from a page
D) It blocks form submissions

Answer: A) It prevents XSS attacks by blocking execution of injected scripts
Explanation: Inline scripts are a common attack vector, and disabling them reduces XSS risks.


187. Why is it important to validate user input before storing it in a database?

A) To prevent stored XSS attacks
B) To increase database query speed
C) To allow users to execute JavaScript
D) To improve page styling

Answer: A) To prevent stored XSS attacks
Explanation: Validating input prevents malicious scripts from being stored and later executed.


188. What is the role of the Referrer-Policy HTTP header in security?

A) It prevents browsers from sending sensitive referrer information to external sites
B) It encrypts all JavaScript requests
C) It blocks inline scripts
D) It prevents SQL Injection

Answer: A) It prevents browsers from sending sensitive referrer information to external sites
Explanation: This helps prevent data leakage by restricting how much referrer information is shared.


189. How can innerHTML be used safely in web applications?

A) By ensuring the input is properly sanitized and encoded before insertion
B) By allowing all user input to be directly inserted
C) By using eval() with innerHTML
D) By disabling CSP

Answer: A) By ensuring the input is properly sanitized and encoded before insertion
Explanation: Without sanitization, innerHTML can execute malicious scripts.


190. What is the risk of using window.location.search without validation?

A) Attackers can inject scripts via URL parameters
B) It improves website performance
C) It prevents SQL Injection
D) It forces pages to load faster

Answer: A) Attackers can inject scripts via URL parameters
Explanation: If unsanitized, window.location.search can be manipulated to inject JavaScript.


191. Why should a developer avoid placing untrusted user input inside onclick attributes?

A) It allows execution of malicious JavaScript when the element is clicked
B) It improves user experience
C) It speeds up rendering
D) It disables the button

Answer: A) It allows execution of malicious JavaScript when the element is clicked
Explanation: Injecting user input into event handlers can trigger XSS when clicked.


192. How does JavaScript’s fetch() function relate to XSS?

A) If misused, it can expose a web application to malicious script injections
B) It blocks all JavaScript execution
C) It encrypts API requests
D) It prevents SQL Injection

Answer: A) If misused, it can expose a web application to malicious script injections
Explanation: If untrusted user input is used in fetch requests, it can lead to XSS.


193. What is a good security practice when using document.write()?

A) Avoid using it with user-generated content
B) Use it in all forms and input fields
C) Allow it to execute inline scripts
D) Use eval() with document.write()

Answer: A) Avoid using it with user-generated content
Explanation: document.write() can execute scripts, making it dangerous when handling user input.


194. Why should websites avoid using javascript: URLs?

A) They allow execution of JavaScript, which can lead to XSS attacks
B) They improve website performance
C) They prevent SQL Injection
D) They are required for modern web applications

Answer: A) They allow execution of JavaScript, which can lead to XSS attacks
Explanation: javascript: URLs execute code when clicked, making them a common XSS attack vector.


195. What is the impact of setting script-src 'self' in a CSP policy?

A) It allows only scripts from the same origin to execute
B) It blocks all JavaScript execution
C) It disables cookies
D) It forces all scripts to load over HTTP

Answer: A) It allows only scripts from the same origin to execute
Explanation: This CSP rule prevents external scripts from being executed, reducing XSS risks.


196. What should a developer do when displaying user-uploaded file names?

A) Sanitize and encode the file name before displaying it
B) Allow any characters in the file name
C) Store file names directly in a JavaScript variable
D) Use innerHTML to insert the file name

Answer: A) Sanitize and encode the file name before displaying it
Explanation: Unsanitized file names can contain scripts that execute when viewed.


197. What is an effective way to test for XSS vulnerabilities in a web application?

A) Inject <script>alert('XSS')</script> into input fields and URLs
B) Modify the site’s CSS
C) Use a slow internet connection
D) Disable cookies

Answer: A) Inject <script>alert('XSS')</script> into input fields and URLs
Explanation: This is a common test to check if user input is executed as JavaScript.


198. Why is using console.log(userInput) dangerous when debugging XSS vulnerabilities?

A) It can be used to inspect and execute malicious scripts injected into the page
B) It prevents page rendering
C) It disables JavaScript execution
D) It encrypts the console output

Answer: A) It can be used to inspect and execute malicious scripts injected into the page
Explanation: Attackers may inject scripts that are logged and later executed via the console.


199. What is the purpose of implementing HTTP response headers like X-Frame-Options: DENY?

A) To prevent clickjacking attacks
B) To block all JavaScript execution
C) To improve SEO rankings
D) To disable HTTP requests

Answer: A) To prevent clickjacking attacks
Explanation: X-Frame-Options: DENY ensures a page cannot be loaded inside an iframe.


200. Why should JavaScript’s Function() constructor be avoided?

A) It allows execution of arbitrary JavaScript, making it an XSS risk
B) It speeds up function execution
C) It improves security
D) It prevents browser caching

Answer: A) It allows execution of arbitrary JavaScript, making it an XSS risk
Explanation: Similar to eval(), the Function() constructor can execute user-supplied JavaScript.