TL;DR
This guide shows you how to block pop-up windows using JavaScript code. We’ll cover a simple method that prevents most common pop-up attempts by overriding the window.open() function.
Blocking Pop-ups with JavaScript
- Understand the Problem: Websites often use
window.open()to create new browser windows (pop-ups). We’ll intercept this call to stop them. - Create a JavaScript Function: Write a function that will replace the default
window.open()with one that does nothing or displays a message.function blockPopups(url, windowName, features) { alert('Pop-up blocked!'); // Or any other action you prefer return false; } - Override the
window.open()Function: Assign your function to the globalwindow.open()property.window.open = blockPopups; - Add the Code to Your Page: Include this JavaScript code in a <script> tag within the <head> section of your HTML document.
<head> <script> function blockPopups(url, windowName, features) { alert('Pop-up blocked!'); return false; } window.open = blockPopups; </script> </head> - Test the Code: Open a website that normally displays pop-ups and verify that they are blocked.
- Considerations & Limitations:
- This method doesn’t block all types of pop-ups. Some advanced techniques might bypass this simple override.
- Users can disable JavaScript in their browser, which will prevent this code from running.
- Some legitimate websites use pop-ups for important functions (e.g., printing). Blocking all pop-ups may break these features.
Alternative: More Robust Pop-up Blocking
For more reliable pop-up blocking, consider using a dedicated browser extension or a content security policy (CSP).