2.CEF常用介面類攔截請求回撥函式
2 Cef常用介面類介紹
2。1 CefClient
2。2 CefContextMenuHandler右鍵選單處理類
2。3 CefDisplayHandler網頁顯示處理類
2。4 CefDownloadHandler網頁下載處理類
2。5 CefDragHandler滑鼠拖動到網頁處理類
2。6 CefKeyboardHandler鍵盤事件響應處理類
2。7 CefLifeSpanHandler生命週期處理類
2。7。1 DoClose標準關閉處理
2。7。2 DoClose非標準關閉處理
2。8 CefLoadHandler網頁載入處理類
2。9 CefRequestHandler網路請求處理類
Cef是一個網頁嵌入外殼,要獲取網頁的響應,攔截網頁中的事件訊息,CEF提供了一系列的介面回撥類,提供各種事件回撥函式,例如攔截獲取鍵盤、滑鼠、載入、顯示、右鍵選單、提示訊息、狀態變化、視窗開啟關閉等,CEF都可以從網頁上攔截捕捉訊息事件,並透過回撥函式傳給應用程式進行處理。
2。1 CefClient
CefClient提供了獲取各種handler的介面,例如上下文選單handler、對話方塊handler、顯示狀態handler,下載事件handler、拖動事件handler、查詢事件handler、鍵盤handler、生命週期事件handler、載入頁面事件handler、離屏render程序handler、請求事件handler等。但是隻是返回事件的handle。每個handler的具體的回撥函式不在CefClient類中,需要繼承各個handler類,才可以實現回撥。CefClient類只有一個回撥函式OnProcessMessageReceived用來處理程序間的通訊訊息。CefClient的定義如下:
class CefClient : public virtual CefBaseRefCounted {
public:
///
// Return the handler for context menus。 If no handler is provided the default
// implementation will be used。
///
/*——cef()——*/
virtual CefRefPtr
return NULL;
}
///
// Return the handler for dialogs。 If no handler is provided the default
// implementation will be used。
///
/*——cef()——*/
virtual CefRefPtr
///
// Return the handler for browser display state events。
///
/*——cef()——*/
virtual CefRefPtr
///
// Return the handler for download events。 If no handler is returned downloads
// will not be allowed。
///
/*——cef()——*/
virtual CefRefPtr
///
// Return the handler for drag events。
///
/*——cef()——*/
virtual CefRefPtr
///
// Return the handler for find result events。
///
/*——cef()——*/
virtual CefRefPtr
///
// Return the handler for focus events。
///
/*——cef()——*/
virtual CefRefPtr
///
// Return the handler for JavaScript dialogs。 If no handler is provided the
// default implementation will be used。
///
/*——cef()——*/
virtual CefRefPtr
///
// Return the handler for keyboard events。
///
/*——cef()——*/
virtual CefRefPtr
///
// Return the handler for browser life span events。
///
/*——cef()——*/
virtual CefRefPtr
///
// Return the handler for browser load status events。
///
/*——cef()——*/
virtual CefRefPtr
///
// Return the handler for off-screen rendering events。
///
/*——cef()——*/
virtual CefRefPtr
///
// Return the handler for browser request events。
///
/*——cef()——*/
virtual CefRefPtr
///
// Called when a new message is received from a different process。 Return true
// if the message was handled or false otherwise。 Do not keep a reference to
// or attempt to access the message outside of this callback。
///
/*——cef()——*/
virtual bool OnProcessMessageReceived(CefRefPtr
CefProcessId source_process,
CefRefPtr
return false;
}
};
2。2 CefContextMenuHandler右鍵選單處理類
CefContextMenuHandler是網頁上的右鍵選單事件回撥函式類,提供OnBeforeContextMenu回撥函式,在右鍵選單彈出之前修改或者禁用右鍵選單。右鍵選單按鈕響應回撥RunContextMenu、右鍵選單命令回撥OnContextMenuCommand選單禁用回撥函式OnContextMenuDismissed等。可以攔截右鍵選單響應,進行自定義的處理。
class CefContextMenuHandler : public virtual CefBaseRefCounted {
public:
typedef cef_event_flags_t EventFlags;
///
// Called before a context menu is displayed。 |params| provides information
// about the context menu state。 |model| initially contains the default
// context menu。 The |model| can be cleared to show no context menu or
// modified to show a custom menu。 Do not keep references to |params| or
// |model| outside of this callback。
///
/*——cef()——*/
virtual void OnBeforeContextMenu(CefRefPtr
CefRefPtr
CefRefPtr
CefRefPtr
///
// Called to allow custom display of the context menu。 |params| provides
// information about the context menu state。 |model| contains the context menu
// model resulting from OnBeforeContextMenu。 For custom display return true
// and execute |callback| either synchronously or asynchronously with the
// selected command ID。 For default display return false。 Do not keep
// references to |params| or |model| outside of this callback。
///
/*——cef()——*/
virtual bool RunContextMenu(CefRefPtr
CefRefPtr
CefRefPtr
CefRefPtr
CefRefPtr
return false;
}
///
// Called to execute a command selected from the context menu。 Return true if
// the command was handled or false for the default implementation。 See
// cef_menu_id_t for the command ids that have default implementations。 All
// user-defined command ids should be between MENU_ID_USER_FIRST and
// MENU_ID_USER_LAST。 |params| will have the same values as what was passed to
// OnBeforeContextMenu()。 Do not keep a reference to |params| outside of this
// callback。
///
/*——cef()——*/
virtual bool OnContextMenuCommand(CefRefPtr
CefRefPtr
CefRefPtr
int command_id,
EventFlags event_flags) {
return false;
}
///
// Called when the context menu is dismissed irregardless of whether the menu
// was empty or a command was selected。
///
/*——cef()——*/
virtual void OnContextMenuDismissed(CefRefPtr
CefRefPtr
};
2。3 CefDisplayHandler網頁顯示處理類
CefDisplayHandler提供了一些頁面顯示回撥函式,例如網址傳送變化OnAddressChange,網頁標題OnTitleChange發生變化,網頁圖示發生變化OnFaviconURLChange,全屏變化OnFullscreenModeChange,顯示提示訊息OnTooltip,狀態列訊息顯示OnStatusMessage,控制檯訊息回撥OnConsoleMessage,設定了自動調整大小回調OnAutoResize,載入程序變化回撥OnLoadingProgressChange,CefDisplayHandler類定義如下
class CefDisplayHandler : public virtual CefBaseRefCounted {
public:
///
// Called when a frame‘s address has changed。
///
/*——cef()——*/
virtual void OnAddressChange(CefRefPtr
CefRefPtr
const CefString& url) {}
///
// Called when the page title changes。
///
/*——cef(optional_param=title)——*/
virtual void OnTitleChange(CefRefPtr
const CefString& title) {}
///
// Called when the page icon changes。
///
/*——cef(optional_param=icon_urls)——*/
virtual void OnFaviconURLChange(CefRefPtr
const std::vector
///
// Called when web content in the page has toggled fullscreen mode。 If
// |fullscreen| is true the content will automatically be sized to fill the
// browser content area。 If |fullscreen| is false the content will
// automatically return to its original size and position。 The client is
// responsible for resizing the browser if desired。
///
/*——cef()——*/
virtual void OnFullscreenModeChange(CefRefPtr
bool fullscreen) {}
///
// Called when the browser is about to display a tooltip。 |text| contains the
// text that will be displayed in the tooltip。 To handle the display of the
// tooltip yourself return true。 Otherwise, you can optionally modify |text|
// and then return false to allow the browser to display the tooltip。
// When window rendering is disabled the application is responsible for
// drawing tooltips and the return value is ignored。
///
/*——cef(optional_param=text)——*/
virtual bool OnTooltip(CefRefPtr
return false;
}
///
// Called when the browser receives a status message。 |value| contains the
// text that will be displayed in the status message。
///
/*——cef(optional_param=value)——*/
virtual void OnStatusMessage(CefRefPtr
const CefString& value) {}
///
// Called to display a console message。 Return true to stop the message from
// being output to the console。
///
/*——cef(optional_param=message,optional_param=source)——*/
virtual bool OnConsoleMessage(CefRefPtr
cef_log_severity_t level,
const CefString& message,
const CefString& source,
int line) {
return false;
}
///
// Called when auto-resize is enabled via CefBrowserHost::SetAutoResizeEnabled
// and the contents have auto-resized。 |new_size| will be the desired size in
// view coordinates。 Return true if the resize was handled or false for
// default handling。
///
/*——cef()——*/
virtual bool OnAutoResize(CefRefPtr
const CefSize& new_size) {
return false;
}
///
// Called when the overall page loading progress has changed。 |progress|
// ranges from 0。0 to 1。0。
///
/*——cef()——*/
virtual void OnLoadingProgressChange(CefRefPtr
double progress) {}
};
2。4 CefDownloadHandler網頁下載處理類
CefDownloadHandler網頁上下載檔案類,提供開始從網頁下載檔案回撥函式OnBeforeDownload,下載檔案進度更新回撥函式OnDownloadUpdated。
class CefDownloadHandler : public virtual CefBaseRefCounted {
public:
///
// Called before a download begins。 |suggested_name| is the suggested name for
// the download file。 By default the download will be canceled。 Execute
// |callback| either asynchronously or in this method to continue the download
// if desired。 Do not keep a reference to |download_item| outside of this
// method。
///
/*——cef()——*/
virtual void OnBeforeDownload(
CefRefPtr
CefRefPtr
const CefString& suggested_name,
CefRefPtr
///
// Called when a download’s status or progress information has been updated。
// This may be called multiple times before and after OnBeforeDownload()。
// Execute |callback| either asynchronously or in this method to cancel the
// download if desired。 Do not keep a reference to |download_item| outside of
// this method。
///
/*——cef()——*/
virtual void OnDownloadUpdated(CefRefPtr
CefRefPtr
CefRefPtr
};
2。5 CefDragHandler滑鼠拖動到網頁處理類
CefDragHandler處理滑鼠拖動事件,提供滑鼠拖動進入網頁回撥函式OnDragEnter,網頁中可以拖動放入的區域發生變化回撥函式OnDraggableRegionsChanged。
// Implement this interface to handle events related to dragging。 The methods of
// this class will be called on the UI thread。
///
/*——cef(source=client)——*/
class CefDragHandler : public virtual CefBaseRefCounted {
public:
typedef cef_drag_operations_mask_t DragOperationsMask;
///
// Called when an external drag event enters the browser window。 |dragData|
// contains the drag event data and |mask| represents the type of drag
// operation。 Return false for default drag handling behavior or true to
// cancel the drag event。
///
/*——cef()——*/
virtual bool OnDragEnter(CefRefPtr
CefRefPtr
DragOperationsMask mask) {
return false;
}
///
// Called whenever draggable regions for the browser window change。 These can
// be specified using the ‘-webkit-app-region: drag/no-drag’ CSS-property。 If
// draggable regions are never defined in a document this method will also
// never be called。 If the last draggable region is removed from a document
// this method will be called with an empty vector。
///
/*——cef()——*/
virtual void OnDraggableRegionsChanged(
CefRefPtr
const std::vector
};
2。6 CefKeyboardHandler鍵盤事件響應處理類
CefKeyboardHandler處理鍵盤響應事件,提供鍵盤按鍵響應回撥函式。攔截鍵盤訊息。
// Implement this interface to handle events related to keyboard input。 The
// methods of this class will be called on the UI thread。
///
/*——cef(source=client)——*/
class CefKeyboardHandler : public virtual CefBaseRefCounted {
public:
///
// Called before a keyboard event is sent to the renderer。 |event| contains
// information about the keyboard event。 |os_event| is the operating system
// event message, if any。 Return true if the event was handled or false
// otherwise。 If the event will be handled in OnKeyEvent() as a keyboard
// shortcut set |is_keyboard_shortcut| to true and return false。
///
/*——cef()——*/
virtual bool OnPreKeyEvent(CefRefPtr
const CefKeyEvent& event,
CefEventHandle os_event,
bool* is_keyboard_shortcut) {
return false;
}
///
// Called after the renderer and JavaScript in the page has had a chance to
// handle the event。 |event| contains information about the keyboard event。
// |os_event| is the operating system event message, if any。 Return true if
// the keyboard event was handled or false otherwise。
///
/*——cef()——*/
virtual bool OnKeyEvent(CefRefPtr
const CefKeyEvent& event,
CefEventHandle os_event) {
return false;
}
};
2。7 CefLifeSpanHandler生命週期處理類
CefLifeSpanHandler是生命週期處理類,新開啟一個網頁或者關閉一個網頁時,會觸發回撥函式。OnBeforePopup這個只能在建立一個新的彈出式網頁時,才會觸發,如果是在一個網頁中開啟一個子網頁,回撥函式是攔截不到訊息的。OnAfterCreated網頁建立完成後的回撥函式。browser銷燬之前會觸發回撥函式OnBeforeClose。還有一個關閉回撥函式DoClose有點複雜,當呼叫CefBrowserHost::*CloseBrowser()函式關閉browser,或者browser是CEF建立的頂層視窗的子視窗,當頂層視窗關閉時,也會觸發關閉DoClose回撥函式。點選網頁的關閉按鈕後,網頁不會立刻關閉,而是會呼叫兩次CloseBrowser()或TryCloseBrowser(),提供了一個讓CEF處理JS的onbeforeunload事件和選擇性取消關閉網頁的機會。CefLifeSpanHandler類定義如下:
// Implement this interface to handle events related to browser life span。 The
// methods of this class will be called on the UI thread unless otherwise
// indicated。
///
/*——cef(source=client)——*/
class CefLifeSpanHandler : public virtual CefBaseRefCounted {
public:
typedef cef_window_open_disposition_t WindowOpenDisposition;
///
// Called on the UI thread before a new popup browser is created。 The
// |browser| and |frame| values represent the source of the popup request。 The
// |target_url| and |target_frame_name| values indicate where the popup
// browser should navigate and may be empty if not specified with the request。
// The |target_disposition| value indicates where the user intended to open
// the popup (e。g。 current tab, new tab, etc)。 The |user_gesture| value will
// be true if the popup was opened via explicit user gesture (e。g。 clicking a
// link) or false if the popup opened automatically (e。g。 via the
// DomContentLoaded event)。 The |popupFeatures| structure contains additional
// information about the requested popup window。 To allow creation of the
// popup browser optionally modify |windowInfo|, |client|, |settings| and
// |no_javascript_access| and return false。 To cancel creation of the popup
// browser return true。 The |client| and |settings| values will default to the
// source browser‘s values。 If the |no_javascript_access| value is set to
// false the new browser will not be scriptable and may not be hosted in the
// same renderer process as the source browser。 Any modifications to
// |windowInfo| will be ignored if the parent browser is wrapped in a
// CefBrowserView。 Popup browser creation will be canceled if the parent
// browser is destroyed before the popup browser creation completes (indicated
// by a call to OnAfterCreated for the popup browser)。
///
/*——cef(optional_param=target_url,optional_param=target_frame_name)——*/
virtual bool OnBeforePopup(CefRefPtr
CefRefPtr
const CefString& target_url,
const CefString& target_frame_name,
WindowOpenDisposition target_disposition,
bool user_gesture,
const CefPopupFeatures& popupFeatures,
CefWindowInfo& windowInfo,
CefRefPtr
CefBrowserSettings& settings,
bool* no_javascript_access) {
return false;
}
///
// Called after a new browser is created。 This callback will be the first
// notification that references |browser|。
///
/*——cef()——*/
virtual void OnAfterCreated(CefRefPtr
///
// Called when a browser has recieved a request to close。 This may result
// directly from a call to CefBrowserHost::*CloseBrowser() or indirectly if
// the browser is parented to a top-level window created by CEF and the user
// attempts to close that window (by clicking the ’X‘, for example)。 The
// DoClose() method will be called after the JavaScript ’onunload‘ event has
// been fired。
//
// An application should handle top-level owner window close notifications by
// calling CefBrowserHost::TryCloseBrowser() or
// CefBrowserHost::CloseBrowser(false) instead of allowing the window to close
// immediately (see the examples below)。 This gives CEF an opportunity to
// process the ’onbeforeunload‘ event and optionally cancel the close before
// DoClose() is called。
//
// When windowed rendering is enabled CEF will internally create a window or
// view to host the browser。 In that case returning false from DoClose() will
// send the standard close notification to the browser’s top-level owner
// window (e。g。 WM_CLOSE on Windows, performClose: on OS X, “delete_event” on
// Linux or CefWindowDelegate::CanClose() callback from Views)。 If the
// browser‘s host window/view has already been destroyed (via view hierarchy
// tear-down, for example) then DoClose() will not be called for that browser
// since is no longer possible to cancel the close。
//
// When windowed rendering is disabled returning false from DoClose() will
// cause the browser object to be destroyed immediately。
//
// If the browser’s top-level owner window requires a non-standard close
// notification then send that notification from DoClose() and return true。
//
// The CefLifeSpanHandler::OnBeforeClose() method will be called after
// DoClose() (if DoClose() is called) and immediately before the browser
// object is destroyed。 The application should only exit after OnBeforeClose()
// has been called for all existing browsers。
//
// The below examples describe what should happen during window close when the
// browser is parented to an application-provided top-level window。
//
// Example 1: Using CefBrowserHost::TryCloseBrowser()。 This is recommended for
// clients using standard close handling and windows created on the browser
// process UI thread。
// 1。 User clicks the window close button which sends a close notification to
// the application‘s top-level window。
// 2。 Application’s top-level window receives the close notification and
// calls TryCloseBrowser() (which internally calls CloseBrowser(false))。
// TryCloseBrowser() returns false so the client cancels the window close。
// 3。 JavaScript ‘onbeforeunload’ handler executes and shows the close
// confirmation dialog (which can be overridden via
// CefJSDialogHandler::OnBeforeUnloadDialog())。
// 4。 User approves the close。
// 5。 JavaScript ‘onunload’ handler executes。
// 6。 CEF sends a close notification to the application‘s top-level window
// (because DoClose() returned false by default)。
// 7。 Application’s top-level window receives the close notification and
// calls TryCloseBrowser()。 TryCloseBrowser() returns true so the client
// allows the window close。
// 8。 Application‘s top-level window is destroyed。
// 9。 Application’s OnBeforeClose() handler is called and the browser object
// is destroyed。
// 10。 Application exits by calling CefQuitMessageLoop() if no other browsers
// exist。
//
// Example 2: Using CefBrowserHost::CloseBrowser(false) and implementing the
// DoClose() callback。 This is recommended for clients using non-standard
// close handling or windows that were not created on the browser process UI
// thread。
// 1。 User clicks the window close button which sends a close notification to
// the application‘s top-level window。
// 2。 Application’s top-level window receives the close notification and:
// A。 Calls CefBrowserHost::CloseBrowser(false)。
// B。 Cancels the window close。
// 3。 JavaScript ‘onbeforeunload’ handler executes and shows the close
// confirmation dialog (which can be overridden via
// CefJSDialogHandler::OnBeforeUnloadDialog())。
// 4。 User approves the close。
// 5。 JavaScript ‘onunload’ handler executes。
// 6。 Application‘s DoClose() handler is called。 Application will:
// A。 Set a flag to indicate that the next close attempt will be allowed。
// B。 Return false。
// 7。 CEF sends an close notification to the application’s top-level window。
// 8。 Application‘s top-level window receives the close notification and
// allows the window to close based on the flag from #6B。
// 9。 Application’s top-level window is destroyed。
// 10。 Application‘s OnBeforeClose() handler is called and the browser object
// is destroyed。
// 11。 Application exits by calling CefQuitMessageLoop() if no other browsers
// exist。
///
/*——cef()——*/
virtual bool DoClose(CefRefPtr
///
// Called just before a browser is destroyed。 Release all references to the
// browser object and do not attempt to execute any methods on the browser
// object after this callback returns。 This callback will be the last
// notification that references |browser|。 See DoClose() documentation for
// additional usage information。
///
/*——cef()——*/
virtual void OnBeforeClose(CefRefPtr
};
2。7。1 DoClose標準關閉處理
當視窗建立是在browser程序的UI執行緒建立時,採用標準的關閉處理,使用CefBrowserHost::TryCloseBrowser()。不實現DoClose回撥,預設返回false。具體步驟:
(1) 點選視窗的關閉按鈕,傳送一個關閉通知給頂層視窗。
(2) 頂層視窗接收到關閉通知,呼叫TryCloseBrowser()函式,返回false;
(3) JS的onbeforeunload處理控制代碼執行顯示關閉確認對話方塊。
(4) 使用者點選按鈕同意關閉;
(5) JS的onunload處理控制代碼執行;
(6) CEF傳送一個close通知給頂層視窗;
(7) 定鞥視窗接收到關閉通知,呼叫TryCloseBrowser,返回true,表示允許關閉。
(8) 頂層視窗銷燬
(9) 程式的OnBeforeClose處理回撥函式執行,browser銷燬。
(10)如果不存在其他browser,則呼叫CefQuitMessageLoop退出程式。
2。7。2 DoClose非標準關閉處理
當視窗不是在browser程序的UI執行緒中建立時,採用非標準的關閉處理,使用函式CefBrowserHost::CloseBrowser(false),並且實現DoClose函式。
(1) 使用者點選視窗的關閉按鈕,傳送一個關閉通知給頂層視窗。
(2) 頂層視窗接收到關閉通知,呼叫CefBrowserHost::CloseBrowser(false)函式,取消關閉;
(3) JS的onbeforeunload處理控制代碼執行顯示關閉確認對話方塊。
(4) 使用者點選按鈕同意關閉;
(5) JS的onunload處理控制代碼執行;
(6) 程式的DoClose()回撥函式被呼叫,設定一個flag表明下次關閉嘗試會被允許,返回false;
(7) CEF傳送一個close通知給頂層視窗;
(8) 頂層視窗接收到關閉通知,根據之前設定的flag判斷是否關閉視窗。
(9) 頂層視窗銷燬;
(10)程式的OnBeforeClose處理回撥函式執行,browser銷燬。
(11)如果不存在其他browser,則呼叫CefQuitMessageLoop退出程式。
2。8 CefLoadHandler網頁載入處理類
在一個網頁中載入內容,或者在網頁中開啟一個子frame,都可以攔截到iframe開啟時的訊息以及url等資訊。可以攔截子網頁url
(1) 開始載入OnLoadStart,navigation執行網之後,開始載入內容之前,回撥此函式,多frame的程序會同時載入。同頁面巡航不會呼叫。
(2) 載入結束OnLoadEnd,載入結束時回撥,sub-frame在主frame載入結束後, 會繼續開始載入或繼續進行載入,同頁面巡航不會呼叫。
(3) 載入錯誤OnLoadError,navigation失敗或者取消是回撥。
(4) 載入狀態發生變化OnLoadingStateChange,載入初始化和載入結束時各呼叫一次,在OnLoadStart之前呼叫一次,OnLoadEnd或OnLoadError之後呼叫一次。
// Implement this interface to handle events related to browser load status。 The
// methods of this class will be called on the browser process UI thread or
// render process main thread (TID_RENDERER)。
///
/*——cef(source=client)——*/
class CefLoadHandler : public virtual CefBaseRefCounted {
public:
typedef cef_errorcode_t ErrorCode;
typedef cef_transition_type_t TransitionType;
///
// Called when the loading state has changed。 This callback will be executed
// twice —— once when loading is initiated either programmatically or by user
// action, and once when loading is terminated due to completion, cancellation
// of failure。 It will be called before any calls to OnLoadStart and after all
// calls to OnLoadError and/or OnLoadEnd。
///
/*——cef()——*/
virtual void OnLoadingStateChange(CefRefPtr
bool isLoading,
bool canGoBack,
bool canGoForward) {}
///
// Called after a navigation has been committed and before the browser begins
// loading contents in the frame。 The |frame| value will never be empty ——
// call the IsMain() method to check if this frame is the main frame。
// |transition_type| provides information about the source of the navigation
// and an accurate value is only available in the browser process。 Multiple
// frames may be loading at the same time。 Sub-frames may start or continue
// loading after the main frame load has ended。 This method will not be called
// for same page navigations (fragments, history state, etc。) or for
// navigations that fail or are canceled before commit。 For notification of
// overall browser load status use OnLoadingStateChange instead。
///
/*——cef()——*/
virtual void OnLoadStart(CefRefPtr
CefRefPtr
TransitionType transition_type) {}
///
// Called when the browser is done loading a frame。 The |frame| value will
// never be empty —— call the IsMain() method to check if this frame is the
// main frame。 Multiple frames may be loading at the same time。 Sub-frames may
// start or continue loading after the main frame load has ended。 This method
// will not be called for same page navigations (fragments, history state,
// etc。) or for navigations that fail or are canceled before commit。 For
// notification of overall browser load status use OnLoadingStateChange
// instead。
///
/*——cef()——*/
virtual void OnLoadEnd(CefRefPtr
CefRefPtr
int httpStatusCode) {}
///
// Called when a navigation fails or is canceled。 This method may be called
// by itself if before commit or in combination with OnLoadStart/OnLoadEnd if
// after commit。 |errorCode| is the error code number, |errorText| is the
// error text and |failedUrl| is the URL that failed to load。
// See net\base\net_error_list。h for complete descriptions of the error codes。
///
/*——cef(optional_param=errorText)——*/
virtual void OnLoadError(CefRefPtr
CefRefPtr
ErrorCode errorCode,
const CefString& errorText,
const CefString& failedUrl) {}
};
2。9 CefRequestHandler網路請求處理類
當開啟一個網頁, CefRequestHandler的OnBeforeBrowser可以攔截網路請求,只有在新開啟網頁的時候,才會觸發,如果網頁已經開啟,在網頁內部點選查詢按鈕,查詢內容,雖然也有request請求,但是OnBeforeBrowser攔截不到獲取請求的URL,post請求的引數都可以獲取到。OnResourceRedirect還可以攔截重定向請求。CefLoadHandler也可以攔截request請求,而且頁面載入中呼叫很多的GET和POST請求都可以攔截到。測試發現CefRequestHandler頁面內部的載入變化是獲取不到的,只有開啟頁面的請求能獲取到。而另外一個函式OnBeforeResourceLoad則可以攔截所有的請求,在瀏覽器中F12顯示的所有請求,包括圖片下載等請求都能一一獲取。所以CefLoadHandler攔截的請求更詳細一些,點選查詢查詢,OnLoadStart和OnLoadEnd 攔截不到,但是OnLoadingStateChange 可以攔截的到請求。
OnBeforeBrowser
開啟新的網頁可以攔截,頁面內容變化,或者頁面內部呼叫請求攔截不到。
OnBeforeResourceLoad
攔截一切請求,最詳細。
OnResourceResponse
攔截一切請求,最詳細。
OnLoadStart和OnLoadEnd
新開啟頁面可以攔截
OnLoadingStateChange
開啟新頁面, 頁面內容重新載入,查詢,按鈕響應可以攔截。像一些圖片載入,CSS載入是攔截不到的。第二詳細。
各回調函的呼叫的先後順序是
OnLoadingStateChange->OnBeforeBrowser->OnLoadStart->OnLoadEnd->OnLoadingStateChange。
// Implement this interface to handle events related to browser requests。 The
// methods of this class will be called on the thread indicated。
///
/*——cef(source=client)——*/
class CefRequestHandler : public virtual CefBaseRefCounted {
public:
typedef cef_return_value_t ReturnValue;
typedef cef_termination_status_t TerminationStatus;
typedef cef_urlrequest_status_t URLRequestStatus;
typedef cef_window_open_disposition_t WindowOpenDisposition;
typedef std::
vector
///
// 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。
// CefLoadHandler::OnLoadingStateChange will be called twice in all cases。
// If the navigation is allowed CefLoadHandler::OnLoadStart and
// CefLoadHandler::OnLoadEnd will be called。 If the navigation is canceled
// CefLoadHandler::OnLoadError will be called with an |errorCode| value of
// ERR_ABORTED。 The |user_gesture| value will be true if the browser
// navigated via explicit user gesture (e。g。 clicking a link) or false if it
// navigated automatically (e。g。 via the DomContentLoaded event)。
///
/*——cef()——*/
(1)OnBeforeBrowse,在瀏覽器巡航前呼叫。
virtual bool OnBeforeBrowse(CefRefPtr
CefRefPtr
CefRefPtr
bool user_gesture,
bool is_redirect) {
return false;
}
///
// Called on the UI thread before OnBeforeBrowse in certain limited cases
// where navigating a new or different browser might be desirable。 This
// includes user-initiated navigation that might open in a special way (e。g。
// links clicked via middle-click or ctrl + left-click) and certain types of
// cross-origin navigation initiated from the renderer process (e。g。
// navigating the top-level frame to/from a file URL)。 The |browser| and
// |frame| values represent the source of the navigation。 The
// |target_disposition| value indicates where the user intended to navigate
// the browser based on standard Chromium behaviors (e。g。 current tab,
// new tab, etc)。 The |user_gesture| value will be true if the browser
// navigated via explicit user gesture (e。g。 clicking a link) or false if it
// navigated automatically (e。g。 via the DomContentLoaded event)。 Return true
// to cancel the navigation or false to allow the navigation to proceed in the
// source browser’s top-level frame。
///
/*——cef()——*/
(2)OnOpenURLFromTab,以特殊的方式開啟的網頁,例如滑鼠中間按鈕,快捷鍵等,一些很少的應用場景。
virtual bool OnOpenURLFromTab(CefRefPtr
CefRefPtr
const CefString& target_url,
WindowOpenDisposition target_disposition,
bool user_gesture) {
return false;
}
///
// Called on the IO thread before a resource request is loaded。 The |request|
// object may be modified。 Return RV_CONTINUE to continue the request
// immediately。 Return RV_CONTINUE_ASYNC and call CefRequestCallback::
// Continue() at a later time to continue or cancel the request
// asynchronously。 Return RV_CANCEL to cancel the request immediately。
//
///
/*——cef(default_retval=RV_CONTINUE)——*/
(3)OnBeforeResourceLoad網頁開始載入資源時呼叫,可以攔截所有的請求,最為詳細。
virtual ReturnValue OnBeforeResourceLoad(
CefRefPtr
CefRefPtr
CefRefPtr
CefRefPtr
return RV_CONTINUE;
}
};
///
// Called on the IO thread before a resource is loaded。 To allow the resource
// to load normally return NULL。 To specify a handler for the resource return
// a CefResourceHandler object。 The |request| object should not be modified in
// this callback。
///
/*——cef()——*/
virtual CefRefPtr
CefRefPtr
CefRefPtr
CefRefPtr
return NULL;
}
///
// Called on the IO thread when a resource load is redirected。 The |request|
// parameter will contain the old URL and other request-related information。
// The |response| parameter will contain the response that resulted in the
// redirect。 The |new_url| parameter will contain the new URL and can be
// changed if desired。 The |request| object cannot be modified in this
// callback。
///
/*——cef()——*/
(4)OnResourceRedirect重定向請求攔截
virtual void OnResourceRedirect(CefRefPtr
CefRefPtr
CefRefPtr
CefRefPtr
CefString& new_url) {}
///
// Called on the IO thread when a resource response is received。 To allow the
// resource to load normally return false。 To redirect or retry the resource
// modify |request| (url, headers or post body) and return true。 The
// |response| object cannot be modified in this callback。
///
/*——cef()——*/
(5)OnResourceResponse請求響應後的回撥函式
virtual bool OnResourceResponse(CefRefPtr
CefRefPtr
CefRefPtr
CefRefPtr
return false;
}
///
// Called on the IO thread to optionally filter resource response content。
// |request| and |response| represent the request and response respectively
// and cannot be modified in this callback。
///
/*——cef()——*/
virtual CefRefPtr
CefRefPtr
CefRefPtr
CefRefPtr
CefRefPtr
return NULL;
}
///
// Called on the IO thread when a resource load has completed。 |request| and
// |response| represent the request and response respectively and cannot be
// modified in this callback。 |status| indicates the load completion status。
// |received_content_length| is the number of response bytes actually read。
///
/*——cef()——*/
(6)OnResourceLoadComplete資源載入結束時的回撥
virtual void OnResourceLoadComplete(CefRefPtr
CefRefPtr
CefRefPtr
CefRefPtr
URLRequestStatus status,
int64 received_content_length) {}
///
// 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。 |realm| is the realm of the
// challenge and may be empty。 |scheme| is the authentication scheme used,
// such as “basic” or “digest”, and will be empty if the source of the request
// is an FTP server。 Return true to continue the request and call
// CefAuthCallback::Continue() either in this method or at a later time when
// the authentication information is available。 Return false to cancel the
// request immediately。
///
/*——cef(optional_param=realm,optional_param=scheme)——*/
virtual bool GetAuthCredentials(CefRefPtr
CefRefPtr
bool isProxy,
const CefString& host,
int port,
const CefString& realm,
const CefString& scheme,
CefRefPtr
return false;
}
///
// Called on the IO thread before sending a network request with a “Cookie”
// request header。 Return true to allow cookies to be included in the network
// request or false to block cookies。 The |request| object should not be
// modified in this callback。
///
/*——cef()——*/
virtual bool CanGetCookies(CefRefPtr
CefRefPtr
CefRefPtr
return true;
}
///
// Called on the IO thread when receiving a network request with a
// “Set-Cookie” response header value represented by |cookie|。 Return true to
// allow the cookie to be stored or false to block the cookie。 The |request|
// object should not be modified in this callback。
///
/*——cef()——*/
virtual bool CanSetCookie(CefRefPtr
CefRefPtr
CefRefPtr
const CefCookie& cookie) {
return true;
}
///
// Called on the IO thread when JavaScript requests a specific storage quota
// size via the webkitStorageInfo。requestQuota function。 |origin_url| is the
// origin of the page making the request。 |new_size| is the requested quota
// size in bytes。 Return true to continue the request and call
// CefRequestCallback::Continue() either in this method or at a later time to
// grant or deny the request。 Return false to cancel the request immediately。
///
/*——cef()——*/
virtual bool OnQuotaRequest(CefRefPtr
const CefString& origin_url,
int64 new_size,
CefRefPtr
return false;
}
///
// Called on the UI thread to handle requests for URLs with an unknown
// protocol component。 Set |allow_os_execution| 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。
///
/*——cef()——*/
virtual void OnProtocolExecution(CefRefPtr
const CefString& url,
bool& allow_os_execution) {}
///
// Called on the UI thread to handle requests for URLs with an invalid
// SSL certificate。 Return true and call CefRequestCallback::Continue() either
// in this method or at a later time to continue or cancel the request。 Return
// false to cancel the request immediately。 If
// CefSettings。ignore_certificate_errors is set all invalid certificates will
// be accepted without calling this method。
///
/*——cef()——*/
virtual bool OnCertificateError(CefRefPtr
cef_errorcode_t cert_error,
const CefString& request_url,
CefRefPtr
CefRefPtr
return false;
}
///
// Called on the UI thread when a client certificate is being requested for
// authentication。 Return false to use the default behavior and automatically
// select the first certificate available。 Return true and call
// CefSelectClientCertificateCallback::Select either in this method or at a
// later time to select a certificate。 Do not call Select or call it with NULL
// to continue without using any certificate。 |isProxy| indicates whether the
// host is an HTTPS proxy or the origin server。 |host| and |port| contains the
// hostname and port of the SSL server。 |certificates| is the list of
// certificates to choose from; this list has already been pruned by Chromium
// so that it only contains certificates from issuers that the server trusts。
///
/*——cef()——*/
virtual bool OnSelectClientCertificate(
CefRefPtr
bool isProxy,
const CefString& host,
int port,
const X509CertificateList& certificates,
CefRefPtr
return false;
}
///
// Called on the browser process UI thread when a plugin has crashed。
// |plugin_path| is the path of the plugin that crashed。
///
/*——cef()——*/
virtual void OnPluginCrashed(CefRefPtr
const CefString& plugin_path) {}
///
// Called on the browser process UI thread when the render view associated
// with |browser| is ready to receive/handle IPC messages in the render
// process。
///
/*——cef()——*/
virtual void OnRenderViewReady(CefRefPtr
///
// Called on the browser process UI thread when the render process
// terminates unexpectedly。 |status| indicates how the process
// terminated。
///
/*——cef()——*/
virtual void OnRenderProcessTerminated(CefRefPtr
TerminationStatus status) {}
};
自己開發了一個股票智慧分析軟體,功能很強大,需要的點選下面的連結獲取:
https://www.cnblogs.com/bclshuai/p/11380657.html