cef概述
CEF3使用多个进程运行。处理窗口创建、绘制和网络访问的主要进程称为浏览器进程。这通常与宿主应用程序的进程相同,大多数应用程序的逻辑将在浏览器进程中运行。使用Blink引擎渲染HTML和JavaScript执行在单独的渲染进程中发生。一些应用程序逻辑(如JavaScript绑定和DOM访问)也将在渲染进程中运行。
浏览器进程(Browser Process):
- 窗口创建、绘制
- 网络访问
- ......
渲染进程(Renderer Process):
- 通过Blink引擎渲染HTML
- JavaScript执行(V8引擎)
- ......
官方示例代码如下:
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include
#include "include/cef_sandbox_win.h"
#include "tests/cefsimple/simple_app.h"
// When generating projects with CMake the CEF_USE_SANDBOX value will be defined
// automatically if using the required compiler version. Pass -DUSE_SANDBOX=OFF
// to the CMake command-line to disable use of the sandbox.
// Uncomment this line to manually enable sandbox support.
// #define CEF_USE_SANDBOX 1
#if defined(CEF_USE_SANDBOX)
// The cef_sandbox.lib static library may not link successfully with all VS
// versions.
#pragma comment(lib, "cef_sandbox.lib")
#endif
// Entry point function for all processes.
int APIENTRY wWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow) {
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// Enable High-DPI support on Windows 7 or newer.
CefEnableHighDPISupport();
void* sandbox_info = nullptr;
#if defined(CEF_USE_SANDBOX)
// Manage the life span of the sandbox information object. This is necessary
// for sandbox support on Windows. See cef_sandbox_win.h for complete details.
CefScopedSandboxInfo scoped_sandbox;
sandbox_info = scoped_sandbox.sandbox_info();
#endif
// Provide CEF with command-line arguments.
CefMainArgs main_args(hInstance);
// CEF applications have multiple sub-processes (render, plugin, GPU, etc)
// that share the same executable. This function checks the command-line and,
// if this is a sub-process, executes the appropriate logic.
int exit_code = CefExecuteProcess(main_args, nullptr, sandbox_info);
if (exit_code >= 0) {
// The sub-process has completed so return here.
return exit_code;
}
// Specify CEF global settings here.
CefSettings settings;
#if !defined(CEF_USE_SANDBOX)
settings.no_sandbox = true;
#endif
// SimpleApp implements application-level callbacks for the browser process.
// It will create the first browser instance in OnContextInitialized() after
// CEF has initialized.
CefRefPtr app(new SimpleApp);
// Initialize CEF.
CefInitialize(main_args, settings, app.get(), sandbox_info);
// Run the CEF message loop. This will block until CefQuitMessageLoop() is
// called.
CefRunMessageLoop();
// Shut down CEF.
CefShutdown();
return 0;
}
CefExecuteProcess
///
// This function should be called from the application entry point function to
// execute a secondary process. It can be used to run secondary processes from
// the browser client executable (default behavior) or from a separate
// executable specified by the CefSettings.browser_subprocess_path value. If
// called for the browser process (identified by no "type" command-line value)
// it will return immediately with a value of -1. If called for a recognized
// secondary process it will block until the process should exit and then return
// the process exit code. The |application| parameter may be empty. The
// |windows_sandbox_info| parameter is only used on Windows and may be NULL (see
// cef_sandbox_win.h for details).
///
/*--cef(api_hash_check,optional_param=application,
optional_param=windows_sandbox_info)--*/
int CefExecuteProcess(const CefMainArgs& args,
CefRefPtr application,
void* windows_sandbox_info);
翻译:
该函数应当在应用程序的入口函数处被调用,用以执行一个子进程。它可以用于执行一个可执行程序来启动一个子进程,该可执行程序可以是当前的浏览器客户端可执行程序(默认行为)或是通过设置CefSettings.browser_subprocess_path指定路径的可执行程序。如果被调用用于浏览器进程(在启动命令行中没有"type"参数),该函数会立刻返回-1。如果被调用时识别为子进程,该函数将会阻塞直到子进程退出并且返回子进程退出的返回码。application参数可以为空(null)。windows_sandbox_info参数只能在Windows上使用或设置为NULL(详见cef_sandbox_win.h)
CEF在以多进程架构下启动的时候,会多次启动自身可执行程序。启动的时候,会通过命令行参数传入某些标识,由CefExecuteProcess内部进行判断。
- 如果是主进程,则该函数立刻返回-1,程序会继续执行下去,那么后续继续运行的代码全部都运行在主进程中;
- 如果是子进程(渲染进程等),那么该函数会阻塞住,直到子进程结束后,该函数会返回一个大于等于0的值,并在main函数直接返回,进而退出。
CefApp
// SimpleApp implements application-level callbacks for the browser process.
// It will create the first browser instance in OnContextInitialized() after
// CEF has initialized.
CefRefPtr app(new SimpleApp);
释翻:
SimpleApp实现了对于浏览器进程在应用级别的回调。该实例CEF初始化后(initialized),在OnContextInitialized中会创建第一个browser实例
SimpleApp类继承自CefApp,后面会详细说明。
CefSettings
///
// Initialization settings. Specify NULL or 0 to get the recommended default
// values. Many of these and other settings can also configured using command-
// line switches.
///
typedef struct _cef_settings_t {
///
// Size of this structure.
///
size_t size;
///
// Set to true (1) to use a single process for the browser and renderer. This
// run mode is not officially supported by Chromium and is less stable than
// the multi-process default. Also configurable using the "single-process"
// command-line switch.
///
int single_process;
///
// Set to true (1) to disable the sandbox for sub-processes. See
// cef_sandbox_win.h for requirements to enable the sandbox on Windows. Also
// configurable using the "no-sandbox" command-line switch.
///
int no_sandbox;
///
// The path to a separate executable that will be launched for sub-processes.
// By default the browser process executable is used. See the comments on
// CefExecuteProcess() for details. Also configurable using the
// "browser-subprocess-path" command-line switch.
///
cef_string_t browser_subprocess_path;
///
// Set to true (1) to have the browser process message loop run in a separate
// thread. If false (0) than the CefDoMessageLoopWork() function must be
// called from your application message loop. This option is only supported on
// Windows.
///
int multi_threaded_message_loop;
///
// Set to true (1) to enable windowless (off-screen) rendering support. Do not
// enable this value if the application does not use windowless rendering as
// it may reduce rendering performance on some systems.
///
int windowless_rendering_enabled;
///
// Set to true (1) to disable configuration of browser process features using
// standard CEF and Chromium command-line arguments. Configuration can still
// be specified using CEF data structures or via the
// CefApp::OnBeforeCommandLineProcessing() method.
///
int command_line_args_disabled;
///
// The location where cache data will be stored on disk. If empty then
// browsers will be created in "incognito mode" where in-memory caches are
// used for storage and no data is persisted to disk. HTML5 databases such as
// localStorage will only persist across sessions if a cache path is
// specified. Can be overridden for individual CefRequestContext instances via
// the CefRequestContextSettings.cache_path value.
///
cef_string_t cache_path;
///
// The location where user data such as spell checking dictionary files will
// be stored on disk. If empty then the default platform-specific user data
// directory will be used ("~/.cef_user_data" directory on Linux,
// "~/Library/Application Support/CEF/User Data" directory on Mac OS X,
// "Local Settings\Application Data\CEF\User Data" directory under the user
// profile directory on Windows).
///
cef_string_t user_data_path;
///
// To persist session cookies (cookies without an expiry date or validity
// interval) by default when using the global cookie manager set this value to
// true (1). Session cookies are generally intended to be transient and most
// Web browsers do not persist them. A |cache_path| value must also be
// specified to enable this feature. Also configurable using the
// "persist-session-cookies" command-line switch. Can be overridden for
// individual CefRequestContext instances via the
// CefRequestContextSettings.persist_session_cookies value.
///
int persist_session_cookies;
///
// To persist user preferences as a JSON file in the cache path directory set
// this value to true (1). A |cache_path| value must also be specified
// to enable this feature. Also configurable using the
// "persist-user-preferences" command-line switch. Can be overridden for
// individual CefRequestContext instances via the
// CefRequestContextSettings.persist_user_preferences value.
///
int persist_user_preferences;
///
// Value that will be returned as the User-Agent HTTP header. If empty the
// default User-Agent string will be used. Also configurable using the
// "user-agent" command-line switch.
///
cef_string_t user_agent;
///
// Value that will be inserted as the product portion of the default
// User-Agent string. If empty the Chromium product version will be used. If
// |userAgent| is specified this value will be ignored. Also configurable
// using the "product-version" command-line switch.
///
cef_string_t product_version;
///
// The locale string that will be passed to WebKit. If empty the default
// locale of "en-US" will be used. This value is ignored on Linux where locale
// is determined using environment variable parsing with the precedence order:
// LANGUAGE, LC_ALL, LC_MESSAGES and LANG. Also configurable using the "lang"
// command-line switch.
///
cef_string_t locale;
///
// The directory and file name to use for the debug log. If empty a default
// log file name and location will be used. On Windows and Linux a "debug.log"
// file will be written in the main executable directory. On Mac OS X a
// "~/Library/Logs/_debug.log" file will be written where
// is the name of the main app executable. Also configurable using the
// "log-file" command-line switch.
///
cef_string_t log_file;
///
// The log severity. Only messages of this severity level or higher will be
// logged. Also configurable using the "log-severity" command-line switch with
// a value of "verbose", "info", "warning", "error", "error-report" or
// "disable".
///
cef_log_severity_t log_severity;
///
// Custom flags that will be used when initializing the V8 JavaScript engine.
// The consequences of using custom flags may not be well tested. Also
// configurable using the "js-flags" command-line switch.
///
cef_string_t javascript_flags;
///
// The fully qualified path for the resources directory. If this value is
// empty the cef.pak and/or devtools_resources.pak files must be located in
// the module directory on Windows/Linux or the app bundle Resources directory
// on Mac OS X. Also configurable using the "resources-dir-path" command-line
// switch.
///
cef_string_t resources_dir_path;
///
// The fully qualified path for the locales directory. If this value is empty
// the locales directory must be located in the module directory. This value
// is ignored on Mac OS X where pack files are always loaded from the app
// bundle Resources directory. Also configurable using the "locales-dir-path"
// command-line switch.
///
cef_string_t locales_dir_path;
///
// Set to true (1) to disable loading of pack files for resources and locales.
// A resource bundle handler must be provided for the browser and render
// processes via CefApp::GetResourceBundleHandler() if loading of pack files
// is disabled. Also configurable using the "disable-pack-loading" command-
// line switch.
///
int pack_loading_disabled;
///
// Set to a value between 1024 and 65535 to enable remote debugging on the
// specified port. For example, if 8080 is specified the remote debugging URL
// will be http://localhost:8080. CEF can be remotely debugged from any CEF or
// Chrome browser window. Also configurable using the "remote-debugging-port"
// command-line switch.
///
int remote_debugging_port;
///
// The number of stack trace frames to capture for uncaught exceptions.
// Specify a positive value to enable the CefRenderProcessHandler::
// OnUncaughtException() callback. Specify 0 (default value) and
// OnUncaughtException() will not be called. Also configurable using the
// "uncaught-exception-stack-size" command-line switch.
///
int uncaught_exception_stack_size;
///
// By default CEF V8 references will be invalidated (the IsValid() method will
// return false) after the owning context has been released. This reduces the
// need for external record keeping and avoids crashes due to the use of V8
// references after the associated context has been released.
//
// CEF currently offers two context safety implementations with different
// performance characteristics. The default implementation (value of 0) uses a
// map of hash values and should provide better performance in situations with
// a small number contexts. The alternate implementation (value of 1) uses a
// hidden value attached to each context and should provide better performance
// in situations with a large number of contexts.
//
// If you need better performance in the creation of V8 references and you
// plan to manually track context lifespan you can disable context safety by
// specifying a value of -1.
//
// Also configurable using the "context-safety-implementation" command-line
// switch.
///
int context_safety_implementation;
///
// Set to true (1) to ignore errors related to invalid SSL certificates.
// Enabling this setting can lead to potential security vulnerabilities like
// "man in the middle" attacks. Applications that load content from the
// internet should not enable this setting. Also configurable using the
// "ignore-certificate-errors" command-line switch. Can be overridden for
// individual CefRequestContext instances via the
// CefRequestContextSettings.ignore_certificate_errors value.
///
int ignore_certificate_errors;
///
// Opaque background color used for accelerated content. By default the
// background color will be white. Only the RGB compontents of the specified
// value will be used. The alpha component must greater than 0 to enable use
// of the background color but will be otherwise ignored.
///
cef_color_t background_color;
///
// Comma delimited ordered list of language codes without any whitespace that
// will be used in the "Accept-Language" HTTP header. May be overridden on a
// per-browser basis using the CefBrowserSettings.accept_language_list value.
// If both values are empty then "en-US,en" will be used. Can be overridden
// for individual CefRequestContext instances via the
// CefRequestContextSettings.accept_language_list value.
///
cef_string_t accept_language_list;
} cef_settings_t;
常用成员
- single_process:
设置为true将为浏览器和渲染使用单进程。此项也可以通过命令行参数“single-process”配置。 - no_sandbox:
沙盒是在受限的安全环境中运行应用程序的一种做法,这种做法是要限制授予应用程序的代码访问权限。沙盒中的所有改动对操作系统不会造成任何损失。设置为ture(1) 以禁止子进程的沙箱。 - browser_subprocess_path:
设置用于启动子进程单独执行器的路径。 - multi_threaded_message_loop:
为false时,可以调用CefRunMessageLoop或者CefDoMessageLoopWork函数来触发Cef消息循环,这时浏览器进程的UI线程就是调用CefRunMessageLoop或者CefDoMessageLoopWork函数的线程。当为true时。浏览器进程的UI线程是另外的线程。设置multi_threaded_message_loop为true则使用多线程消息循环。一般默认为false,使用定时器进行事件触发CefDoMessageLoopWork来进行事件处理。(仅在windows上支持此选项) - windowless_rendering_enabled:
离屏渲染,需要在CefRenderHandler里实现OnPaint。设置为true(1)以启用无窗口(屏幕外)渲染支持。如果应用程序不使用无窗口渲染,请不要启用此值,它可能会降低某些系统上的渲染性能。 - command_line_args_idsabled:
cef3和chromium中的许多特性都可以用命令行参数来设置。这些参数使用”–some-argument[=optional-param]”的格式并通过CefExecuteProcess()和CefMainArgs结构体传递给cef。
禁用命令行参数,在调用CefInitialize()函数之前,将CefSettings.command_line_args_disabled设为true。
指定主应用程序的命令行参数,需要实现CefApp::OnBeforeCommandLineProcessing()方法。
指定传递给子进程的命令行参数,需要实现CefApp::OnBeforeCommandLineProcessing()方法。 - cache_path:
设置磁盘上用于存放缓存数据的位置。如果为空则将以“隐身模式”创建浏览器,其中内存缓存用于存储,并且没有数据持久保存到磁盘。如果指定了缓存路径,则 localStorage 等HTML5数据库将仅在会话中保持不变。可以通过CefRequestContextSettings.cache_path值覆盖单个CefRequestContext实例。
如果为空,内存缓存会被某些特性使用,临时磁盘缓存会被其他地方使用。如果不为空,如HTML5本地存储数据库会跨域。 - user_data_path:
将拼写检查字典文件等用户数据存储在磁盘上的位置。如果为空,则将使用默认的特定于平台的用户数据目录(Linux上的“〜/ .cef_user_data”目录,
“Mac OS X上的〜/ Library / Application Support / CEF / User Data”目录,
Windows上用户“Local Settings\Application Data\CEF\User Data”目录)。
persist_session_cookies:
在使用全局cookie管理器时,默认情况下, 要保持会话cookie(没有到期日期或有效期的间隔),将此值设置为true(1)。会话cookie通常是暂时的,大多数Web浏览器不会持久化。A | cache_path | 还必须指定值以启用此功能。也可以使用“persist-session-cookies”命令行开关进行配置。可以通过CefRequestContextSettings.persist_session_cookies值覆盖各个CefRequestContext实例。 - persist_user_preferences:
将用户首选项作为JSON文件保存在缓存路径目录中将此值设置为true(1)。A | cache_path | 还必须指定以启用此功能。也可以使用“persist-user-preferences”命令行开关进行配置。可以通过 CefRequestContextSettings.persist_user_preferences值覆盖各个CefRequestContext实例。 - user_agent:
设置客户端标识,服务器可以识别是从哪里发来的请求。 - product_version:
将作为默认User-Agent字符串的产品部分插入的值。如果为空,将使用Chromium产品版本。如果 | userAgent | 指定此值将被忽略。也可以配置使用“product-version”命令行开关。 - locale :
此设置项将传递给Blink。如果此项为空,将使用默认值“en-US”。在Linux平台下此项被忽略,使用环境变量中的值,解析的依次顺序为:LANGUAE,LC_ALL,LC_MESSAGES和LANG。此项也可以通过命令行参数“lang”配置。 - log_file :
此项设置的文件夹和文件名将用于输出debug日志。如果此项为空,默认的日志文件名为debug.log,位于应用程序所在的目录。此项也可以通过命令参数“log-file”配置。 - log_severity :
此项设置日志级别。只有此等级、或者比此等级高的日志的才会被记录。此项可以通过命令行参数“log-severity”配置,可以设置的值为“verbose”,“info”,“warning”,“error”,“error-report”,“disable”。 - javascript_flags :
初始化V8 JavaScript引擎时将使用的自定义标志。使用自定义标志的后果可能未经过充分测试。也使用“JS-标志”命令行开关//配置。 - resources_dir_path :
此项设置资源文件夹的位置。如果此项为空,Windows平台下cef.pak、devtools_resourcs.pak、Mac OS X下的app bundle Resources目录必须位于组件目录。此项也可以通过命令行参数“resource-dir-path”配置。 - locales_dir_path :
此项设置locale文件夹位置。如果此项为空,locale文件夹必须位于组件目录,在Mac OS X平台下此项被忽略,pak文件从app bundle Resources目录。此项也可以通过命令行参数“locales-dir-path”配置。 - pack_loading_disabled :
设置为true(1)以禁用资源和区域设置的包文件加载。如果禁用了包文件的加载,则必须为浏览器提供资源包处理程序并通过CefApp :: GetResourceBundleHandler()呈现进程。也可以使用“disable-pack-loading”命令 进行开关进行配置。 - remote_debugging_port :
此项可以设置1024-65535之间的值,用于在指定端口开启远程调试。例如,如果设置的值为8080,远程调试的URL为http://localhost:8080。CEF或者Chrome浏览器能够调试CEF。此项也可以通过命令行参数“remote-debugging-port”配置。 - uncaught_exception_stack_size :
捕获未捕获异常的堆栈跟踪帧数。指定一个正值以启用CefRenderProcessHandler::OnUncaughtException()回调。指定0(默认值)和不会调用OnUncaughtException()。也可以使用uncaught-exception-stack-size”命令行开关进行配置。 - context_safety_implementation
- ignore_certificate_errors:
设置为true(1)以忽略与无效SSL证书相关的错误。启用此设置可能会导致潜在的安全漏洞,例如“中间人”攻击。从Internet 加载内容的应用程序不应启用此设置。也可以使用“ignore-certificate-errors”命令行开关进行配置。可以通过 CefRequestContextSettings.ignore_certificate_errors值覆盖各个CefRequestContext实例。 - background_color:
在加载文档之前和没有指定文档颜色时用于浏览器的背景颜色。alpha分量必须是完全不透明(0xFF)或完全透明(0x00)。如果alpha分量完全是不透明的,则RGB分量将用作背景颜色。如果 alpha组件对于窗口浏览器完全透明,则使用默认值opaque white。如果alpha组件对于无窗口(屏幕外)浏览器是完全透明的,那么将启用透明绘制 - ccept_language_list :
逗号分隔的有序语言代码列表,没有任何空格将在“Accept-Language”HTTP标头中使用。可以使用CefBrowserSettings.accept_language_list值在每个浏览器的基础上覆盖。如果两个值都为空,则使用“en-US,en”。可以通过CefRequestContextSettings.accept_language_list值覆盖各个CefRequestContext实例。
一些重要接口说明
//用于检测是当前进程是否是浏览器进程(main入口函数调用)
int CefExecuteProcess(const CefMainArgs& args, CefRefPtr application, void* windows_sandbox_info);
//主线程里面初始化Cef 浏览器进程信息
bool CefInitialize(const CefMainArgs& args,const CefSettings& settings,CefRefPtr application, void* windows_sandbox_info);
//浏览器进程退出的时候调用
void CefShutdown();
//在CefInitialize之后调用,建议使用CefRunMessageLoop替代CefDoMessageLoopWork,
如果使用此函数那么将会回调CefBrowserProcessHandler::OnScheduleMessagePumpWork()
void CefDoMessageLoopWork();
//运行Cef 消息环,如果调用CefQuitMessageLoop则退出消息环
void CefRunMessageLoop();
//通知cef消息环退出
void CefQuitMessageLoop();
//调用windows Api进入模态消息环之前设置为true,退出模态消息环的时候设置为false,例如TrackPopupMenu
void CefSetOSModalLoop(bool osModalLoop);
//启用高DPI支持
void CefEnableHighDPISupport();