Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How to Handle Browser Ads with Selenium and C# depends on what “ad” means in the browser. A page overlay is an element in the DOM; an ad opened in a new tab is a separate window context; and a JavaScript alert is a native browser dialog. Selenium does not have a universal ad-blocking switch. Identify the behavior first, then use the matching WebDriver operation and an explicit wait.

Identify the browser behavior before writing a handler

Start by asking where the interruption lives and what the automation should do with it. These cases are not interchangeable:

What you see Where it lives Typical Selenium response
A banner, modal, or interstitial drawn over the page Page DOM, sometimes inside an iframe Wait for its element and interact with its actual control
A new tab or window after a click A separate WebDriver window context Save the original handle, wait for the new one, switch contexts, then return or close it
A native JavaScript alert, confirm, or prompt Browser dialog, not a page element Use Selenium’s alert interface
Network requests for ads or trackers Browser network activity Treat as instrumentation or request-control work, not DOM dismissal

Decide whether the goal is to test that advertising appears, dismiss an obstructive overlay, keep an unrelated popup from derailing a workflow, or observe network traffic. The right answer depends on that goal as much as on the visual symptom.

Set up Selenium and use waits for the condition you need

The examples below use C# with Selenium WebDriver and Selenium.Support. Install the packages into your .NET project, for example with:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
GL.iNet GL-MT3000 Beryl AX Wi-Fi 6 Travel Router, 2.5G WAN, VPN, OpenWrt
  • 【DUAL BAND AX TRAVEL ROUTER】Products with US, UK, EU Plug; Dual band network with wireless speed 574Mbps (2.4G)+2402Mbps (5G); 2.5G Multi-gigabit WAN port and a 1G gigabit LAN port; USB 3.0 port; Wi-Fi 6 offers more than double the total Wi-Fi speed with the MT3000 VPN Router.
  • 【VPN CLIENT & SERVER】OpenVPN and WireGuard are pre-installed, compatible with 30+ VPN service providers (active subscription required). Simply log in to your existing VPN account with our portable wifi device, and Beryl AX automatically encrypts all network traffic within the connected network. Max. VPN speed of 150 Mbps (OpenVPN); 300 Mbps (WireGuard). *Speed tests are conducted on a local network. Real-world speeds may differ depending on your network configuration.*
  • 【OpenWrt 21.02 FIRMWARE】The Beryl AX is a portable wifi box and mini router that runs on OpenWrt 21.02 firmware. It supports more than 5,000 ready-made plug-ins for customization. Simply browse, install, and manage packages with our no-code interface within Beryl AX's Admin Panel.
  • 【PROTECT YOUR NETWORK SECURITY】Our pocket wifi, unlike other vulnerable portable wifi hotspot for travel purposes supports WPA3 protocol–Preventive measures against password brute-force attacks; DNS over HTTPS & DNS over TLS–Protecting domain name system traffic and preventing data eavesdropping from malicious parties; IPv6–Built-in authentication for privacy protection, eliminating the need for network address translation.
  • 【VPN CASCADING AT EASE】Surpassing the mediocre performance of most VPN routers for home usage, the Beryl AX is capable of hosting a VPN server and VPN client at the same time within the same device, enabling users to remote access local network resources like Wi-Fi printers or local web servers, and accessing the public internet as a VPN client simultaneously.
dotnet add package Selenium.WebDriver
dotnet add package Selenium.Support

Use a browser driver compatible with the browser installed in your environment; the exact setup and browser options depend on that browser and driver. Selenium navigation waits for a document readiness state, but JavaScript can continue changing the page after navigation returns. Wait for the specific element or window state your task requires rather than assuming that page load means every ad or widget has settled. See Selenium’s Browser Options and Browser interactions documentation.

Here is a minimal Chrome setup and a reusable explicit wait:

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;

var options = new ChromeOptions();
using var driver = new ChromeDriver(options);
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));

driver.Navigate().GoToUrl("https://example.com");
wait.Until(d => ((IJavaScriptExecutor)d)
    .ExecuteScript("return document.readyState")?.ToString() == "complete");

This checks document readiness only; it is not a substitute for waiting on a dynamically rendered banner, close control, or popup. Choose a timeout appropriate to the application and environment. When a condition does not become true, Selenium throws a timeout exception; capture useful page and browser state in your own test diagnostics before deciding whether to retry.

Dismiss a banner or overlay in the page DOM

For a page-owned banner, locate a stable selector and wait until its close control is visible or clickable. The selector below is illustrative: replace it with a selector that actually exists on the site or in your test fixture.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
var closeButton = wait.Until(d =>
{
    var element = d.FindElement(By.CssSelector(".consent-banner button.close"));
    return element.Displayed && element.Enabled ? element : null;
});
closeButton.Click();

