How to disable JavaScript in browser using Selenium (Java)? - java

In my feature automation, I need to disable JavaScript in browser and run the flow. How to disable JavaScript?
Tried DesiredCapabilities for firefox and Chrome.
DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability(CapabilityType.SUPPORTS_JAVASCRIPT, false)
And
DesiredCapabilities dc = new DesiredCapabilities();
dc.setJavascriptEnabled(false);
For firefox, tried
1) Setting up profile for firefox
2) Adding add-on - noScript.xpi
3) profile.setPreference("javascript.enabled", false);
4) Through UI, tried changing the flag - "javascript.enabled" in "about:config" to false. Here, opened firefox and gave "about:config" getting a warning - "This might void your warranty!". There is a button - "I'll be careful, I promise!" with id - warningButton. This button should be clicked to proceed further. To click this button, used driver.findElement(By.id("warningButton")).click(); but it not work.
All the above options are not working. Any advice will be helpful.

I don't know Java, but maybe a solution for Python 3 will help you.
in Python, you can use Options() instead of FirefoxProfile() to deactivate JavaScript:
from selenium.webdriver.firefox.options import Options
options = Options()
options.preferences.update({"javascript.enabled": False})
driver = webdriver.Firefox(options=options)
driver.get('about:config')
Maybe Java this:
FirefoxOptions options = new FirefoxOptions();
options.preferences.update({"javascript.enabled": False});
WebDriver driver = new FirefoxDriver(options);
driver.get('about:config')

You change the preference value using profile with lots of options:
DesiredCapabilities capabilities = new DesiredCapabilities();
// setCapability(SUPPORTS_JAVASCRIPT, javascriptEnabled);
capabilities.setJavascriptEnabled(false);
FirefoxBinary binary = new FirefoxBinary( new File( binaryPath ) );
FirefoxProfile profile = new FirefoxProfile();
//profile.setPreference("preferenceName", "Value");
profile.setPreference("javascript.enabled", false);
RemoteWebDriver driver = new FirefoxDriver(binary, profile, capabilities);
To view the preferences, you can visit the URL about:config
#See
Chrome driver to disable JavaScript issue
chromium-command-line-switches

Truse me this was random trial but works perfectly for me
from selenium import webdriver
options= webdriver.ChromeOptions()
chrome_prefs = {}
options.experimental_options["prefs"] = chrome_prefs
chrome_prefs["profile.default_content_settings"] = {"javascript": 2}
chrome_prefs["profile.managed_default_content_settings"] = {"javascript": 2}
driver = webdriver.Chrome("your chromedriver path here",options=options)
driver.get('https://google.com/search?q=welcome to python world')
Example image here:-https://i.stack.imgur.com/DdKZQ.png

As per Selenium 3.6 Java Client Release, the easiest way to disable Javascript in the browser would be to set the setJavascriptEnabled argument through an instance of DesiredCapabilities to False and merge it through an instance of FirefoxOptions as follows:
package demo;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
public class Q46883024_setJavascriptEnabled
{
public static void main(String[] args)
{
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
DesiredCapabilities dc = new DesiredCapabilities();
dc.setJavascriptEnabled(false);
FirefoxOptions op = new FirefoxOptions();
op.merge(dc);
WebDriver driver = new FirefoxDriver(op);
driver.get("https://google.com");
driver.quit();
}
}
While execution, the browser you are using may override the setJavascriptEnabled settings.

this works:
FirefoxOptions options = new FirefoxOptions();
options.addPreference("javascript.enabled", false);

This is how you can do it for Chrome in Java.
// import org.openqa.selenium.chrome.ChromeOptions;
ChromeOptions options = new ChromeOptions();
options.addArguments("user-agent=\"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)\"");
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_setting_values.javascript", 2);
options.setExperimentalOption("prefs", chromePrefs);
new ChromeDriver(options);
And it worked for me with ChromeDriver 2.41.578706. As a bonus I am also setting Googlebot as user-agent.
In case you need to do something with DesiredCapabilities you can also convert the options above to capabilities:
// import static org.openqa.selenium.chrome.ChromeOptions.CAPABILITY;
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(CAPABILITY, options);
new ChromeDriver(capabilities);

Related

How to set Chrome Options when using WebDriverManager?

