Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium WebDriver (Firefox): dynamically disable Javascript

I know I can use Firefox profiles to disable JavaScript. For example, see Enable/disable javascript using Selenium WebDriver.

However, I have a case where I need JavaScript to be enabled in order for me to log in to a page, but then I want JavaScript to be disabled after I am logged in, so that when I do page_source, it returns the DOM as if JavaScript has not run. The key is that the login page requires JavaScript. Is it possible to dynamically control whether JavaScript is on or off in Selenium WebDriver?

like image 410
user1002119 Avatar asked Jun 19 '15 19:06

user1002119


1 Answers

I suggest not to dynamically disable the javascript as most functionality of webdriver is written in javascript and so it may give unexpected results sometimes. Better to use Firefox Profiles to disable it, but I have written the code that may help you disable it during runtime.

WebDriver driver = new FirefoxDriver();
driver.get("about:config");
Actions act = new Actions(driver);
act.sendKeys(Keys.RETURN).sendKeys("javascript.enabled").perform();
Thread.sleep(1000);
act.sendKeys(Keys.TAB).sendKeys(Keys.RETURN).sendKeys(Keys.F5).perform();

If using Selenium IDE, you can refer: http://thom.org.uk/2006/03/12/disabling-javascript-from-selenium/ as well.

like image 68
Manu Avatar answered Sep 22 '22 09:09

Manu