Prefer the interface a visitor would use: an explicit accept, reject, or close button. Do not assume that every banner permits dismissal without a choice, or that a selector is stable across sites. If the purpose of the test is to verify the banner, do not close it before making the relevant assertions.

When the ad is inside an iframe

Elements inside a frame are not found from the top-level document. Switch to the frame first, find and interact with the element, and then return to the top-level page. Frame selectors are site-specific:

var frame = wait.Until(d => d.FindElement(By.CssSelector("iframe.ad-frame")));
driver.SwitchTo().Frame(frame);

var frameClose = wait.Until(d =>
{
    var element = d.FindElement(By.CssSelector("button.close"));
    return element.Displayed && element.Enabled ? element : null;
});
frameClose.Click();
driver.SwitchTo().DefaultContent();

If interaction throws because the frame has not loaded yet, wait for the frame to be available before switching. If the element is not inside that frame, switching into it will make the target page’s elements unavailable until you switch back. Selenium’s interaction and execution context is described in its Browser interactions documentation.

Rank #2
GL.iNet GL-BE9300 Flint 3 Tri-Band Wi-Fi 7 Router 5 x 2.5G VPN Router
  • 【Rapid OpenVPN & Wireguard speed】Wireguard VPN and OpenVPN speeds both up to 680Mbps, giving you complete control over your gaming, streaming and working bandwidth. Actual speed may differ depending on internet service provider, network environment, VPN server location, VPN service provider, etc.
  • 【AdGuard Home Supported】Enabling the use of a DNS server for blocking unwanted tracking and offers a convenient web interface for filtering selected digital advertisements. Users can take full control of their online experience and enjoy a clutter-free browsing environment with ease.
  • 【Mass device connectivity】Experience enhanced online connectivity with our higher storage capacity, catering to over a hundred devices and fulfilling the requirements of DIY users seeking to install additional plugins. Enjoy stable and reliable connections, ensuring seamless performance and accommodating a wide range of digital needs.
  • 【Easy Setup】Follow the Initial Set-up video tutorial on Amazon or Connect BE9300 to your computer via Ethernet cable to access the web Admin Panel, easy connect to wireless internet.
  • 【MLO Technology】Flint 3 represents the future of wireless technology, delivering ultra-fast speeds, significantly reduced latency, and improved connectivity in high-density environments through cutting-edge innovations like Multi-Link Operation (MLO), enhanced OFDMA, 4K QAM, and preamble puncturing.

Why deleting the banner with JavaScript is usually a poor default

JavaScript execution operates in the currently selected window and frame. It is possible to remove a DOM node with a script, but doing so bypasses the page’s normal controls and can conceal layout, focus, or interaction problems that a test should expose. Prefer a documented test fixture or the page’s own control. Use DOM mutation only when changing the DOM is explicitly part of the task, and make that choice visible in the test.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Handle an ad that opens a new tab or window

Selenium represents tabs and windows as window handles. Save the current handle before triggering the action, then wait for a handle that was not present before. Do not assume the new context is always at index 1 or that a particular destination will load. The official Selenium guidance includes C# window examples: Working with windows and tabs.

string originalHandle = driver.CurrentWindowHandle;
var handlesBefore = driver.WindowHandles.ToHashSet();

// Trigger the link or button that may open another context.
driver.FindElement(By.CssSelector("a.opens-ad-window")).Click();

string newHandle = wait.Until(d =>
    d.WindowHandles.FirstOrDefault(h => !handlesBefore.Contains(h))
    ?? throw new WebDriverTimeoutException("No new window or tab appeared."));

driver.SwitchTo().Window(newHandle);

// Inspect the new context, or close it if that is the intended behavior.
// driver.Close();

driver.SwitchTo().Window(originalHandle);

The selector is only an example. If multiple new contexts can open, collect all handles added after the action and apply a defined rule—such as waiting for a known page condition—rather than selecting whichever appears first. If your automation closes the unwanted context, switch back only after closing it. Switching to a closed handle will fail.

Popup behavior can vary with browser configuration and version. ChromeDriver’s capabilities material discusses Chrome options and popup dialogs, but browser-specific settings should be checked against the installed Chrome/ChromeDriver pair: Capabilities and ChromeOptions. A popup-blocking setting is not the same thing as comprehensive blocking of display ads, trackers, or page-injected content.

