Selenium 4 – Chrome Dev Protocol – Block Url
Selenium 4 alpha version has introduced support for Chrome Dev Protocol which is really a good news for automation testers. This can be used in various scenarios. E.g.
- Mimic Geo location
- Block a url (this is particularly useful if you want to check how page behaves if e.g. product recommendation api is blocked)
- Check if the application recovers from brief network issue etc
In this blog we will see, how to block a url with the ChromeDevTools. And we will use setBlockedUrls method to achieve this.
Sample code
package selenium4.selenium4; import static java.util.Optional.empty; import static java.util.Optional.of; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.devtools.DevTools; import org.openqa.selenium.devtools.network.Network; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.google.common.collect.ImmutableList; public class Selenium4Locators { ChromeDriver webDriver = null; String url=""; // Application url under Test String urlToBlock=""; // Url which you want to block. It can be an API url or image url etc @BeforeTest public void beforeTest() throws InterruptedException{ System.setProperty("webdriver.chrome.driver","C:\\Selenium\\Chrome84\\chromedriver.exe"); webDriver = new ChromeDriver(); webDriver.manage().window().maximize(); Thread.sleep(2000); } @Test public void f() { DevTools devTools = webDriver.getDevTools(); devTools.createSession(); devTools.send(Network.enable(of(100000000), empty(),empty())); devTools.send(Network.setBlockedURLs(ImmutableList.of(urlToBlock))); webDriver.get(url); // load application url under Test } @AfterTest public void afterTest() { webDriver.quit(); } }
Few points to note:
Here we are using ChromeDriver as its ChromeDevProtocol 🙂
Replace the url and urlToBlock as per your requirement. And also use Thread.sleep() or Debug to see if the urlToBlock is really blocked or not.