SecurityError:CSSStyleSheet.cssRules getter:使用 Selenium Firefox 读取 CSS 样式表时不允许访问跨源样式表错误

问题描述 投票:0回答:2

我正在使用带有 Java 和 Chrome/Firefox 驱动程序的 Selenium。

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

尝试阅读 CSS 样式表

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

我收到以下错误:

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

使用 chrome 驱动程序我得到错误

error reading property
.

我正在尝试获取页面的

document.styleSheets
,但由于 CORS 规则我不能。如何禁用它们?

java selenium firefox cross-domain selenium-firefoxdriver
2个回答
2
投票

好像打错了。而不是

documnent
可能你的意思是
document
。如此有效,您的代码行将是:

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

但是,这个错误信息...

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

...意味着 cssRules

getter()
方法被阻止访问 cross-origin 样式表.


详情

根据 Unable to access cssRules property DOMException: "CSSStyleSheet.cssRules getter: Not allowed to access cross-origin stylesheet" 即使您的应用程序可能没有任何 cross-origin 样式表 仍然以防万一您正在使用,这些跨源样式表Ghostery浏览器扩展注入。

所以一个快速的解决方案是禁用 Ghostery 扩展 来解决问题。


0
投票

您的网页项目可能会在加载文档内联 css 之前通过 javascript 为您的文档加载 css。您甚至可能将您的 css 放置为

<link src"cssfile.css">
如果已经加载了其他 css,从 css 的角度来看,它已经可以被视为跨源访问。那么从这里您的文档仍然没有样式表 javascript 可以正确访问。因此,您尝试在此类文档 css 甚至存在之前修改 css 规则,因此失败并抛出跨域访问安全错误,因为浏览器自己的本机样式表随后被尝试修改,这当然是您不想要的,也是如此不工作。

解决

a) 在特定错误抛出 js 开始处理之前,对文档 css 进行排序。

b) 给你的文档一个样式表来使用,即使它是空的。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            * {} /* empty stylesheet0 solves the problem */
        </style>
        <!-- ..because the following line -->
        <link rel="stylesheet" type="text/css" href="external.css">
        <!-- does not create a document stylesheet on its own -->
        <script src="stylesheet_manipulating.js"></script>
    </head>
    <body>
    </body>
</html>

© www.soinside.com 2019 - 2024. All rights reserved.