Rank #3
GL.iNet GL-MT6000 Flint 2 Wi-Fi 6 Gaming Router Dual 2.5G Ports
  • Please update the firmware upon initial setup of the router, as it greatly enhances the device's performance and ensures a superior user experience.*** 【WiFi 6 Standard with ultra-low latency】Wi-Fi 6 speeds up to 6 Gbps to let you enjoy smoother 4K streaming, gaming, video calls and more, DDR4 1GB / eMMC 8GB
  • 【High Speed Gaming Router】Dominate with uninterrupted performance with the ultimate MT6000 gaming internet router, equipped with 8-stream Wi-Fi 6 technology, the Flint 2 delivers blazing speeds, ensuring a stable and high-speed connection during intense multiplayer battles.
  • 【Rapid OpenVPN & Wireguard speed】Wireguard VPN and OpenVPN speeds up to 900Mbps and 880Mbps respectively, giving you complete control over your gaming, streaming and working bandwidth. Actual speed may differ depending on internet service provider, network environment, VPN server location, VPN service provider, etc.
  • 【AdGuard Home Supported】Enabling the use of a DNS server for blocking unwanted tracking and offers a convenient web interface for filtering selected digital advertisements. Users can take full control of their online experience and enjoy a clutter-free browsing environment with ease.
  • 【Mass device connectivity】Experience enhanced online connectivity with our higher storage capacity, catering to over a hundred devices and fulfilling the requirements of DIY users seeking to install additional plugins. Enjoy stable and reliable connections, ensuring seamless performance and accommodating a wide range of digital needs.

Handle a native JavaScript dialog

A native alert is not rendered as a normal DOM element, so FindElement is the wrong tool. Switch to Selenium’s alert interface. For example, if the site under test deliberately opens an alert and your test is expected to accept it:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
var alert = wait.Until(d =>
{
    try
    {
        return d.SwitchTo().Alert();
    }
    catch (NoAlertPresentException)
    {
        return null;
    }
});

string message = alert.Text;
alert.Accept();

Use Dismiss() instead when the intended behavior is to cancel a confirmation dialog; for a prompt, the alert interface also supports sending text before accepting. Only accept or dismiss a dialog when that action matches the scenario being tested. Confirm the exact interface behavior against the .NET API version installed in your project: Selenium .NET API Docs.

Popup blocking, ad blocking, and request observation are different jobs

Browser options configure a session; they do not turn Selenium into a general-purpose ad blocker. A browser setting that changes whether a popup appears may be useful when the task specifically concerns popup behavior, but it does not establish that banners, trackers, or ad scripts are blocked. Browser-specific options can also change test fidelity: a result from a specially configured session may not represent what a visitor sees in the normal browser.

Selenium describes WebDriver BiDi as a bidirectional protocol that can stream browser events, including network requests, console messages, and JavaScript errors. That makes it relevant when the task is observing browser activity. The documentation does not, by itself, provide a verified, ready-to-copy C# implementation for blocking ad requests, nor does it make BiDi a cross-browser ad-filtering switch. See the WebDriver and BiDi overview and verify any implementation against the Selenium and browser versions you use.

  • Need a realistic page test? Keep normal browser behavior and interact with the page’s real controls.
  • Need to test popup handling? Observe and handle the extra window context instead of assuming a blocker will prevent it.
  • Need network telemetry? Investigate version-specific BiDi support and event APIs; do not treat DOM removal as request blocking.
  • Need to control test conditions? Use a controlled fixture or documented browser setup, and record configuration that changes what the browser renders.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common failures

“No such element” for a banner or close button

The element may be injected later, be inside an iframe, use a different selector, or not appear in that test run. Confirm the DOM and selector, switch into the correct frame when needed, and wait for the element condition instead of searching immediately after navigation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
GL.iNet GL-MT5000 Brume 3 Wired VPN Security Gateway NO Wi-Fi
  • 【Up to 1100 Mbps VPN Speed 】 Hardware-accelerated WireGuard and OpenVPN-DCO deliver up to 1100 Mbps VPN throughput, over 3× faster than Brume 2 for smooth remote access and file transfers.
  • 【Three 2.5G Ports & Multi-WAN】Tri-port 2.5GbE design with flexible WAN LAN configuration supports multi-gigabit wired setups, dual-ISP Multi-WAN and failover to keep home and SOHO networks online.
  • 【Stealth VPN Obfuscation】VPN obfuscation disguises VPN traffic as regular HTTPS, helping you evade blocking, bypass restrictive networks and maintain stable, private connections.
  • 【DPI protection】Deep Packet Inspection with visual dashboards blocks adult/gambling/malicious sites, while SQM and QoS prioritize gaming, calls, and video when bandwidth is tight
  • 【OpenWrt & USB 3.0 Expansion】OpenWrt with 1GB DDR4 and 8GB eMMC lets you install plugins and build VPN, ad-blocking or NAS, while USB 3.0 Type‑C connects high-speed storage or 4G/5G dongles