I'm using Web driver manager to setup chrome driver. When setting up the driver I want to add some chrome options? How can I do it when using web driver manager?
I checked the WebDriverManager API but couldn't find any clue..
As of WebDriverManager 5.x you can instantiate the webDriver directly via the WebDriverManager builder with additional capabilities this way (in java) :
WebDriver driver;
//...
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless");
//...
//chromeOptions.addArguments(<another-option>);
//...
driver = WebDriverManager.chromedriver().capabilities(chromeOptions).create();
The capabilities method take a Capabilities as param.
Lucky we are, ChromeOptions implements the Capabilities interface.
public void WebDriverManagerTest()
{
//setup the chromedriver using WebDriverManager
WebDriverManager.chromedriver().setup();
//Create Chrome Options
ChromeOptions option = new ChromeOptions();
option.addArguments("--test-type");
option.addArguments("--disable-popup-bloacking");
DesiredCapabilities chrome = DesiredCapabilities.chrome();
chrome.setJavascriptEnabled(true);
option.setCapability(ChromeOptions.CAPABILITY, option);
//Create driver object for Chrome
WebDriver driver = new ChromeDriver(option);
//Navigate to a URL
driver.get("http://toolsqa.com");
//quit the browser
driver.quit();
}
Found the answer.. Check above!
This is the example code:
public class Test1{
#Test
public void WebDriverManagerTest()
{
//setup the chromedriver using WebDriverManager
WebDriverManager.chromedriver().setup();
//Create driver object for Chrome
WebDriver driver = new ChromeDriver();
//Navigate to a URL
driver.get("http://toolsqa.com");
//quit the browser
driver.quit();
}
}
from https://pypi.org/project/webdriver-manager/, pass it in after .install()
from selenium import webdriver
from webdriver_manager.opera import OperaDriverManager
options = webdriver.ChromeOptions()
options.add_argument('allow-elevated-browser')
options.binary_location = "C:\\Users\\USERNAME\\FOLDERLOCATION\\Opera\\VERSION\\opera.exe"
driver = webdriver.Opera(executable_path=OperaDriverManager().install(), options=options)

Getting error as "NoSuchSessionException" when trying to open an website through FirefoxProfile

