I get a call to OnBeforeResourceLoad with the URL https://www.ticketmaster.co.uk/api/cookies and identifier 902363, but never got a call to OnResourceLoadComplete with the same identifier (nor the same URL). I understand OnResourceLoadComplete should be called for all requests, so I wonder if this is a bug (probably unrelated to the one I mentioned before about browsers not being fully created sometimes).
@jsoldi I'd suggest moving the conversation over to https://magpcss.org/ceforum/index.php as the behaviour is entirely implemented in CEF/Chromium
.
It sounds like a bug to me, though the CEF
maintainer will hopefully be able to confirm.
hello what i would like to do is add a chrome extension to a cefsharp window is that possible?
@hawke0777 Already asked at https://github.com/cefsharp/CefSharp/discussions/3869
Please just ask your question once and wait for a reply, thanks.
It tried it with this example in a seperated class. But the problem is it just enters the credentials by itself and the login window never shows. I really searched the internet for hours and can't find anything that helped me right now.
I use this code on a WindowsForms Application at Visual Studio Express 2012
protected override bool GetAuthCredentials(IWebBrowser chromiumWebBrowser, IBrowser browser, string originUrl, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
{
//NOTE: We also suggest you explicitly Dispose of the callback as it wraps an unmanaged resource.
//Example #1
//Spawn a Task to execute our callback and return true;
//Typical usage would see you invoke onto the UI thread to open a username/password dialog
//Then execute the callback with the response username/password
//You can cast the IWebBrowser param to ChromiumWebBrowser to easily access
//control, from there you can invoke onto the UI thread, should be in an async fashion
//Load https://httpbin.org/basic-auth/cefsharp/passwd in the browser to test
Task.Run(() =>
{
using (callback)
{
if (originUrl.Contains("https://httpbin.org/basic-auth/"))
{
var parts = originUrl.Split('/');
var username = parts[parts.Length - 2];
var password = parts[parts.Length - 1];
callback.Continue(username, password);
}
}
});
return true;
//Example #2
//Return false to cancel the request
//callback.Dispose();
//return false;
}
@jsoldi Hello, I did the test with my own solution and I do get the OK response. I get that response:
HTTP/1.1 200 OK
Accept-Ranges: bytes
Cache-Control: no-store, must-revalidate, max-age=0
Connection: keep-alive
Content-Length: 2
Content-Security-Policy: frame-ancestors 'none';
Content-Type: text/plain;charset=UTF-8
Date: Thu, 04 Nov 2021 14:19:10 GMT
Server: iccp-backend
Set-Cookie: BID=HE0lJVpvUyFA2YqAfp73OBvOQE_DP3b5dMTA-BsfC_144uocKqPFuecprug5WeDR0LvaZe0fRnLct8jc; Path=/; Domain=.ticketmaster.co.uk; Max-Age=31536000; Expires=Fri, 04 Nov 2022 14:19:09 GMT; Secure; HttpOnly; SameSite=None
Set-Cookie: SID=mBvo1ICwHIDHJ7ygTfmXZKo-pQhKBaN59DST8zQm-mMGguZh1uhGfWyWogc4tUQZtfLIRyA-GpfZXIsb; Path=/; Domain=.ticketmaster.co.uk; Secure; HttpOnly; SameSite=None
Set-Cookie: sticky=ABDC; Domain=.ticketmaster.co.uk; Path=/
Set-Cookie: ab-myacc=iccp; Domain=.ticketmaster.co.uk; Path=/
TMPS-Correlation-Id: 6acdc200-cfd3-4228-86b6-75baac67f432
Vary: Accept-Encoding
Via: 1.1 varnish, 1.1 varnish
X-Cache: MISS, MISS
X-Cache-Hits: 0, 0
X-Content-Type-Options: nosniff
X-Fastly: ICCP-GLOBAL-PROD
X-Frame-Options: Deny
X-Page-Type: api
X-Served-By: cache-yyz4551-YYZ, cache-yyz4551-YYZ
X-TM-BID: jP4ADlbUvBzV7CMrCi8sZZ0aTGYaq4/9T/PW0I/Pdg97zhmtuvdopHndJQpIBMt6/cqzy/49Ce8Hs6iomUsQbMSQIslXMpOSMuJTsb3L4DAyNdU9MXeDeRD8/v6XDPrQ
X-TM-SID: ggtQEQil+Z6ga0Q8OZmH33k7VbIw4COS/Nh2zKYji9j0vGNzVwUimQa3Vt2wifu2Gg8LBa71VvLqEwWLHc6Zq+qdJo9W0vmwbNXLiX6saTq4+z7Bs6GEfWrxQ55sI9W8
X-Timer: S1636035550.816619,VS0,VE226
X-XSS-Protection: 1
x-d-debug-state: SUCCESS
My theory is that along the many overrides and interception the code is not right. It happened to me many times as I use a lot of customized event handlers and overrides.
One thing I notice in your code is that you keep reusing the same custom request handler. In my case I create a new one each time to ensure that each request has its own context and is not overwrite by a concurrent request since it shares the same object. In the examples I saw it was always a new instance. I think you should start with that, let me know if it works.
OK done. I also mention there that this specific request looks "weird" on Chrome too, so I wonder if this is a Chromium bug.
@jsoldi Possibly a Chromium BUG
, it's also possible that CEF
ignores the response. You'd need to debug the source to find out for sure.
https://github.com/chromiumembedded/cef/blob/a7bbd8a62bfc91b0d53eeef8d07b64a5ed719a5f/libcef/browser/net_service/resource_request_handler_wrapper.cc#L975
What's changed on the CefSharp lifecycle or maybe I'm going smth wrong?
Here's the code - https://pastebin.com/EcZYssWD, hang on line 109.
@serhiy1994 Start by checking the log file. See https://github.com/cefsharp/CefSharp/wiki/Trouble-Shooting#log-file
I need more information before I can speculate as to what's going on.
OnResourceResponse
with a 200 response, but no call to OnResourceLoadComplete
. The reason is that the script calls fetch
but doesn't call text
or json
to get the response body, so the request hangs there forever. I'm not sure if this is the expected behavior thought, since I've noted that doing fetch
on HTML documents automatically pulls the content body regardless of whether you call text
or not, but it seems that it doesn't do that with JSON requests, so I'm still not sure if this is a bug or not. I don't think CEF is ignoring the request because the error code on OnResourceResponse
is None
and one of the conditions to ignore it is for the error code to be ERR_ABORTED
, unless it changes to aborted later? I'll see if I can debug that and report back.
@larouchefrancois I tried what you suggested:
public class MyRequestHandler : RequestHandler
{
protected override IResourceRequestHandler GetResourceRequestHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool isNavigation, bool isDownload, string requestInitiator, ref bool disableDefaultHandling)
{
return new MyResourceHandler();
}
}
public class MyResourceHandler : ResourceRequestHandler
{
protected override bool OnResourceResponse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response)
{
System.Diagnostics.Debug.WriteLine($"OnResourceResponse [{request.Identifier}]: {request.Url}");
return base.OnResourceResponse(chromiumWebBrowser, browser, frame, request, response);
}
protected override CefReturnValue OnBeforeResourceLoad(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
{
System.Diagnostics.Debug.WriteLine($"OnBeforeResourceLoad [{request.Identifier}]: {request.Url}");
return base.OnBeforeResourceLoad(chromiumWebBrowser, browser, frame, request, callback);
}
protected override void OnResourceLoadComplete(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
{
System.Diagnostics.Debug.WriteLine($"OnResourceLoadComplete [{request.Identifier}]: {request.Url}");
base.OnResourceLoadComplete(chromiumWebBrowser, browser, frame, request, response, status, receivedContentLength);
}
}
But only got these two:
OnBeforeResourceLoad [863083]: https://www.ticketmaster.co.uk/api/cookies
OnResourceResponse [863083]: https://www.ticketmaster.co.uk/api/cookies
No call to OnResourceLoadComplete
except after I navigated away again, I guess because CEF disposed the request:
OnResourceLoadComplete [863083]: https://www.ticketmaster.co.uk/api/cookies
So I wonder if you're doing something else that I'm not. I literally just downloaded the latest version of CefSharp and added the code. I originally thought it worked but it was because I added some code to ignore this specific request which then forgot to remove.
ticketmaster.co.uk
and that's when you got the call to OnResourceLoadComplete
?
CefSharp in a winforms C# application
@citylogic-au What version are you using?
Users are complaining of high CPU usage resulting in high fan noise
How does Chrome
at the same version behave on the same machine?
Does anyone have any suggestions on getting optimal performance for rendering SVG
Performance is largely tied to the Chromium
version. I'm not aware of any SVG
rendering specific options. Try searching in the Chromium
issue tracker.
As a general debugging step you can load chrome://gpu/
in both Chrome
and CefSharp
to compare the GPU Acceleration
.
is there a way to change the region / location to South Africa only in CefSharp
@JaredDrakeZA You can change the following:
How does the website determine region? IP Address? Accept-Language header? timezone?
Secondly, how to disable Cloudflare Security Check (CAPTCHA) when browsing the website.
If CloudFlare
has a server side component to it's captcha then it's unlikely you can disable it.
I'd search for something like headless chrome cloudflare
.
https://bitbucket.org/chromiumembedded/cef/issues/3200/sso-throwing-onloaderrors-with. A trial fix seems to be available today (2021-11-10).
@buhtig0815 I've updated master
with the latest beta CEF
build and you can test out the fix using a CI
nuget package available from https://www.myget.org/gallery/cefsharp
Changes are included in 96.0.120-CI4308
If the problem still reproduces then if you have an example url that reproduces the problem then it's probably worth posting on the bitbucket
issue for testing purposes.
Hello, firstly, it has been awhile but I am grateful to see this project still being maintained @amaitland - thank you.
I noticed it is now possible to take screenshots via DevTools
, which is awesome. However, I am trying to capture a full page screenshot (that is, capture everything beyond the current viewport) but my results always return a screenshot of the current viewport (that is, what the user is currently looking it).
My code is based on the example in the docs: https://github.com/cefsharp/CefSharp/wiki/General-Usage#screenshots but I note an optional (and experimental) boolean parameter is available captureBeyondViewport
. Regardless, I end up with a screenshot of just the current view. Is it possible to take a fullpage screenshot via this method?
using (var devToolsClient = uiTabbedBrowserControl.CurrentTab.Browser.GetDevToolsClient())
{
var result = await devToolsClient.Page.CaptureScreenshotAsync(null, null, null, null, true);
File.WriteAllBytes(@"C:\Users\joe\Desktop\test1.png", result.Data);
}
I am rusty around the edges, so am happy to concede I am missing something blindingly obvious. Thank you for any help, as always.
Version: WinForms, 95.7.14
Hello, firstly
Hi @joe-williams-cccu, it has been a while :smile:
it has been awhile but I am grateful to see this project still being maintained
yep, still going :smile:
I am rusty around the edges, so am happy to concede I am missing something blindingly obvious.
The DevTools
protocol in CefSharp
is generated, provides raw access to the underlying protocol. I am working on a cutdown version of PuppeteerSharp
specifically for CefSharp
that will provide a nicer API
for using the DevTools
protocol. See https://github.com/cefsharp/PuppeteerSharp.Embedded#puppeteersharp-embedded-cefsharp (There's no official nuget package as yet).
Anyway back to the question. the upstream
documentation is actually fairly lacking. Little bit of research and it looks like you need to provide the clip
param also. See https://bugs.chromium.org/p/chromium/issues/detail?id=1198576#c17
Tested with WinForms
version 95.7.141
and the following appears to work:
using (var devToolsClient = browser.GetDevToolsClient())
{
//Get the content size
var layoutMetricsResponse = await devToolsClient.Page.GetLayoutMetricsAsync();
var contentSize = layoutMetricsResponse.ContentSize;
var viewPort = new Viewport()
{
Height= contentSize.Height,
Width = contentSize.Width,
X = 0,
Y = 0,
Scale = 1
};
// https://bugs.chromium.org/p/chromium/issues/detail?id=1198576#c17
var result = await devToolsClient.Page.CaptureScreenshotAsync(clip: viewPort, fromSurface:true, captureBeyondViewport: true);
return result.Data;
}
Hi, I have following code
private async Task ExecuteAsync(Func<ChromiumWebBrowser, Task> action)
{
using var browser = new ChromiumWebBrowser(new HtmlString(htmlContent));
var loadResponse = await browser.WaitForInitialLoadAsync();
if (loadResponse.Success)
{
await action(browser);
}
else
{
logger.LogError(
"Chromium browser failed to load with error code: {ErrorCode}",
loadResponse.ErrorCode);
}
browser.Dispose();
}
When called, application hangs on var loadResponse = await browser.WaitForInitialLoadAsync();
indefinitely.
If I remove this line exception is thrown instead that says:
System.Exception: 'The ChromiumWebBrowser instance creates the underlying Chromium Embedded Framework (CEF) browser instance in an async fashion.
The undelying CefBrowser instance is not yet initialized. Use the IsBrowserInitializedChanged event and check the IsBrowserInitialized property to
determine when the browser has been initialized.'
I have also tried subscribing to lifecycle events but they were never raised.
What should I do in this scenario?
@amaitland In our application, we use CefSharp Winforms library and we open multiple instances CefSharp browsers in different tabs. There is an option to close the tab and the expectation is the CefSharp browser instance should get killed and it happens that way.
But, in some cases what we observe is even after all the tabs are closed in the application, still some of the CefSharp browser instances show up in the task manager. Is possible to happen from the runtime point of view?
I have a problem with cors after updating cefsharp.winforms from 79.1.360 to 95.7.141.
Uncaught DOMException: Blocked a frame with origin "akela://" from accessing a cross-origin frame.
at Player._onLoadWorskpace (webpack:///./pages/player/controller.js?:462:38)
at HTMLIFrameElement.dispatch (akela://common/assets/js/jquery-latest.min.js:2:41772)
at HTMLIFrameElement.y.handle (akela://common/assets/js/jquery-latest.min.js:2:39791)
Headers.Add("Access-Control-Allow-Origin", "*");
After update i had to remove (because of the changes):
this.browser.BrowserSettings.FileAccessFromFileUrls = CefState.Enabled;
this.browser.BrowserSettings.UniversalAccessFromFileUrls = CefState.Enabled;
this.browser.BrowserSettings.WebSecurity = CefState.Enabled;
instead i included:
cefSettings.CefCommandLineArgs.Add("allow-universal-access-from-files");
cefSettings.CefCommandLineArgs.Add("allow-file-access-from-files");
//i thought this will help solve the issue (as a last resort, not really comfortable with this solution), but for some reason cors problem is still there (it feels like it is ignored?)
// cefSettings.CefCommandLineArgs.Add("disable-web-security");
//cefSettings.CefCommandLineArgs.Add("disable-features", "OutOfBlinkCors");
I am lost at what I can do to make it work again. I have a feeling that my command line arguments are being ignored maybe (at least disable-web-security
)? Is there a way to check that those arguments are applied properly?
Hello all, hopefully it's an easy one.
I was wondering why some ajax requests are not detected in OnBeforeBrowse when I click in the browser link?
The specific case is as followed in client side code:
<a href="#" onclick="new Ajax.Updater('sidebar', '/account/signup_form', {asynchronous:true, evalScripts:true}); return false;"><< Register</a>
I can detect many types of XHR but not that one.
I'm using CefSharp 94.4.50.
@chaitanyajun12 Calling ChromiumWebBrowser.Dispose
should close the associated CefSharp.BrowserSubProcess.exe
render process instance. Starting in version 95
there is a spare render process that will be closed when Cef.Shutdown
is called.
Make sure you are correctly disposing of the browser.
I have a feeling that my command line arguments are being ignored maybe
@dadloo If you load chrome://version/
in the ChromiumWebBrowser
instance you should see the command line args
cefSettings.CefCommandLineArgs.Add("disable-features", "OutOfBlinkCors");
@dadloo From memory it's no longer possible to disable OutOfBlinkCors
, and a quick check confirms it.
https://magpcss.org/ceforum/viewtopic.php?f=6&t=18157