The element exists but Selenium cannot click it

It may be hidden, disabled, covered by another layer, or not yet ready for interaction. Wait for visibility and enabled state, then investigate which overlay is intercepting the click. Avoid treating JavaScript node removal as a routine fix if the test is meant to represent normal user interaction.

The new tab never appears

The click may not have opened a context, the action may have been blocked, or the page may still be processing it. Check that the click targeted the intended control, wait for a new handle rather than a fixed delay, and capture the current handle list when the wait times out. Do not hard-code a handle position.

“No alert present” or an alert wait times out

The interruption may be a DOM modal rather than a native dialog, or the alert may not belong to the current window. Confirm what kind of UI appeared and that Selenium is focused on the context that triggered it before calling SwitchTo().Alert().

The page looks incomplete even though navigation returned

Document readiness can precede JavaScript-driven rendering. Wait for the specific content, close control, or state your task needs. Arbitrary long sleeps can waste time when content is quick and still fail when a page is slower than expected.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
GL.iNet GL-MT3600BE Beryl 7 Dual-Band Wi-Fi 7 Travel Router
  • 【DUAL BAND WIFI 7 TRAVEL ROUTER】Products with US, UK, EU, AU Plug; Dual band network with wireless speed 688Mbps (2.4G)+2882Mbps (5G); Dual 2.5G Ethernet Ports (1x WAN and 1x LAN Port); USB 3.0 port. Enjoy gaming and streaming across up to 120 devices.
  • 【HIGH SPEED VPN CLIENT & SERVER】Max. VPN speed of 1100 Mbps (WireGuard); 1000 Mbps (OpenVPN-DCO). OpenVPN and WireGuard are pre-installed, compatible with 30+ VPN service providers (active subscription required). Simply log in to your existing account with our portable wifi device, and Beryl 7 automatically encrypts all network traffic within the connected network. *Speed tests are conducted on a local network. Real-world speeds may differ depending on your network configuration.*
  • 【OpenWrt 21.02 FIRMWARE】The Beryl 7 (GL-MT3600BE) is a high-performance Wi-Fi 7 travel router, built with OpenWrt 21.02 (Kernel 5.4.281) for maximum customization and advanced networking capabilities. With 512MB storage, total customization with open-source freedom and flexible installation of OpenWrt plugins.
  • 【PERFECT PORTABLE WIFI ROUTER FOR TRAVEL】The Beryl 7 is an ideal international wireless portable wifi travel router. With its mini size and travel-friendly features, the pocket Wi-Fi router is the perfect companion for travelers in need of a secure internet connectivity on the go. portable wi-fi for traveling, hotels or cruise ships.
  • 【PROTECT YOUR NETWORK SECURITY】Our pocket wifi, unlike other vulnerable portable wifi hotspot devices for travel purposes supports WPA3 protocol–Preventive measures against password brute-force attacks; DNS over HTTPS & DNS over TLS–Protecting domain name system traffic and preventing data eavesdropping from malicious parties; IPv6–Built-in authentication for privacy protection, eliminating the need for network address translation.

A browser option behaves differently after an update

Options and capabilities are browser-specific and can vary by browser/driver version. Check the corresponding current browser documentation and the installed Chrome/ChromeDriver pairing instead of copying a dated flag as universal advice.

Or skip the browser setup

If your goal is to capture a page rather than test Selenium’s ad-handling behavior, ScreenshotNeo offers a website screenshot API and MCP server. Its API can return an image or PDF from one GET request. Example using cURL, as documented at ScreenshotNeo’s documentation:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and responses identify the page verdict and billing status in headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents, including Claude, Cursor, and other MCP clients.

The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Yearly billing gives two months free, and every feature is available on every plan. ScreenshotNeo is for capturing pages, not a replacement for validating ad behavior in a Selenium test. Sign up for 1,000 free screenshots a month with no card.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can Selenium block every browser ad with one setting?

No. Selenium provides browser automation controls, not a universal ad-blocking switch. The correct handling depends on whether the interruption is page content, another window, a native dialog, or network activity.

Should I use implicit waits for ad elements?

The examples use explicit waits tied to a particular condition because ad UI may load dynamically. Avoid mixing wait strategies without understanding how they affect element lookups and timeout behavior in your project.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.