Skip to content
Simon Hatt edited this page Feb 10, 2016 · 3 revisions

RequestHandler callbacks

Implement this interface to handle events related to browser requests.

For an example of how to implement handler see cefpython.CreateBrowser(). For a list of all handler interfaces see API > Client handlers.

The RequestHandler tests can be found in the wxpython.py script.

CEF 3

void OnBeforeBrowse(Browser browser, Frame frame, Request request, bool isRedirect)

Called on the UI thread before browser navigation. Return true to cancel the navigation or false to allow the navigation to proceed. The |request| object cannot be modified in this callback. DisplayHandler.OnLoadingStateChange will be called twice in all cases. If the navigation is allowed LoadHandler.OnLoadStart and OnLoadEnd will be called. If the navigation is canceled LoadHandler.OnLoadError will be called with an |errorCode| value of ERR_ABORTED.

bool OnBeforeResourceLoad(Browser browser, Frame frame, Request request)

Called on the IO thread before a resource request is loaded. The |request| object may be modified. To cancel the request return true otherwise return false.

ResourceHandler GetResourceHandler(Browser browser, Frame frame, Request request)

Called on the IO thread before a resource is loaded. To allow the resource to load normally return None. To specify a handler for the resource return a ResourceHandler object. The |request| object should not be modified in this callback.

The ResourceHandler object is a python class that implements the ResourceHandler callbacks. Remember to keep a strong reference to this object while resource is being loaded.

The GetResourceHandler example can be found in the wxpython-response.py script on Linux.

void OnResourceResponse()

Not yet available in CEF 3 (see CEF Issue 515), though it can be emulated, see the comment below.

You can implement this functionality by using ResourceHandler and WebRequest / WebRequestClient. For an example see the _OnResourceResponse() method in the wxpython-response.py script.

void OnResourceRedirect(Browser browser, Frame frame, string oldUrl, list& newUrlOut)

Called on the IO thread when a resource load is redirected. The |oldUrl| parameter will contain the old URL. The newUrlOut[0] parameter will contain the new URL and can be changed if desired.

