Blog | G5 Cyber Security

Block Pop-ups with JavaScript

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

  1. Understand the Problem: Websites often use window.open() to create new browser windows (pop-ups). We’ll intercept this call to stop them.
  2. 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;
    }
    
  3. Override the window.open() Function: Assign your function to the global window.open() property.
    window.open = blockPopups;
    
  4. 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>
    
  5. Test the Code: Open a website that normally displays pop-ups and verify that they are blocked.
  6. 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).

Exit mobile version