Cef frame render что это
990x.top
Простой компьютерный блог для души)
Папка CEF — что это за папка и можно ли ее удалить?
Папка CEF может иметь отношение к двум программам (по крайней мере) — игра и браузер. Однако в обоих случаях, вероятно связана с браузером Google Chrome.
Важно! CEF расшифровывается как Chromium Embedded Framework.
Что это за папка на компьютере?
Папка CEF может быть в игре World of Tanks — удалять нельзя. Располагаться может по такому адресу:
Буква диска может быть другой. Как видим, папка CEF содержит cef_browser_process.exe — модуль браузера в игре. Браузер не может работать без интернета — поэтому антивирус/фаервол может выдать запрос на доступ в интернет для процесса. Может требовать соединение с promo.worldoftanks.ru (офф сайт игры). Присутствует в чистом клиенте — значит офф компонент, не вирус.
Информация с офф форума World of Tanks: CEF — папка встроенного клиентского браузера, пришедший на смену Awesomium. Запуск игры через лаунчер должен решать проблему — лаунчер дает команду фаерволу не блокировать cef_browser_process.exe. Можно разрешать доступ в сеть, добавлять файл в список доверенных. cef_browser_process.exe не является угрозой.
Ссылка на ВирусТотал, где можно убедиться — файл чистый.
Также папку могло создать ПО Steam:
Сообщение с офф форума Steam, пользователь пишет — он специально удалил папку CEF. После запуска Steam — автоматически восстанавливается (если я правильно понял перевод).
CEF в AppData\Local
Второй вариант расположения:
Dima — название учетной записи, у вас будет другое. Внутри возможно наличие другой папки — User Data. Внутри которой — Dictionaries, внутри — файл en-US-8-0.bdic:
По информации, найденной в интернете — расширение файла bdic относится к браузеру Google Chrome, точнее к словарям. Браузер может использовать словари для проверки орфографии при наборе.
На моем ПК данная папка CEF в AppData\Local также присутствует. С даты создания папки никакой софт в систему не устанавливался. Никакие программы с интернета не загружались. Факт наличия вируса исключен. Скорее всего у вас CEF в AppData\Local также не является результатом работы вируса.
В любом случае, файл en-US-8-0.bdic можно проверить на ВирусТотале:
У меня места занимает немного — меньше мегабайта:
Не стоит удалять — вирусов нет, файл en-US-8-0.bdic безопасен, места занимает мало, по информации в интернете — нужна Хрому.
Важно! При подозрении на вирус — просканируйте ПК наиболее эффективными антивирусными утилитами Dr.Web CureIt!, AdwCleaner, HitmanPro (офф ссылки).
Можно ли ее удалить?
Заключение
Русские Блоги
Руководство по эксплуатации CEF (Chromium Embedded Framework)
CEFруководство пользователя
1.2 Загрузите и скомпилируйте CEF
1.3.1 Структурная взаимосвязь между процессом CEF и окном
1.3.2 Структура реализации процесса рендеринга
1.3.3 Структура реализации процесса браузера
1.4 CEF многопроцессорность и многопоточность
1.5 Встроенная структура приложения на веб-странице
1.5.2 Процесс единственного экземпляра CEF
1.5.3 Режим главного и дочернего процессов
1.6 Класс окна браузера CefBrowser
1.7 Класс управления работой браузера CefBrowserHost
1.8 Класс веб-интерфейса CefFrame
1.9 Категория приложений CefApp
1.10 Счетчик ссылок CEF
1.11 Пользовательская строка CEF
1.11.1 Зачем настраивать тип строки
1.11.2 Функция обработки строк CefString
1.11.3 Преобразование между CEF и String
2 Введение в общие классы интерфейса Cef
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
3 расширенных приложения CEF
3.1 Взаимодействие между CEF и JavaScript
3.1.1 Выполнение сценария JavaScript в CEF
3.1.2 Реализация JavaScript для выполнения функций в CEF в режиме расширения
3.2 Связь между процессами CEF
3.2.1 Функция межпроцессного взаимодействия
3.2.2 Примеры коммуникации процесса
3.2.3 Назначенная передача кадра CEF
1. Введение
1.1 Роль CEF
1.2 Загрузите и скомпилируйте CEF
Как показано на рисунке, проект CefClient представляет собой простую демонстрацию веб-браузера с вводом URL, перемоткой вперед и назад и т. Д.
Тестовый проект CefTest.
Папка Release содержит файлы выходной библиотеки и зависимые файлы библиотеки. Вы можете скопировать файлы включения и выпуска в проект при самостоятельной разработке проекта. Обратитесь к примерам кода CefSimple и CefClient.
1.3 Структура CEF
1.3.1 Структурная взаимосвязь между процессом CEF и окном
В браузере есть много окон CefBrowser, и эти окна создаются в процессе браузера. Процесс браузера используется для управления и обработки сообщений функции обратного вызова.
Процесс рендеринга используется для реализации рендеринга веб-страниц.Каждый процесс рендеринга содержит мэйнфрейм главной веб-страницы и несколько подфреймов подчиненных страниц.
1.3.2 Структура реализации процесса рендеринга
Программа визуализации наследует классы CefApp и CefRenderProcessHandler и инициализируется в основной функции. Настройте путь к исполняемой программе рендеринга через CefSettings.browser_subprocess_path. Процесс браузера запустит этот процесс для визуализации веб-страницы.
1.3.3 Структура реализации процесса браузера
Browserapp должен наследовать классы CefApp и CefBrowserProcessHandler. Реализуйте определение browserapp. В то же время создайте новый класс clienthandler для реализации класса интерфейса функции обратного вызова, показанного на рисунке, который используется для обработки запросов ответа на перехват, управления жизненным циклом, загрузки, отображения загрузки, контекстных меню и т. Д. Инициализируйте и запустите цикл сообщений в функции mian. Вызовите статический метод CefBrowserHost для создания объекта окна браузера и загрузите содержимое визуализации в фрейм процесса визуализации.
1.4 CEF многопроцессорность и многопоточность
1.4.1 Процесс
1.4.2 Резьба
Процесс браузера содержит следующие основные потоки:
1.5 Состав и примеры кода приложения, встроенного в веб-страницу
Каждое приложение CEF3 имеет одинаковую структуру
1.5.1 Функция ввода
Необходимо выполнить создание объекта cef, инициализацию, анализ параметров командной строки, установку атрибута CEF и открытие цикла сообщений CEF в функции ввода программы. CEF необходимо запустить основной процесс для управления веб-встречами. Основной процесс запускается в функции man, входит в цикл обработки сообщений и выходит из основной функции до завершения программы.
1.5.2 Процесс единственного экземпляра CEF
int main(int argc, char* argv[]) <
// Structure for passing command-line arguments.
// The definition of this structure is platform-specific.
CefMainArgs main_args(argc, argv);
// Optional implementation of the CefApp interface.
CefRefPtr app(new MyApp);
// Execute the sub-process logic, if any. This will either return immediately for the browser
// process or block until the sub-process should exit.
int exit_code = CefExecuteProcess(main_args, app.get());
// The sub-process terminated, exit now.
// Populate this structure to customize CEF behavior.
// Initialize CEF in the main process.
CefInitialize(main_args, settings, app.get());
// Run the CEF message loop. This will block until CefQuitMessageLoop() is called.
1.5.3 Режим главного и дочернего процессов
Основной процесс и дочерний процесс разделены, основной процесс запускает процесс браузера, а веб-страница загружается в процессе рендеринга дочернего процесса. Это необходимость создания двух процессов и двух основных функций.
Функция входа в главную программу:
// Program entry-point function.
// Функция входа в программу
int main(int argc, char* argv[]) <
// Structure for passing command-line arguments.
// The definition of this structure is platform-specific.
// Передаем структуру параметров командной строки.
// Определение этой структуры связано с платформой.
CefMainArgs main_args(argc, argv);
// Optional implementation of the CefApp interface.
// Необязательно реализовать интерфейс CefApp
CefRefPtr app(new MyApp);
// Populate this structure to customize CEF behavior.
// Заполняем эту структуру, чтобы настроить поведение CEF.
// Specify the path for the sub-process executable.
// Указываем путь выполнения дочернего процесса
// Initialize CEF in the main process.
// Инициализируем CEF в основном процессе
CefInitialize(main_args, settings, app.get());
// Run the CEF message loop. This will block until CefQuitMessageLoop() is called.
// Выполняем цикл сообщений, в это время он будет заблокирован, пока не будет вызвана функция CefQuitMessageLoop ().
Функция входа в программу дочернего процесса:
// Program entry-point function.
// Функция входа в программу
int main(int argc, char* argv[]) <
// Structure for passing command-line arguments.
// The definition of this structure is platform-specific.
// Передаем структуру параметров командной строки.
// Определение этой структуры связано с платформой.
CefMainArgs main_args(argc, argv);
// Optional implementation of the CefApp interface.
// Необязательно реализовать интерфейс CefApp
CefRefPtr app(new MyApp);
// Execute the sub-process logic. This will block until the sub-process should exit.
// Выполняем логику дочернего процесса и блокируемся, пока дочерний процесс не завершится.
return CefExecuteProcess(main_args, app.get());
1.6 Класс окна браузера CefBrowser
// Class used to represent a browser window. When used in the browser process
// the methods of this class may be called on any thread unless otherwise
// indicated in the comments. When used in the render process the methods of
// this class may only be called on the main thread.
class CefBrowser : public virtual CefBaseRefCounted <
// Returns the browser host object. This method can only be called in the
virtual CefRefPtr GetHost() = 0;
// Returns true if the browser can navigate backwards.
virtual bool CanGoBack() = 0;
virtual void GoBack() = 0;
// Returns true if the browser can navigate forwards.
virtual bool CanGoForward() = 0;
virtual void GoForward() = 0;
// Returns true if the browser is currently loading.
virtual bool IsLoading() = 0;
// Reload the current page.
virtual void Reload() = 0;
// Reload the current page ignoring any cached data.
virtual void ReloadIgnoreCache() = 0;
// Stop loading the page.
virtual void StopLoad() = 0;
// Returns the globally unique identifier for this browser. This value is also
// used as the tabId for extension APIs.
virtual int GetIdentifier() = 0;
// Returns true if this object is pointing to the same handle as |that|
virtual bool IsSame(CefRefPtr that) = 0;
// Returns true if the window is a popup window.
virtual bool IsPopup() = 0;
// Returns true if a document has been loaded in the browser.
virtual bool HasDocument() = 0;
// Returns the main (top-level) frame for the browser window.
virtual CefRefPtr GetMainFrame() = 0;
// Returns the focused frame for the browser window.
virtual CefRefPtr GetFocusedFrame() = 0;
// Returns the frame with the specified identifier, or NULL if not found.
virtual CefRefPtr GetFrame(int64 identifier) = 0;
// Returns the frame with the specified name, or NULL if not found.
virtual CefRefPtr GetFrame(const CefString& name) = 0;
// Returns the number of frames that currently exist.
virtual size_t GetFrameCount() = 0;
// Returns the identifiers of all existing frames.
virtual void GetFrameIdentifiers(std::vector & identifiers) = 0;
// Returns the names of all existing frames.
virtual void GetFrameNames(std::vector & names) = 0;
// Send a message to the specified |target_process|. Returns true if the
// message was sent successfully.
virtual bool SendProcessMessage(CefProcessId target_process,
CefRefPtr message) = 0;
1.7 Класс управления работой браузера CefBrowserHost
class CefBrowserHost : public virtual CefBaseRefCounted <
typedef cef_drag_operations_mask_t DragOperationsMask;
typedef cef_file_dialog_mode_t FileDialogMode;
typedef cef_mouse_button_type_t MouseButtonType;
typedef cef_paint_element_type_t PaintElementType;
// Create a new browser window using the window parameters specified by
// |windowInfo|. All values will be copied internally and the actual window
// will be created on the UI thread. If |request_context| is empty the
// global request context will be used. This method can be called on any
// browser process thread and will not block.
static bool CreateBrowser(const CefWindowInfo& windowInfo,
const CefString& url,
const CefBrowserSettings& settings,
// Create a new browser window using the window parameters specified by
// |windowInfo|. If |request_context| is empty the global request context
// will be used. This method can only be called on the browser process UI
static CefRefPtr CreateBrowserSync(
const CefWindowInfo& windowInfo,
const CefString& url,
const CefBrowserSettings& settings,
// Returns the hosted browser object.
virtual CefRefPtr GetBrowser() = 0;
// Request that the browser close. The JavaScript ‘onbeforeunload’ event will
// be fired. If |force_close| is false the event handler, if any, will be
// allowed to prompt the user and the user can optionally cancel the close.
// If |force_close| is true the prompt will not be displayed and the close
// will proceed. Results in a call to CefLifeSpanHandler::DoClose() if the
// event handler allows the close or if |force_close| is true. See
// CefLifeSpanHandler::DoClose() documentation for additional usage
virtual void CloseBrowser(bool force_close) = 0;
// Helper for closing a browser. Call this method from the top-level window
// close handler. Internally this calls CloseBrowser(false) if the close has
// not yet been initiated. This method returns false while the close is
// pending and true after the close has completed. See CloseBrowser() and
// CefLifeSpanHandler::DoClose() documentation for additional usage
// information. This method must be called on the browser process UI thread.
virtual bool TryCloseBrowser() = 0;
// Set whether the browser is focused.
virtual void SetFocus(bool focus) = 0;
// Retrieve the window handle for this browser. If this browser is wrapped in
// a CefBrowserView this method should be called on the browser process UI
// thread and it will return the handle for the top-level native window.
virtual CefWindowHandle GetWindowHandle() = 0;
// Retrieve the window handle of the browser that opened this browser. Will
// return NULL for non-popup windows or if this browser is wrapped in a
// CefBrowserView. This method can be used in combination with custom handling
virtual CefWindowHandle GetOpenerWindowHandle() = 0;
1.8 Класс веб-интерфейса CefFrame
Каждое окно CefBrowser содержит главный объект CefFrame и несколько объектов подкадра. Основной CefFrame эквивалентен основному интерфейсу веб-страницы, а вспомогательный CefFrame эквивалентен подстранице главной страницы. CefFrame содержит текст на веб-странице, исходную строку HTML, заголовок имени веб-страницы, загруженный URL-адрес, указатель CefBrowser, V8Context и т. Д. Вы также можете загружать страницы с помощью LoadURL или LoadRequest.
// Class used to represent a frame in the browser window. When used in the
// browser process the methods of this class may be called on any thread unless
// otherwise indicated in the comments. When used in the render process the
// methods of this class may only be called on the main thread.
class CefFrame : public virtual CefBaseRefCounted <
// True if this object is currently attached to a valid frame.
virtual bool IsValid() = 0;
// Execute undo in this frame.
virtual void Undo() = 0;
// Execute redo in this frame.
virtual void Redo() = 0;
// Execute cut in this frame.
virtual void Cut() = 0;
// Execute copy in this frame.
virtual void Copy() = 0;
// Execute paste in this frame.
virtual void Paste() = 0;
// Execute delete in this frame.
virtual void Delete() = 0;
// Execute select all in this frame.
virtual void SelectAll() = 0;
// Save this frame’s HTML source to a temporary file and open it in the
// default text viewing application. This method can only be called from the
virtual void ViewSource() = 0;
// Retrieve this frame’s HTML source as a string sent to the specified
virtual void GetSource(CefRefPtr visitor) = 0;
// Retrieve this frame’s display text as a string sent to the specified
virtual void GetText(CefRefPtr visitor) = 0;
// Load the request represented by the |request| object.
virtual void LoadRequest(CefRefPtr request) = 0;
// Load the specified |url|.
virtual void LoadURL(const CefString& url) = 0;
// Load the contents of |string_val| with the specified dummy |url|. |url|
// should have a standard scheme (for example, http scheme) or behaviors like
// link clicks and web security restrictions may not behave as expected.
virtual void LoadString(const CefString& string_val,
// Execute a string of JavaScript code in this frame. The |script_url|
// parameter is the URL where the script in question can be found, if any.
// The renderer may request this URL to show the developer the source of the
// error. The |start_line| parameter is the base line number to use for error
virtual void ExecuteJavaScript(const CefString& code,
const CefString& script_url,
// Returns true if this is the main (top-level) frame.
virtual bool IsMain() = 0;
// Returns true if this is the focused frame.
virtual bool IsFocused() = 0;
// Returns the name for this frame. If the frame has an assigned name (for
// example, set via the iframe «name» attribute) then that value will be
// returned. Otherwise a unique name will be constructed based on the frame
// parent hierarchy. The main (top-level) frame will always have an empty name
virtual CefString GetName() = 0;
// Returns the globally unique identifier for this frame or GetParent() = 0;
// Returns the URL currently loaded in this frame.
virtual CefString GetURL() = 0;
// Returns the browser that this frame belongs to.
virtual CefRefPtr GetBrowser() = 0;
// Get the V8 context associated with the frame. This method can only be
// called from the render process.
virtual CefRefPtr GetV8Context() = 0;
// Visit the DOM document. This method can only be called from the render
virtual void VisitDOM(CefRefPtr visitor) = 0;
1.9 Класс приложения CefApp
class CefApp : public virtual CefBaseRefCounted <
/// Изменить параметры командной строки
// Provides an opportunity to view and/or modify command-line arguments before
// processing by CEF and Chromium. The |process_type| value will be empty for
// the browser process. Do not keep a reference to the CefCommandLine object
// passed to this method. The CefSettings.command_line_args_disabled value
// can be used to start with an empty command-line object. Any values
// specified in CefSettings that equate to command-line arguments will be set
// before this method is called. Be cautious when using this method to modify
// command-line arguments for non-browser processes as this may result in
// undefined behavior including crashes.
virtual void OnBeforeCommandLineProcessing(
const CefString& process_type,
// Provides an opportunity to register custom schemes. Do not keep a reference
// to the |registrar| object. This method is called on the main thread for
// each process and the registered schemes should be the same across all
virtual void OnRegisterCustomSchemes(
// Return the handler for resource bundle events. If
// CefSettings.pack_loading_disabled is true a handler must be returned. If no
// handler is returned resources will be loaded from pack files. This method
// is called by the browser and render processes on multiple threads.
virtual CefRefPtr GetResourceBundleHandler() <
// Return the handler for functionality specific to the browser process. This
// method is called on multiple threads in the browser process.
virtual CefRefPtr GetBrowserProcessHandler() <
// Return the handler for functionality specific to the render process. This
// method is called on the render process main thread.
virtual CefRefPtr GetRenderProcessHandler() <
1.10 Счетчик ссылок CEF
CEF создает объекты в форме CefRefPtr app (new SimpleApp); или CefRefPtr app = new SimpleApp (); Созданный счетчик ссылок указателя управляется CefRefPtr, а CefRefPtr автоматически управляет ссылками, вызывая AddRef () и Количество методов Release (). CefRefPtr определяется следующим образом:
using CefRefPtr = scoped_refptr ;
typedef T element_type;
scoped_refptr(T* p) : ptr_(p) <
scoped_refptr(const scoped_refptr & r) : ptr_(r.ptr_) <
scoped_refptr(const scoped_refptr & r) : ptr_(r.get()) <
// Allow scoped_refptr to be used in boolean expression
// and comparison operations.
scoped_refptr & operator=(T* p) <
// AddRef first so that self assignment should work
scoped_refptr & operator=(const scoped_refptr & r) <
return *this = r.ptr_;
scoped_refptr & operator=(const scoped_refptr & r) <
void swap(scoped_refptr & r)
1.11 Пользовательская строка CEF
1.11.1 Зачем настраивать тип строки
Пакет libcef и основная программа могут использовать разные среды выполнения и иметь разные способы управления кучей. Все объекты, включая строки, должны быть уверены, что они используют ту же среду выполнения, что и запрошенная память кучи. Итак, вам нужно настроить тип строки.
1.11.2 Функция обработки строк CefString
CEF предоставляет набор методов языка C для управления строками (адаптация к различным кодировкам символов с помощью #define)
cef_string_set присваивает значения указанным строковым переменным (поддерживает глубокое или мелкое копирование).
cef_string_clear очищает строку.
cef_string_cmp сравнивает две строки.
1.11.3 Преобразование между CEF и String
CefString поддерживает взаимное преобразование с типами std :: string (UTF8) и std :: wstring (wide). Его также можно использовать для обертывания структуры cef_string_t для присвоения значения.
(1)stringочередьCefString
std::string str = “Some UTF8 string”;
std::wstring str = “Some wide string”;
const char* cstr = “Some ASCII string”;
(2)CefStringочередьstring
2 Введение в общие классы интерфейса Cef
2.1 CefClient
CefClient предоставляет интерфейсы для получения различных обработчиков, таких как обработчик контекстного меню, обработчик диалогового окна, обработчик состояния отображения, обработчик события загрузки, обработчик событий перетаскивания, обработчик событий поиска, обработчик клавиатуры, обработчик событий жизненного цикла, обработчик событий страницы загрузки и экран выхода. обработчик процесса рендеринга, обработчик события запроса и т. д. Но он просто возвращает дескриптор события. Конкретная функция обратного вызова каждого обработчика отсутствует в классе CefClient, и каждый класс обработчика должен быть унаследован для реализации обратного вызова. Класс CefClient имеет только одну функцию обратного вызова OnProcessMessageReceived для обработки сообщений связи между процессами. Определение CefClient следующее:
class CefClient : public virtual CefBaseRefCounted <
// Return the handler for context menus. If no handler is provided the default
// implementation will be used.
virtual CefRefPtr GetContextMenuHandler() <
// Return the handler for dialogs. If no handler is provided the default
// implementation will be used.
virtual CefRefPtr GetDialogHandler()
// Return the handler for browser display state events.
virtual CefRefPtr GetDisplayHandler()
// Return the handler for download events. If no handler is returned downloads
// will not be allowed.
virtual CefRefPtr GetDownloadHandler()
// Return the handler for drag events.
virtual CefRefPtr GetDragHandler()
// Return the handler for find result events.
virtual CefRefPtr GetFindHandler()
// Return the handler for focus events.
virtual CefRefPtr GetFocusHandler()
// Return the handler for JavaScript dialogs. If no handler is provided the
// default implementation will be used.
virtual CefRefPtr GetJSDialogHandler()
// Return the handler for keyboard events.
virtual CefRefPtr GetKeyboardHandler()
// Return the handler for browser life span events.
virtual CefRefPtr GetLifeSpanHandler()
// Return the handler for browser load status events.
virtual CefRefPtr GetLoadHandler()
// Return the handler for off-screen rendering events.
virtual CefRefPtr GetRenderHandler()
// Return the handler for browser request events.
virtual CefRefPtr GetRequestHandler()
// 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.
virtual bool OnProcessMessageReceived(CefRefPtr browser,
2.2 Класс обработки контекстного меню CefContextMenuHandler
class CefContextMenuHandler : public virtual CefBaseRefCounted <
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.
virtual void OnBeforeContextMenu(CefRefPtr browser,
// 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.
virtual bool RunContextMenu(CefRefPtr browser,
// 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
virtual bool OnContextMenuCommand(CefRefPtr browser,
// Called when the context menu is dismissed irregardless of whether the menu
// was empty or a command was selected.
virtual void OnContextMenuDismissed(CefRefPtr browser,
2.3 Класс обработки отображения веб-страницы CefDisplayHandler
CefDisplayHandler предоставляет некоторые функции обратного вызова для отображения страницы, такие как изменение отправки URL-адреса OnAddressChange, заголовок веб-страницы OnTitleChange, изменение веб-значка OnFaviconURLChange, изменение полноэкранного режима OnFullscreenModeChange, отображение подсказки OnTooltip, отображение сообщения строки состояния OnStatusMessage, обратный вызов сообщения консоли OnConsoleMessage, обратный вызов сообщения консоли OnConsoleMessage OnAutoResize, обратный вызов изменения процесса загрузки OnLoadingProgressChange, класс CefDisplayHandler определяется следующим образом
class CefDisplayHandler : public virtual CefBaseRefCounted <
// Called when a frame’s address has changed.
virtual void OnAddressChange(CefRefPtr browser,
const CefString& url) <>
// Called when the page title changes.
virtual void OnTitleChange(CefRefPtr browser,
const CefString& title) <>
// Called when the page icon changes.
virtual void OnFaviconURLChange(CefRefPtr browser,
const std::vector & icon_urls) <>
// 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.
virtual void OnFullscreenModeChange(CefRefPtr browser,
// 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.
virtual bool OnTooltip(CefRefPtr browser, CefString& text) <
// Called when the browser receives a status message. |value| contains the
// text that will be displayed in the status message.
virtual void OnStatusMessage(CefRefPtr browser,
const CefString& value) <>
// Called to display a console message. Return true to stop the message from
// being output to the console.
virtual bool OnConsoleMessage(CefRefPtr browser,
const CefString& message,
const CefString& source,
// 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
virtual bool OnAutoResize(CefRefPtr browser,
const CefSize& new_size) <
// Called when the overall page loading progress has changed. |progress|
// ranges from 0.0 to 1.0.
virtual void OnLoadingProgressChange(CefRefPtr browser,
2.4 Класс обработки загрузки веб-страницы CefDownloadHandler
CefDownloadHandler загружает класс файла на веб-страницу, предоставляет функцию обратного вызова OnBeforeDownload, чтобы начать загрузку файла с веб-страницы, и функцию обратного вызова OnDownloadUpdated для обновления хода загрузки файла.
class CefDownloadHandler : public virtual CefBaseRefCounted <
// 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
virtual void OnBeforeDownload(
const CefString& suggested_name,
CefRefPtr callback) = 0;
// 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
virtual void OnDownloadUpdated(CefRefPtr browser,
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.
class CefDragHandler : public virtual CefBaseRefCounted <
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.
virtual bool OnDragEnter(CefRefPtr browser,
// 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.
virtual void OnDraggableRegionsChanged(
const std::vector & regions) <>
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.
class CefKeyboardHandler : public virtual CefBaseRefCounted <
// 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.
virtual bool OnPreKeyEvent(CefRefPtr browser,
const CefKeyEvent& event,
// 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.
virtual bool OnKeyEvent(CefRefPtr browser,
const CefKeyEvent& event,
2.7 Класс обработки жизненного цикла 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
class CefLifeSpanHandler : public virtual CefBaseRefCounted <
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).
virtual bool OnBeforePopup(CefRefPtr browser,
const CefString& target_url,
const CefString& target_frame_name,
const CefPopupFeatures& popupFeatures,
// Called after a new browser is created. This callback will be the first
// notification that references |browser|.
virtual void OnAfterCreated(CefRefPtr browser) <>
// 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
// 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
// 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
// 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
// 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
// 10. Application exits by calling CefQuitMessageLoop() if no other browsers
// 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
// 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
// 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.
// 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
// 11. Application exits by calling CefQuitMessageLoop() if no other browsers
virtual bool DoClose(CefRefPtr browser)
// 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.
virtual void OnBeforeClose(CefRefPtr browser) <>
2.7.1 Стандартная обработка закрытия DoClose
Когда окно создается в потоке пользовательского интерфейса процесса браузера, применяется стандартный процесс закрытия с использованием CefBrowserHost :: TryCloseBrowser (). Не реализует обратный вызов DoClose и по умолчанию возвращает false. Конкретные шаги:
(1) Нажмите кнопку закрытия окна, чтобы отправить уведомление о закрытии в окно верхнего уровня.
(2) Когда окно верхнего уровня получает уведомление о закрытии, оно вызывает функцию TryCloseBrowser () и возвращает false;
(3) При выполнении дескриптора обработки onbeforeunload JS отображается диалоговое окно подтверждения закрытия.
(4) Пользователь нажимает кнопку, чтобы согласиться на закрытие;
(5) выполнение дескриптора обработки при загрузке JS;
(6) CEF отправляет уведомление о закрытии в окно верхнего уровня;
(7) Когда окно Dingying получает уведомление о закрытии, оно вызывает TryCloseBrowser и возвращает true, чтобы указать, что ему разрешено закрытие.
(8) Разрушение окна верхнего уровня
(9) Выполняется функция обратного вызова обработки OnBeforeClose программы, и браузер уничтожается.
(10) Если другого браузера нет, вызовите CefQuitMessageLoop для выхода из программы.
2.7.2 DoClose нестандартная обработка закрытия
Когда окно не создается в потоке пользовательского интерфейса процесса браузера, используется нестандартный процесс закрытия, используется функция CefBrowserHost :: CloseBrowser (false) и реализуется функция DoClose.
(1) Пользователь нажимает кнопку закрытия окна, чтобы отправить уведомление о закрытии в окно верхнего уровня.
(2) Окно верхнего уровня получает уведомление о закрытии, вызовитеCefBrowserHost::CloseBrowser(false)Функция отмены закрытия;
(3) При выполнении дескриптора обработки onbeforeunload JS отображается диалоговое окно подтверждения закрытия.
(4) Пользователь нажимает кнопку, чтобы согласиться на закрытие;
(5) выполнение дескриптора обработки при загрузке JS;
(6) Вызывается функция обратного вызова DoClose () программы, устанавливается флаг, указывающий, что следующая попытка закрытия будет разрешена, и возвращается false;
(7) CEF отправляет уведомление о закрытии в окно верхнего уровня;
(8) Окно верхнего уровня получает уведомление о закрытии в соответствии с ранее установленным флагомОпределите, закрывать ли окно.
(9) Уничтожить окно верхнего уровня;
(10) Выполняется функция обратного вызова обработки OnBeforeClose программы, и браузер уничтожается.
(11) Если нет другого браузера, вызовите CefQuitMessageLoop для выхода из программы.
2.8 Класс обработки загрузки веб-страницы CefLoadHandler
Загрузка содержимого на веб-страницу или открытие подкадра на веб-странице может перехватить сообщение и URL-адрес при открытии iframe. Может перехватывать URL подстраницы
(1) Начните загрузку OnLoadStart, после сети выполнения навигации, прежде чем начать загрузку контента, вызовите эту функцию, и процесс нескольких кадров будет загружен одновременно. Эта же страница круизом называться не будет.
(2) OnLoadEnd вызывается, когда загрузка завершена. После загрузки основного кадра подкадр будет продолжать загружаться или продолжать загрузку, и тот же переход по странице не будет вызываться.
(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).
class CefLoadHandler : public virtual CefBaseRefCounted <
typedef cef_errorcode_t ErrorCode;
typedef cef_transition_type_t TransitionType;
// Called when the loading state has changed. This callback will be executed
// 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.
virtual void OnLoadingStateChange(CefRefPtr browser,
// Called after a navigation has been committed and before the browser begins
// 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.
virtual void OnLoadStart(CefRefPtr browser,
// Called when the browser is done loading a frame. The |frame| value will
// 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
virtual void OnLoadEnd(CefRefPtr browser,
// 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.
virtual void OnLoadError(CefRefPtr browser,
const CefString& errorText,
const CefString& failedUrl) <>
2.9 Класс обработки сетевого запроса CefRequestHandler
Когда веб-страница открыта, OnBeforeBrowser из CefRequestHandler может перехватывать сетевые запросы. Он будет срабатывать только при новом открытии веб-страницы. Если веб-страница уже открыта, нажмите кнопку запроса внутри веб-страницы, чтобы запросить содержимое. Хотя есть также запросы запросов, OnBeforeBrowser не может его перехватить. Получить запрошенный URL и параметры почтового запроса можно. OnResourceRedirect также может перехватывать запросы перенаправления. CefLoadHandler также может перехватывать запросы запросов, и многие запросы GET и POST, вызываемые во время загрузки страницы, могут быть перехвачены. Тест показал, что внутренние изменения загрузки страницы CefRequestHandler не могут быть получены, и может быть получен только запрос на открытие страницы. Другая функция, OnBeforeResourceLoad, может перехватывать все запросы.Все запросы, отображаемые клавишей F12 в браузере, включая запросы на загрузку изображений, могут быть получены один за другим. Таким образом, запрос, перехваченный CefLoadHandler, более подробный: щелкните запрос, OnLoadStart и OnLoadEnd не могут быть перехвачены, но OnLoadingStateChange может перехватить запрос.
Открытие новой веб-страницы может быть заблокировано, содержимое страницы может быть изменено, или внутренний запрос вызова не может быть заблокирован.
Перехватываю все запросы, максимально подробные.
Перехватываю все запросы, максимально подробные.
OnLoadStart и OnLoadEnd
Недавно открытая страница может быть заблокирована
Откройте новую страницу, перезагрузите содержимое страницы, запросы и ответы кнопок могут быть перехвачены. Как и при загрузке некоторых изображений, загрузку CSS невозможно перехватить. Вторая деталь.
Порядок вызова каждого обратного вызова:
// Implement this interface to handle events related to browser requests. The
// methods of this class will be called on the thread indicated.
class CefRequestHandler : public virtual CefBaseRefCounted <
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 > X509CertificateList;
// 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).
(1) OnBeforeBrowse, вызываемый перед переходом браузера.
virtual bool OnBeforeBrowse(CefRefPtr browser,
// 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.
virtual bool OnOpenURLFromTab(CefRefPtr browser,
const CefString& target_url,
// 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.
(3) OnBeforeResourceLoad вызывается, когда веб-страница начинает загружать ресурсы, он может перехватывать все запросы, самые подробные.
virtual ReturnValue OnBeforeResourceLoad(
// 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
virtual CefRefPtr GetResourceHandler(
// 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
(4) Перехват запроса перенаправления OnResourceRedirect
virtual void OnResourceRedirect(CefRefPtr browser,
// 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.
(5) Функция обратного вызова после ответа на запрос OnResourceResponse
virtual bool OnResourceResponse(CefRefPtr browser,
// 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.
virtual CefRefPtr GetResourceResponseFilter(
// 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.
(6) Обратный вызов при завершении загрузки ресурса OnResourceLoadComplete.
virtual void OnResourceLoadComplete(CefRefPtr browser,
// 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
virtual bool GetAuthCredentials(CefRefPtr browser,
const CefString& host,
const CefString& realm,
const CefString& scheme,
// 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.
virtual bool CanGetCookies(CefRefPtr browser,
// 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.
virtual bool CanSetCookie(CefRefPtr browser,
const CefCookie& cookie) <
// 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.
virtual bool OnQuotaRequest(CefRefPtr browser,
const CefString& origin_url,
// 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.
virtual void OnProtocolExecution(CefRefPtr browser,
const CefString& url,
// 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.
virtual bool OnCertificateError(CefRefPtr browser,
const CefString& request_url,
// 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.
virtual bool OnSelectClientCertificate(
const CefString& host,
const X509CertificateList& certificates,
// Called on the browser process UI thread when a plugin has crashed.
// |plugin_path| is the path of the plugin that crashed.
virtual void OnPluginCrashed(CefRefPtr browser,
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
virtual void OnRenderViewReady(CefRefPtr browser) <>
// Called on the browser process UI thread when the render process
// terminates unexpectedly. |status| indicates how the process
virtual void OnRenderProcessTerminated(CefRefPtr browser,
3 расширенных приложения CEF
3.1 Взаимодействие между CEF и JavaScript
Механизм JavaScript V8, используемый CEF, используется для внутренней реализации JavaScript, и каждый фрейм имеет контекст (контекст) JS для обеспечения объема и безопасности выполнения кода JS. CEF предоставляет множество функций JS, которые могут взаимодействовать с клиентскими программами.
3.1.1 Выполнение сценария JavaScript в CEF
Сценарий приложения состоит в том, чтобы перехватить URL-запрос в CEF и перенаправить его на другой URL-адрес.Вы можете вызвать pFrame-> ExecuteJavaScript, чтобы выполнить сценарий JavaScript для достижения перехода. Конечно, могут быть реализованы и другие функции приложения.
CefRefPtr pFrame = browser->GetMainFrame();
std::string strurl = pFrame->GetURL().ToString();
std::string strname = pFrame->GetName().ToString();
if (pFrame->GetURL() == «https://10.19.141.75/portal/»)
3.1.2 Метод привязки окна реализует CEF для установки переменных JavaScript
В программе CEF создайте объект CefV8Value, получите объект окна контекста и вставьте значение переменной объекта окна.Вы можете использовать JavaScript для получения значения переменной на веб-странице. Окно привязывается к функции CefRenderProcessHandler :: OnContextCreated (). Это функция ответа создания контекста. Метод привязки окна будет загружаться каждый раз при перезагрузке фрейма (создание контекста). Программа CEF может устанавливать различные значения переменных для каждого фрейма в OnContextCreated ().
// Retrieve the context’s window object.
CefRefPtr object = context->GetGlobal();
// Create a new V8 string value. See the «Basic JS Types» section below.
CefRefPtr str = CefV8Value::CreateString(«My Value!»);
// Add the string to the window object as «window.myval». See the «JS Objects» section below.
object->SetValue(«myval», str, V8_PROPERTY_ATTRIBUTE_NONE);
JavaScript in the frame can then interact with the window bindings.
3.1.3 Метод расширения (Extension) реализует CEF и устанавливает переменные JavaScript.
Метод расширения аналогичен методу привязки окна, но метод расширения заключается в загрузке каждого кадра в контекст. После загрузки его нельзя изменить. Перед загрузкой DOM не существует. Попытка установить диапазон этого значения DOM приведет к крушение. Метод Extension регистрируется с помощью функции CefRegisterExtension () в функции CefRenderProcessHandler :: OnWebKitInitialized (), которая реализована в функции инициализации, поэтому она одинакова для каждого кадра.
// Define the extension contents.
» test.myval = ‘My Value!’;»
// Register the extension.
CefRegisterExtension(«v8/test», extensionCode, NULL);
Вызов значения переменной в JS
3.1.4 Метод привязки окна реализует CEF предоставляет функции для JavaScript.
(1) Пользовательский класс реализует класс CefV8Handler и реализует интерфейс Execute. После того, как JavaScript выполняет функцию, имя функции, параметры и ссылки на возвращаемое значение передаются в функцию Execute. Функция Execute вызывает функцию в соответствии с именем функции. Конкретная реализация функции находится в «Выполнить», а затем выполнить возвращаемое значение.
class MyV8Handler : public CefV8Handler <
virtual bool Execute(const CefString& name,
const CefV8ValueList& arguments,
CefString& exception) OVERRIDE <
// Return my string value.
retval = CefV8Value::CreateString(«My Value!»);
// Function does not exist.
// Provide the reference counting implementation for this class.
(2) Задайте имя функции для объекта окна и укажите дескриптор, который принимает вызовы.
// Retrieve the context’s window object.
CefRefPtr object = context->GetGlobal();
// Create an instance of my CefV8Handler object.
CefRefPtr handler = new MyV8Handler();
// Create the «myfunc» function.
CefRefPtr func = CefV8Value::CreateFunction(«myfunc», handler);
// Add the «myfunc» function to the «window» object.
object->SetValue(«myfunc», func, V8_PROPERTY_ATTRIBUTE_NONE);
(3) Когда JavaScript выполняет вызов функции, он входит в функцию «Выполнить», возвращает возвращаемое значение, а предупреждение отображает результат во всплывающем окне.
3.1.5 Реализуйте CEF для предоставления функций JavaScript в режиме расширения
JavaScript вызывает шаги функции в CEF:
(1) Реализуйте класс приложения, наследовать от CefApp, переписать OnWebKitInitialized и использовать функции определения строк внутри функции OnWebKitInitialized. CEF вызывает функцию CefRegisterExtension для регистрации функции с помощью JavaScript и предоставляет обработчик для обработки вызова.
class CCefClientApp : public CefApp, public CefBrowserProcessHandler, CefRenderProcessHandler
// Все интерфейсы CEF должны перегружать GetXXXHandler и возвращать это, чтобы действовать
virtual CefRefPtr GetRenderProcessHandler() override
virtual void OnWebKitInitialized() override;
// Include the default reference counting implementation.