28

I am wondering how do I disable javascript when using selenium so I can test server side validation.

I found this article but I don't know what to really do. Like I make this javascript file then what?

http://thom.org.uk/2006/03/12/disabling-javascript-from-selenium/

Liam
  • 27,717
  • 28
  • 128
  • 190
chobo2
  • 83,322
  • 195
  • 530
  • 832
  • 2
    I wrote that article - unfortunately, that method only works inside the Selenium IDE extension in Firefox. Trying to disable JavaScript from the Selenium JavaScript runner (which I assume your NUnit tests use under the hood) would result in a security exception, so I'm afraid this method isn't of use to you. mfn's suggestions below are what I'd generally consider these days. – Thom Nov 04 '09 at 12:12

17 Answers17

24

This is a way to do it if you use WebDriver with FireFox:

FirefoxProfile p = new FirefoxProfile();
p.setPreference("javascript.enabled", false);
driver = new FirefoxDriver(p);
Rohit Arya
  • 6,751
  • 1
  • 26
  • 40
Assaf Shemesh
  • 2,078
  • 2
  • 18
  • 19
12

This is the simple answer, for python at least.

from selenium import webdriver

profile = webdriver.FirefoxProfile()
profile.set_preference("javascript.enabled", False);
driver = webdriver.Firefox(profile)
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Aaron Schif
  • 2,421
  • 3
  • 17
  • 29
  • 2
    Does not work in 2018, but the following answer does: https://stackoverflow.com/a/51681608/913569 – damd Aug 23 '18 at 13:02
10

Edit

In the meantime better alternatives did arise, please see the other answers e.g. https://stackoverflow.com/a/7492504/47573 .

Original answer

Other possibilities would be:

  • Write your application to support disabling JavaScript (yes, the web application).
    Sounds crazy? Isn't. In our development process we're doing exactly this, implementing features without JS until all are there, then spice up with JS. We usually provide a hook within all templates which can control from a single point to basically which JS off/on from the web application itself. And, yes, the application is hardly recognizable without JS enabled, but it's the best way to ensure things work properly. We even write Selenium tests for it, for both versions; NOJS and JS. The NOJS are so quickly implemented that they don't matter compared to what it takes to write sophisticated JS tests ...
  • Modify the appropriate browser profile to have JS disabled. I.e. for FF you can tell Selenium which profile to use; you can load this profile normally, disable JS in about:config and feed this profile as default profile to Selenium RC.
mark
  • 6,308
  • 8
  • 46
  • 57
  • Good answer for 2009, not so much for 2018. :) – damd Aug 23 '18 at 13:01
  • True, I see if I can delete it. Edit: nope, can't delete accepted answer and can't un-accept it. Edit2: edited answer to reference currently the ones with highest votes. Thx @damn – mark Aug 24 '18 at 05:21
  • In 2018 it works like this https://stackoverflow.com/a/53054654/7685008 – AtachiShadow Nov 05 '18 at 01:43
6

As of 2018 the above solutions didn't work for me for Firefox 61.0.1 and geckodriver 0.20.1.

And here is a solution which works.

from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

browser_exe = '/path/to/firefox/exe'
browser_driver_exe = '/path/to/geckodriver/exe'

firefox_binary = FirefoxBinary(browser_exe)

profile = webdriver.FirefoxProfile()
profile.DEFAULT_PREFERENCES['frozen']['javascript.enabled'] = False
profile.set_preference("app.update.auto", False)
profile.set_preference("app.update.enabled", False)
profile.update_preferences()

driver = webdriver.Firefox(
    executable_path=browser_driver_exe,
    firefox_binary=firefox_binary,
    firefox_profile=profile,
)

driver.get("about:config")

Now in the search bar type javascript and you should see the following.

enter image description here

Levon
  • 10,408
  • 4
  • 47
  • 42
  • 1
    You don't need to fiddle with binary paths, see this answer: https://stackoverflow.com/a/59227090/4592067 – imrek Dec 07 '19 at 14:41
4

