我正在使用 CefSharp 进行网页的离屏渲染,我想在截取渲染页面的屏幕截图之前执行 JavaScript 代码。
不幸的是,在某些网页(例如 https://github.com/ )上使用 browser.EvaluateScriptAsync("document.body.scrollHeight")
会导致以下错误:
Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src assets-cdn.github.com".
@ undefined:0:-1
这显然是由于内容安全策略 header 而发生的。
根据this answer ,可以禁用 Firefox 中的安全性。是否也可以在 CEF 中禁用它?或者是否可以通过其他方式执行脚本?
最佳答案
我刚刚遇到了同样的问题,使用 cefsharp 在我不拥有的网站上测试一些 javascript 代码。最近的 cefsharp 版本拒绝使用 ExecuteJavascriptAsync() 处理此类请求。
我以残酷的方式解决了我的问题,使用代理来禁用 CSP 检查。 代理将元标记 http-equiv="content-security-policy"替换为虚拟标记以禁用它。请注意,我没有更改字符串长度以避免副作用,例如更改“Content-Length”http header 。
代理:https://github.com/justcoding121/Titanium-Web-Proxy
在这里你可以找到我的快速而肮脏的代码。
启动代理的代码:
var proxyServer = new ProxyServer();
var explicitEndPoint = new ExplicitProxyEndPoint(IPAddress.Any, 8123, true)
{
};
// An explicit endpoint is where the client knows about the existence of a proxy
// So client sends request in a proxy friendly manner
proxyServer.AddEndPoint(explicitEndPoint);
proxyServer.Start();
proxyServer.BeforeResponse 事件:
private async Task Proxy_BeforeResponse(object sender, Titanium.Web.Proxy.EventArguments.SessionEventArgs e)
{
if (e.HttpClient.Response.Headers.Headers.ContainsKey("Content-Type"))
{
if (e.HttpClient.Response.Headers.Headers["Content-Type"].Value.Contains("text/html"))
{
string bodyString = await e.GetResponseBodyAsString();
e.SetResponseBodyString(bodyString.Replace("content-security-policy", "content-unsecure-policy"));
}
}
}
cefsharp 切换为使用代理:
cefSettings.CefCommandLineArgs.Add("proxy-server", "http://localhost:8123");
关于javascript - 在 CEF/CefSharp 中禁用 "Content Security Policy",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37978454/