bool GetAuthCredentials(Browser browser, Frame frame, bool isProxy, string host, int port, string realm, string scheme, AuthCallback callback) {

Called on the IO thread when the browser needs credentials from the user. |isProxy| indicates whether the host is a proxy server. |host| contains the hostname and |port| contains the port number. Return true to continue the request and call AuthCallback::Continue() when the authentication information is available. Return false to cancel the request.

The AuthCallback object methods:

  • void Continue(string username, string password)
  • void Cancel()

bool OnQuotaRequest(Browser browser, string originUrl, long newSize, QuotaCallback callback)

Called on the IO thread when javascript requests a specific storage quota size via the webkitStorageInfo.requestQuota function. |originUrl| is the origin of the page making the request. |newSize| is the requested quota size in bytes. Return true and call QuotaCallback::Continue() either in this method or at a later time to grant or deny the request. Return False to cancel the request.

The QuotaCallback object methods:

  • void Continue(bool allow)
  • void Cancel()

CookieManager GetCookieManager(Browser browser|None, string mainUrl)

Called on the IO thread to retrieve the cookie manager. |mainUrl| is the URL of the top-level frame. Cookies managers can be unique per browser or shared across multiple browsers. The global cookie manager will be used if this method returns None.

To successfully implement separate cookie manager per browser session, you have to set ApplicationSettings.unique_request_context_per_browser to True. Otherwise the browser param passed to this callback will always be the same first browser that was created using cefpython.CreateBrowserSync.

Popup browsers created javascript's window.open share the same renderer process and request context. If you want to have separate cookie managers for popups created using window.open then you have to implement the LifespanHandler.OnBeforePopup callback. Return True in that callback to cancel popup creation and instead create the window on your own and embed browser in it. The CreateAnotherBrowser function from the wxpython example does that.

IMPORTANT: in an exceptional case the browser parameter could be None, so you should handle such case. During testing this issue did not occur, but it may happen in some yet unknown scenarios.

void OnProtocolExecution(Browser browser, string url, list& allowExecutionOut)

Called on the UI thread to handle requests for URLs with an unknown protocol component. Set allowExecutionOut[0] to True to attempt execution via the registered OS protocol handler, if any. SECURITY WARNING: YOU SHOULD USE THIS METHOD TO ENFORCE RESTRICTIONS BASED ON SCHEME, HOST OR OTHER URL ANALYSIS BEFORE ALLOWING OS EXECUTION.

There's no default implementation for OnProtocolExecution on Linux, you have to make OS system call on your own. You probably also need to use LoadHandler::OnLoadError() when implementing this on Linux.

bool _OnBeforePluginLoad(Browser browser, string url, string policyUrl, WebPluginInfo info)

Called on the browser process IO thread before a plugin is loaded. Return True to block loading of the plugin.

This callback will be executed during browser creation, thus you must call cefpython.SetGlobalClientCallback() to use it. The callback name was prefixed with "_" to distinguish this special behavior.

Plugins are loaded on demand, only when website requires it. This callback is called every time the page tries to load a plugin (perhaps even multiple times per plugin).

bool _OnCertificateError(NetworkError certError, string requestUrl, AllowCertificateErrorCallback callback)

This callback is not associated with any specific browser, thus you must call cefpython.SetGlobalClientCallback() to use it. The callback name was prefixed with "_" to distinguish this special behavior.

Called on the UI thread to handle requests for URLs with an invalid SSL certificate. Return True and call AllowCertificateErrorCallback:: Continue() either in this method or at a later time to continue or cancel the request. Return False to cancel the request immediately. If |callback| is empty the error cannot be recovered from and the request will be canceled automatically. If ApplicationSettings.ignore_certificate_errors is set all invalid certificates will be accepted without calling this method.

The AllowCertificateErrorCallback object methods:

  • void Continue(bool allow)

void OnRendererProcessTerminated(Browser browser, TerminationStatus status)

Called when the render process terminates unexpectedly. |status| indicates how the process terminated.

TerminationStatus constants:

  • cefpython.TS_ABNORMAL_TERMINATION - Non-zero exit status.
  • cefpython.TS_PROCESS_WAS_KILLED - SIGKILL or task manager kill.
  • cefpython.TS_PROCESS_CRASHED - Segmentation fault.

void OnPluginCrashed(Browser browser, string pluginPath)

Called when a plugin has crashed. |pluginPath| is the path of the plugin that crashed.

CEF 1

bool OnBeforeBrowse(Browser browser, Frame frame, Request request, int navType, bool isRedirect)

Called on the UI thread before browser navigation. Return true to cancel the navigation or false to allow the navigation to proceed.

You cannot modify request headers nor post data via the Request object in this callback, you have to do it in OnBeforeResourceLoad().

|navType| can be one of:

cefpython.NAVTYPE_LINKCLICKED

cefpython.NAVTYPE_FORMSUBMITTED
cefpython.NAVTYPE_BACKFORWARD
cefpython.NAVTYPE_RELOAD
cefpython.NAVTYPE_FORMRESUBMITTED
cefpython.NAVTYPE_OTHER
cefpython.NAVTYPE_LINKDROPPED

bool OnBeforeResourceLoad(Browser browser, Request request, string& redirectURL[0], StreamReader streamReader, Response response, int loadFlags)

Called on the IO thread before a resource is loaded. To allow the resource
to load normally return false. To redirect the resource to a new url
populate the |redirectUrl| value and return false. To specify data for the
resource set it through |streamReader|, use the |response|
object to set mime type, HTTP status code and optional header values, and
return false. To cancel loading of the resource return true. Any
modifications to |request| will be observed. If the URL in |request| is
changed and |redirectUrl| is also set, the URL in |request| will be used.

void OnResourceRedirect(Browser browser, string oldURL, string& newURL[0])

Called on the IO thread when a resource load is redirected. The |oldURL| parameter will contain the old URL. The |newURL[0]| parameter will contain the new URL and can be changed if desired.

void OnResourceResponse(Browser browser, string url, Response response, ContentFilter& filter[0])

Called on the UI thread after a response to the resource request is received. Set |filter| if response content needs to be monitored and/or modified as it arrives.
ContentFilter is not yet implemented, as of the moment you can only read responses using the Response object.
This function does not get called for local disk resources (file:///). If you want to track local disk resources that failed to load, the way to go is to implement Schemehandler (see thread here: http://magpcss.org/ceforum/viewtopic.php?f=6&t=3442)

bool OnProtocolExecution(Browser browser, string URL, bool& allowOSExecution[0])

Called on the IO thread to handle requests for URLs with an unknown
protocol component. Return true to indicate that the request should
succeed because it was handled externally. Set |allowOSExecution[0]| to true and return false to attempt execution via the registered OS protocol handler, if any. If false is returned and either |allowOSExecution[0]| is false or OS protocol handler execution fails then the request will fail with an error condition.
SECURITY WARNING: you should use this method to enforce restrictions based on scheme, host or other url analysis before allowing os execution.

DownloadHandler GetDownloadHandler(Browser browser, string mimeType, string filename, int contentLength)

Called on the UI thread when a server indicates via the
'Content-Disposition' header that a response represents a file to download.
|mimeType| is the mime type for the download, |fileName| is the suggested
target file name and |contentLength| is either the value of the
'Content-Size' header or -1 if no size was provided.
Return a DownloadHandler object to download the file or False
to cancel the file download.
The DownloadHandler object is a python class that implements the
DownloadHandler callbacks, you must keep a strong reference to
this object while download is proceeding, otherwise it gets destroyed
and the callbacks won't be called.

bool GetAuthCredentials(Browser browser, bool isProxy, string host, int port, string realm, string scheme, string& username[0], string& password[0])

On Windows there is a default implementation for Http Authentication. On Linux there is no default implementation.
Called on the IO thread when the browser needs credentials from the user. |isProxy| indicates whether the host is a proxy server. |host| contains the hostname and port number. Set |username[0]| and |password[0]| and return true to handle the request. Return false to cancel the request.

CookieManager GetCookieManager(Browser browser, string mainUrl)

Called on the IO thread to retrieve the cookie manager. |mainUrl| is the URL of the top-level frame. Cookies managers can be unique per browser or shared across multiple browsers. The global cookie manager will be used if this method returns None.
This method may be called multiple times for the same browser,
if you return a cookie manager you need to save it somewhere
so that you don't create a new one on next call, use
Browser.SetUserData() and Browser.GetUserData() for
that purpose.

Clone this wiki locally