I will provide my solution in Java. There is always an option to simulate toggling javascript on/off in the chrome settings. The trick is to create a custom WebDriver class that implements WebDriver.
To begin, you could save current page URL so the driver can know where to come back after toggling javascript, afterwards you should keep track about javascript current state - and if current javascript state differentiates from passed enable argument then proceed with toggling javascript. The button for toggling javascript works on the middle of screen with radius of at least 60% of the page, so the X axis will always work correctly, while Y axis is an approximation which should work most of the time.
Here is the implementation:
public class IWebDriver implements WebDriver {
private boolean enableJavascript;
private WebDriver driver;
public IWebDriver() {
// Javascript is enabled by default
this.enableJavascript = true;
this.driver = new ChromeDriver();
}
public void setEnableJavaScript(boolean enable) throws Exception {
/* Save current page URL */
String currentUrl = getCurrentUrl();
/* Toggle javascript if passed argument javascript state differentiates from actual javascript state */
if (this.enableJavaScript != enable) {
this.driver.navigate().to("chrome://settings/content/javascript");
Dimension d = driver.manage().window().getSize();
int x = d.getWidth() / 2;
int y = (int) ((float) d.getHeight() * 0.123f);
Actions actions = new Actions(this.driver);
actions.moveByOffset(x, y).click().build().perform();
// change current javascript enabled state
this.enableJavaScript = !this.enableJavaScript;
}
/* Get back to the original URL */
this.driver.navigate().to(currentUrl);
}
public boolean isEnableJavascript() {
return this.enableJavascript;
}
//Getters, setters and overridden methods...
}