Skip to content

Instantly share code, notes, and snippets.

@gwpantazes
Last active January 26, 2023 14:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gwpantazes/818959580b47565ae1f33cddfcb43090 to your computer and use it in GitHub Desktop.
Save gwpantazes/818959580b47565ae1f33cddfcb43090 to your computer and use it in GitHub Desktop.
Setting Selenium WebDriver useragents
import io.github.bonigarcia.wdm.WebDriverManager;
import java.io.IOException;
import java.util.Map;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
/*
Touchscreen detection with mobile-detect.
- https://www.npmjs.com/package/mobile-detect
- https://github.com/zeno/mobile-detect-demo
- http://zeno.github.io/mobile-detect-demo/
How to do mobile Selenium emulation
- Chrome can emulate touchscreen - http://chromedriver.chromium.org/mobile-emulation
- Firefox can overriding useragent
- Safari?
- https://github.com/bonigarcia/webdrivermanager/issues/238 Driver binary not
needed!
- Edge? ** Maybe we skip this one
Great Selenium useragent howto: https://tarunlalwani.com/post/selenium-change-user-agent-different-browsers/
*/
class ChromeMobileEmulation {
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("mobileEmulation", Map.of("deviceName", "Nexus 5"));
WebDriver driver = new ChromeDriver(chromeOptions);
driver.get("http://zeno.github.io/mobile-detect-demo/");
}
}
class FirefoxUserAgentOverride {
public static void main(String[] args) {
WebDriverManager.firefoxdriver().setup();
final String userAgent =
"Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 "
+ "(KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16";
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.addPreference("general.useragent.override", userAgent);
WebDriver driver = new FirefoxDriver(firefoxOptions);
driver.get("http://zeno.github.io/mobile-detect-demo/");
}
}
class SafariMobile {
public static void main(String[] args) throws IOException {
// TODO Check that this one works! WIP
ProcessBuilder pb = new ProcessBuilder(
"defaults",
"write",
"com.apple.Safari CustomUserAgent",
"\"New user agent\""
);
pb.inheritIO();
pb.directory(new File("bin"));
pb.start();
new SafariDriver();
}
}
class EdgeMobile {
// TODO
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment