'SecurityError: CSSStyleSheet.cssRules getter: Not allowed to access cross-origin stylesheet error while reading CSS stylesheet using Selenium Firefox

I am using Selenium with Java and Chrome/Firefox driver.

FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("javascript.enabled", true);
profile.setPreference("security.fileuri.strict_origin_policy", false);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability(FirefoxDriver.PROFILE, profile);
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities.setCapability("acceptInsecureCerts",true);
FirefoxOptions options = new FirefoxOptions();
options.addCapabilities(capabilities);
WebDriver webDriver = new FirefoxDriver(options);

Trying to read the CSS stylesheet

JavascriptExecutor js = ((JavascriptExecutor) driver);
Object properties = js.executeScript("return document.styleSheets");

I get the following error:

Exception in thread "main" org.openqa.selenium.WebDriverException: SecurityError: CSSStyleSheet.cssRules getter: Not allowed to access cross-origin stylesheet

With a chrome driver I get the error error reading property.

I am trying to get the document.styleSheets of a page, but I can't because of CORS rules. How to disable them?



Solution 1:[1]

Seems like a typo. Instead of documnent possibly you meant document. So effectively, your line of code will be:

Object properties = js.executeScript("return document.styleSheets");

However, this error message...

Exception in thread "main" org.openqa.selenium.WebDriverException: SecurityError: CSSStyleSheet.cssRules getter: Not allowed to access cross-origin stylesheet

...implies that the cssRules getter() method was blocked from accessing the cross-origin stylesheet.


Details

As per the discussion in Unable to access cssRules property DOMException: "CSSStyleSheet.cssRules getter: Not allowed to access cross-origin stylesheet" even though your application may not have any cross-origin stylesheets still in case you are using , these cross-origin stylesheets are injected by the Ghostery browser extension.

So a quick solution would be to disable the Ghostery extension to solve the issue.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1