The steps to use the script referenced above aren't to bad:

  1. Create the selenium "user-extensions.js" file as mentioned in the article you link.
  2. Select your "user-extensions.js" file in the Selenium preferences in Options->Options.
  3. Use the script by selecting the command "DisableJavascript" or "EnableJavascript" from the command list (or just type it manually).

For screen shot examples of steps 2 and 3 see: http://i32.tinypic.com/161mgcm.jpg

Update: For information about using user-extensions.js with Selenium RC try the following URL: http://seleniumhq.org/docs/08_user_extensions.html

coderjoe
  • 11,129
  • 2
  • 26
  • 25
  • Will this command show up in nunit. I write all my tests in nunit. – chobo2 Aug 17 '09 at 22:11
  • I believe so? I have not tried it so I can't be sure. Try the documentation I've added to my answer for information about using user-extensions.js with Selenium RC (which I assume you're using). – coderjoe Aug 17 '09 at 23:11
  • "http://i32.tinypic.com/161mgcm.jpg" where is the image? You should have added code snippet. – paul Feb 13 '18 at 11:10
4

The following works as of late 2019 with geckodriver 0.24.0 ( 2019-01-28) and Python 3.6.9 (and possibly other nearby versions.)

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
options.set_preference('javascript.enabled', False)
driver = webdriver.Firefox(options=options)
driver.get('about:config') # now you can filter for javascript.enabled and check

about:config shows false for javascript.enabled. enter image description here

imrek
  • 2,930
  • 3
  • 20
  • 36
  • Updated this answer b/c of ```DeprecationWarning: use options instead of firefox_options``` – imrek Feb 24 '21 at 17:27
2

Sometimes, profile.set_preference("javascript.enabled", False) does not work in Firefox. Use the below python to get around this:

 from pyvirtualdisplay import Display
 from selenium import webdriver
 from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
 from selenium.webdriver.common.keys import Keys
 from selenium.webdriver.common.action_chains import ActionChains


 profile = webdriver.FirefoxProfile()
 profile.update_preferences() #May or may not be needed

 display = Display(visible=0, size=(1200, 800))
 display.start()

 browser = webdriver.Firefox(profile)
 browser.get("about:config")
 actions = ActionChains(browser)
 actions.send_keys(Keys.RETURN)
 actions.send_keys("javascript.enabled")
 actions.perform()
 actions.send_keys(Keys.TAB)
 actions.send_keys(Keys.RETURN)
 actions.send_keys(Keys.F5)
 actions.perform()

 browser.quit()
 display.stop()
Alex Begun
  • 451
  • 3
  • 7
2

You can disable javascript using selenium at runtime by using the code:

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')

sample_Image

iampritamraj
  • 196
  • 2
  • 6
1

It looks like creating this file will give you the functions that you need to disable javascript for your test. You will call the "doDisableJavascript" function before you begin the test and the "doEnableJavascript" function when you want to enable it again.

Steven
  • 3,813
  • 2
  • 22
  • 27
  • how do I call it though? Like where am I calling it from? – chobo2 Aug 17 '09 at 02:32
  • 1
    with Selenium calling functions that you created would be the name of the function without the do e.g doDisableJavascript would be called from selenium with the command DisableJavascript – AutomatedTester Aug 17 '09 at 07:41
1

Set the browser name in the selenium settings to htmlunit.

This is a driver that has JavaScript disabled by default https://code.google.com/p/selenium/wiki/HtmlUnitDriver . The JavaScript required for selenium to interact with the page will still be able to run.

sloa
  • 113
  • 6
1

If you want solution with chrome, chromedriver, Python. This works for any version of chrome, assuming the layout for disabling JS remains same.

from selenium import webdriver
from selenium.webdriver import ActionChains
from time import sleep

path = 'chrome://settings/content/javascript'
options = webdriver.ChromeOptions()
options.binary_location = "/usr/bin/chromium"
driver = webdriver.Chrome(chrome_options=options)
driver.get(path)
# clicking toggle button
sleep(1)
ActionChains(chrome_driver).send_keys(Keys.TAB).send_keys(Keys.TAB).send_keys(Keys.ENTER).perform()
driver.get('https://www.google.com/')
1

I was trying to solve this problem and found this blog but the first post has a link that is no longer valid. But I finally found the code to place inside the user-extensions.js that works. Here it is:

Selenium.prototype.doDisableJavascript = function() {
    setJavascriptPref(false);
};

Selenium.prototype.doEnableJavascript = function() {
    setJavascriptPref(true);
};

function setJavascriptPref(bool) {
   prefs = Components.classes["@mozilla.org/preferences-service;1"]
           .getService(Components.interfaces.nsIPrefBranch);
   prefs.setBoolPref("javascript.enabled", bool);
}

Hope this save the time it took me to find it.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Carlos
  • 11
  • 1
0

You don't need to disable JavaScript. If you fill out your form you can use JavaScript to submit your form e.g. use runScript and window.document.forms[0].submit().

Whenever you call submit() directly on a form, the form is submitted directly to the server, there is no onsubmit event fired, and therefore, no client-side validation. (Unless your form action is something like javascript:validateForm(), in which case your system doesn't work when JavaScript is disabled).

Lee Kowalkowski
  • 11,591
  • 3
  • 40
  • 46
0

You can disable the JavaScript during runtime by using the code:

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();
Manu
  • 2,251
  • 19
  • 30
0

I substitute this parameter in the Options () configuration, I don’t remember from whom I spied it (for someone on SO), but it works:

from selenium.webdriver.firefox.options import Options

options = Options()
options.preferences.update({'javascript.enabled': False})
browser = webdriver.Firefox(options=options)

Selenium 3.14 and Firefox 63.0

AtachiShadow
  • 381
  • 4
  • 13
0

I was trying to achieve the same in Chrome (in 2020), spent too much time on this, the final solution was to automate the disabling of Javascript in Chrome settings page.

To do that, i was writing a function to get Shadow DOM elements from Chrome with Javascript by the provided path, until i reached the level where the control i had to click on was located.

This is the function i was using for that (i found the solution here and modified a bit):

public IWebElement GetElementFromShadow(string[] Path)
{
    IWebElement root = null;
    foreach (string act in Path)
    {
        if (root == null)
        {
            root = (IWebElement)((IJavaScriptExecutor)_driver).ExecuteScript("return document.querySelector(arguments[0]).shadowRoot", act);
        }
        else
        {
            root = (IWebElement)((IJavaScriptExecutor)_driver).ExecuteScript("return arguments[0].querySelector(arguments[1]).shadowRoot", root, act);
        }
    }
    return root;
}

Then in the test definition, i created an array of strings with the shadow dom path i found in DevTools, used the function above to get the WebElement from inside the nested shadowRoot, so i could click on it with Selenium:

string[] DisableJSShadowRootPath = { "settings-ui", "settings-main", "settings-basic-page", "settings-privacy-page", "category-default-setting", "settings-toggle-button", "cr-toggle" };
IWebElement control = _JSsettings.GetElementFromShadow(DisableJSShadowRootPath);
control.FindElements(By.TagName("span")).Where(e => e.GetAttribute("id") == "knob").First().Click();

The path can be easily found at the bottom ribbon of Chrome DevTools:

enter image description here

Barnebyte
  • 161
  • 5
0

This solution applies to Selenium for Python.

In case javascript.enabled doesn't work, you can use selenium-wire to block javascript requests. Note that inline scripts will still run. You can also block other requests like stylesheets and images using the request path's file extension, or the Accept header.

from seleniumwire import webdriver

def interceptor(request):
    if request.path.endswith('.js'):
        request.abort()

driver = webdriver.Firefox()
driver.request_interceptor = interceptor
# driver.get()

selenium-wire docs
selenium-wire on PyPi

Tested using

selenium==4.1.0
selenium-wire==4.6.2
aphilas
  • 2,066
  • 1
  • 14
  • 9