问题
I am using CEFsharp browser and determine the page finish loading with LoadingStateChanged event but it fires many times.
I need it to fire only once the page has fully loaded, how can this be done?
private async void Browser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
if (!e.Browser.IsLoading)
{
await Task.Run(async () =>
{
await Task.Delay(3000);
});
try
{
MessageBox.Show("Page has been loaded");
}
catch (Exception ex)
{
}
}
}
回答1:
For those interested, I use (a variation of) the following workaround. I keep track of the number of requests made and only do an action if there is a newer request. For my case, this seems to work fine. However I can imagine that the browser actually still does something and you would sometimes need to wait for the last time it finishes.
using CefSharp;
public class RequestHandler : IRequestHandler
{
//left all the irrelevant IRequestHandler methods out of this example code, but you'll need to implement them
public int NrOfCalls { get; set; }
public bool OnBeforeBrowse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect)
{
NrOfCalls++;
return false;
}
}
public class Handle
{
private RequestHandler _requestHandler;
private IWebBrowser _browser;
private int previousRequestNrWhereLoadingFinished = -1;
public Handle()
{
_requestHandler = new RequestHandler();
_browser.RequestHandler = _requestHandler;
}
private void _browser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
// Check if page has finished loading
if (!e.IsLoading)
{
//sometimes this is called multiple times for one request, we will only do something if it comes from a newer request than the previous action
if (previousRequestNrWhereLoadingFinished < _requestHandler.NrOfCalls)
{
previousRequestNrWhereLoadingFinished = _requestHandler.NrOfCalls;
ThisMethodWillOnlyBeCalledOncePerRequest();
}
}
}
}
回答2:
These days its really simple. Put for example these 2 lines of Code in ur Form_Load:
browser = new ChromiumWebBrowser();
(browser).FrameLoadEnd += Browser_FrameLoadEnd;
Then add the required methode:
async void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{ // Jumps in here when the page is fully loaded:
if (e.Frame.IsMain)
{
if (e.Url.Contains("whatever you need"))
{
// Call a methode or something else.
}
}
}
来源:https://stackoverflow.com/questions/42978669/cef-sharp-browser-wait-till-website-fully-loaded