I am running the below code, to open a URL. However, I am getting error as "NoSuchSessionException". Kindly suggest.
Is it because of the below versions I am using.
Selenium--> 3.12.0, Firefox Setup 50.0 and geckodriver-v0.21.0-win64
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
public class Gmail {
public static void main(String[] args){
System.setProperty("webdriver.gecko.driver", "D:\\Drivers\\geckodriver.exe");
FirefoxOptions options = new FirefoxOptions();
ProfilesIni allProf = new ProfilesIni();// all profiles
FirefoxProfile prof = allProf.getProfile("Abhi_Selenium");
options.setProfile(prof);
//FirefoxDriver driver = new FirefoxDriver(options);
WebDriver driver = new FirefoxDriver(options);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://gmail.com");
}
}
You have 2 ways to use a existing Firefox Profile to access a Web Application as follows:
Using DesiredCapabilities() and FirefoxOptions():
public class FirefoxProfile_dc_opt {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
ProfilesIni profile = new ProfilesIni();
FirefoxProfile testprofile = profile.getProfile("Abhi_Selenium");
DesiredCapabilities dc = DesiredCapabilities.firefox();
dc.setCapability(FirefoxDriver.PROFILE, testprofile);
FirefoxOptions opt = new FirefoxOptions();
opt.merge(dc);
WebDriver driver = new FirefoxDriver(opt);
driver.get("https://www.google.com");
}
}
Using FirefoxOptions():
public class FirefoxProfile_opt {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
ProfilesIni profile = new ProfilesIni();
FirefoxProfile testprofile = profile.getProfile("Abhi_Selenium");
FirefoxOptions opt = new FirefoxOptions();
opt.setProfile(testprofile);
WebDriver driver = new FirefoxDriver(opt);
driver.get("https://www.google.com");
}
}
Note: Ensure that you have already created a Firefox Profile as Abhi_Selenium before you trigger your Test.
Update
As you are still seeing the exception as no such session, perform the following upgradation/cleanup steps:
Upgrade JDK to recent levels JDK 8u181.
Upgrade Selenium to current levels Version 3.13.0.
Upgrade GeckoDriver to GeckoDriver v0.20.1 level.
Ensure GeckoDriver is present in the specified location.
Ensure GeckoDriver is having executable permission for non-root users.
Upgrade Firefox version to Firefox v61.0.1 levels.
Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.
(WindowsOS only) Use CCleaner tool to wipe off all the OS chores before and after the execution of your Test Suite.
(LinuxOS only) Free Up and Release the Unused/Cached Memory in Ubuntu/Linux Mint before and after the execution of your Test Suite.
If your base Web Client version is too old, then uninstall it through Revo Uninstaller and install a recent GA and released version of Web Client.
Take a System Reboot.
Execute your Test as a non-root user.
Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.
You can use FireFoxProfile class and FirefoxOptions class to set a profile.
FirefoxOptions options = new FirefoxOptions();
FirefoxProfile firefoxProfile = new FirefoxProfile(pathToProfile);
options.setProfile(firefoxProfile);
On the first look the path to firefox.exe is missing. There is my setup:
public class foo{
private static WebDriver driver;
#BeforeClass
public static void setUpClass() {
FirefoxOptions options = new FirefoxOptions();
ProfilesIni allProfiles = new ProfilesIni();
FirefoxProfile selenium_profile = allProfiles.getProfile("selenium_profile");
options.setProfile(selenium_profile);
options.setBinary("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
System.setProperty("webdriver.gecko.driver", "C:\\Users\\pburgr\\Desktop\\geckodriver-v0.20.0-win64\\geckodriver.exe");
driver = new FirefoxDriver(options);
driver.manage().window().maximize();}
// #Before, #After, #AfterClass and #Test
}

How to set proxy for Chrome browser in selenium using Java code

I am trying to run my selenium java code to test a webpage. But webpage is not loading because of network restrictions. When I set the proxy manually and hit the url in browser it works fine. Now I need to pass those proxy setting while running the selenium code. Please help me on this.
I tried below code, but still it shows the same error:
Proxy p=new Proxy();
// Set HTTP Port to 7777
p.setHttpProxy("www.abc.com:8080");
// Create desired Capability object
DesiredCapabilities cap=new DesiredCapabilities();
// Pass proxy object p
cap.setCapability(CapabilityType.PROXY, p);
// Open firefox browser
WebDriver driver=new ChromeDriver(cap);
Passing a Capabilities object to the ChromeDriver() constructor is deprecated. One way to use a proxy is this:
String proxy = "127.0.0.1:5000";
ChromeOptions options = new ChromeOptions().addArguments("--proxy-server=http://" + proxy);
WebDriver webDriver = new ChromeDriver(options);
Issue is resolved with below code -
Proxy proxy = new Proxy();
proxy.setHttpProxy("yoururl:portno");
proxy.setSslProxy("yoururl:portno");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("proxy", proxy);
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(capabilities);
Passing a Capabilities object to the ChromeDriver() constructor is deprecated. You can find new official doc here.
ChromeOptions chromeOptions = new ChromeOptions();
Proxy proxy = new Proxy();
proxy.setAutodetect(false);
proxy.setHttpProxy("http_proxy-url:port");
proxy.setSslProxy("https_proxy-url:port");
proxy.setNoProxy("no_proxy-var");
chromeOptions.setCapability("proxy", proxy);
driver = new ChromeDriver(chromeOptions);
DesiredCapabilities dc;
dc = DesiredCapabilities.chrome();
System.setProperty("http.proxyHost", "127.0.0.1");
System.setProperty("http.proxyPort", "9090");
System.setProperty("https.proxyHost", "127.0.0.1");
System.setProperty("https.proxyPort", "9090");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.addArguments("--disable-extensions");
dc.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(dc);
Another way of doing it:
boolean useProxy = true;
ChromeOptions options = new ChromeOptions().addArguments(
'--headless',
'--no-sandbox',
'--disable-extensions',
'--proxy-bypass-list=localhost');
if (useProxy) {
options.addArguments("--proxy-server=http://ProxyHost:8080");
}
WebDriver driver = new ChromeDriver(options);
See https://peter.sh/experiments/chromium-command-line-switches/ for more Chrome switches
Another way to set a proxy:
Proxy proxy = new Proxy();
proxy.setHttpProxy("<HOST:PORT>");
proxy.setSslProxy("<HOST:PORT>");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setCapability("proxy", proxy);
WebDriver webDriver = new ChromeDriver(chromeOptions);

Java. Selenium. Chromedriver. How can I enable and disable extensions?

I'm using this code to add own extension, but before load the page it automaticly disabels. How can I enable it?
ChromeOptions options = new ChromeOptions();
options.addArguments("load-extension=...");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
ChromeDriver driver = new ChromeDriver(capabilities);
To add an extension and disable the plugins with Chrome:
ChromeOptions options = new ChromeOptions();
Map<String, Object> preferences = new Hashtable<String, Object>();
options.setExperimentalOption("prefs", preferences);
// add an extension
options.addExtensions(new File("C:\\extension.crx"));
// disable flash and the PDF viewer
preferences.put("plugins.plugins_disabled", new String[]{
"Adobe Flash Player", "Chrome PDF Viewer"});
ChromeDriver driver = new ChromeDriver(options);
driver.get("https://www.google.co.uk");

How to set Proxy setting for Chrome in Selenium Java

I am able to set proxy settings for Firefox as below.
org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
proxy.setProxyType(ProxyType.MANUAL);
proxy.setHttpProxy(CONFIG.getProperty("hostname"));
proxy.setSslProxy(CONFIG.getProperty("hostname"));
proxy.setFtpProxy(CONFIG.getProperty("hostname"));
proxy.setSocksUsername(CONFIG.getProperty("username"));
proxy.setSocksPassword(CONFIG.getProperty("password"));
FirefoxProfile fp = new FirefoxProfile();
fp.setProxyPreferences(proxy);
driver = new FirefoxDriver(fp);
builder = new Actions(driver);
bckdbrowser = new WebDriverBackedSelenium(driver, ConfigReader.ENVIRONMENT_URL);
But I need to setup for Chrome as well.. Can any one assist me how to do ?
Thanks
Raj
You can try using the DesiredCapabilities class, like this:
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--proxy-server=http://user:password#proxy.com:8080"));
WebDriver driver = new ChromeDriver(capabilities);
Try this code:
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("network.proxy.type", ProxyType.AUTODETECT.ordinal());
WebDriver driver = new FirefoxDriver(profile);
here we have one more solution....it's worked for me

Categories

Resources