Class CefriumBrowser
Two rendering modes are available:
- Off-screen (OSR) — frames delivered as BGRA pixel buffers
via
CefriumRenderHandler.onPaint(int, int, ByteBuffer). Use for headless rendering, screenshots, or custom compositing. Create withCefriumBrowser(int, int, float). - Surface — hardware-accelerated rendering to an Android Surface
via ContentViewRenderView. Supports video, audio, touch, DRM.
Create with
createWithSurface(android.app.Activity).
Lifecycle: Call onPause() / onResume() from your
Activity lifecycle. Call close() when done — this releases native
resources. Do not call any method after close().
Threading: All methods must be called on the UI thread.
// Surface mode (recommended for most apps)
CefriumBrowser browser = CefriumBrowser.createWithSurface(activity);
layout.addView(browser.getSurfaceContainer());
browser.loadUrl("https://example.com");
// OSR mode (headless / screenshots)
CefriumBrowser browser = new CefriumBrowser(1080, 1920, 2.75f);
browser.setRenderHandler((w, h, pixels) -> { });
browser.loadUrl("https://example.com");
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfacestatic interfaceReceives the captured page bitmap (null on failure).static classUnified callback interface for browser events.static interfaceRicher download handler that can allow/deny a download before it starts and cancel/pause/resume one in progress.static final classA candidate device offered to aCefriumBrowser.DeviceChooserSession.static final classAn HTTP cookie read from the browser's cookie store.static interfaceReceives the result ofgetCookies(String, CefriumBrowser.CookieCallback).static interfacePresents device chooser UI for the frontier web device APIs.static interfaceA live device chooser.static final classSnapshot of a download plus in-progress controls.static interfaceReceives the app's credentials (or cancel) for an HTTP auth challenge.static interfaceSupplies credentials for an HTTP or proxy authentication challenge (the WebViewonReceivedHttpAuthRequestequivalent).static interfaceReceives an image fetched viadownloadImage(String, int, ImageCallback).static interfaceResolves a JS dialog.static interfaceHandles page JS dialogs (alert/confirm/prompt).static classOne entry in the navigation history.static interfaceListener for context menu events (long press on links/images).static interfaceListener for download progress updates.static interfaceListener for find-in-page results.static interfaceListener for fullscreen mode changes.static interfaceListener for loading state changes.static interfaceListener for renderer-process termination.static interfaceListener for network requests.static interfaceListener for title changes.static interfaceListener for URL changes.static interfacestatic interfaceReceives the app's grant/deny decision for a permission request.static interfaceDecides web permission requests (geolocation, camera, mic, ...).static interfaceHandles popups (window.open / target=_blank).static interfaceResolves aCefriumBrowser.QueryHandlerquery back to JavaScript.static interfaceHandles JavaScriptwindow.cefriumQuery({request, onSuccess, onFailure})calls from page content (the JS ↔ native bridge).final classExecutes the OSR text-selection quick-menu choice.static interfaceDecides whether to block outgoing requests.static interfaceReceives the app's proceed/cancel decision for an invalid certificate.static interfaceDecides whether to continue loading a URL whose TLS certificate failed validation (the WebViewonReceivedSslErrorequivalent). -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intDevice chooser kinds, passed toCefriumBrowser.DeviceChooserHandler.static final intstatic final intstatic final intalert()static final intconfirm()static final intprompt()static final intKey event type: character (matches CEFKEYEVENT_CHAR).static final intKey event type: key down (matches CEFKEYEVENT_KEYDOWN).static final intKey event type: raw key down (matches CEFKEYEVENT_RAWKEYDOWN).static final intKey event type: key up (matches CEFKEYEVENT_KEYUP).static final intMouse button for the click APIs (matches CEF's MBT_LEFT/MIDDLE/RIGHT).static final intstatic final intstatic final intstatic final intstatic final intModifier bit flags for mouse events; OR them together (0 = none).static final intstatic final intClipboard read (navigator.clipboard.readText).static final intPermission types (bitmask, from cef_permission_request_types_t).static final intstatic final intWeb NFC (NDEFReader scan/write).static final intstatic final Stringstatic final StringProxy modes forsetProxy(String, String)(Chromium proxy modes).static final Stringstatic final Stringstatic final Stringstatic final intQuick-menu edit-state flag: Copy is available.static final intQuick-menu edit-state flag: Cut is available (matches CEF QM_EDITFLAG_CAN_CUT).static final intQuick-menu edit-state flag: Paste is available.static final intstatic final intstatic final intstatic final intstatic final intstatic final intstatic final intstatic final intContent setting values forsetContentSetting(String, int, int).static final intTermination status: process exited abnormally.static final intTermination status: process crashed.static final intTermination status: process was killed (e.g.static final intTermination status: process ran out of memory.static final intDecimal keyboard.static final intDefault input mode (a normal focused field): show the keyboard.static final intEmail keyboard.static final intNo virtual keyboard (nothing focused, or inputmode="none"): hide it.static final intNumeric keyboard.static final intSearch keyboard.static final intTelephone keypad.static final intPlain text keyboard.static final intURL keyboard. -
Constructor Summary
ConstructorsConstructorDescriptionCreate a new off-screen browser with default settings.CefriumBrowser(int width, int height) Create a new off-screen browser with specified viewport size.CefriumBrowser(int width, int height, float scale) Create a new off-screen browser with specified viewport size and device scale factor. -
Method Summary
Modifier and TypeMethodDescriptionstatic intExact number of live renderer processes the engine currently has -- countsRenderProcessHostonly, so utility/network/audio/storage and GPU child processes are NOT included (this is the clean renderer count, unlikeps | grep sandboxed_processwhich mixes them all).voidcancelDownload(int id) Cancel an in-progress download by itsid.booleanvoidcaptureBitmap(CefriumBrowser.BitmapCallback callback) Captures the current page to aBitmap, delivered asynchronously on the main thread.voidClears the browser's HTTP cache.booleanConvenience: disable proxying (direct connection).voidclose()Close this browser and release all native resources.static intCumulative number of browsers that have finished closing (theirOnBeforeClosefired).voidcontextMenuCommand(int commandId) Send the user's context menu selection back to CEF.static CefriumBrowsercreateWithSurface(android.app.Activity activity) Create a browser that renders directly to an Android Surface.static CefriumBrowsercreateWithSurface(android.app.Activity activity, boolean incognito) LikecreateWithSurface(android.app.Activity)but for a private (incognito) tab.voiddeleteCookies(String url, String name) Deletes cookies forurl;namenull/empty = all for the URL.voiddownloadImage(String url, int maxSize, CefriumBrowser.ImageCallback callback) Fetches an image (e.g.voidevaluateJavaScript(String script) Execute JavaScript in the browser's main frame (fire-and-forget).voidProgrammatically exit HTML fullscreen (e.g.voidfileDialogResult(long id, String[] paths) Delivers a file-chooser selection (empty/null cancels).voidSearch for text in the current page.voidPersists the cookie store to disk.intGet the number of blocked ad/tracking requests since the browser was created.voidgetCookies(String url, CefriumBrowser.CookieCallback callback) Reads cookies visible tourl; the callback fires on the UI thread.Returns the back/forward history with titles, oldest-first.android.widget.FrameLayoutGet the container View for Surface rendering.getUrl()The current top-level URL, ornullbefore the first navigation.voidgoBack()Navigate back in history.voidNavigate forward in history.voidCancel the current composition, discarding the composed text.voidimeCommitText(String text, int relativeCursorPos) Commit text, ending any active composition.voidimeFinishComposingText(boolean keepSelection) Complete the current composition, keeping the composed text.voidimeSetComposition(String text, int selStart, int selEnd) Set (or update) the current IME composition.voidForce the browser to repaint.booleanWhether the page's audio is currently muted viasetAudioMuted(boolean).booleanbooleanbooleanWhether this browser currently has audible media playing -- at least one audio media session that is not paused.static intLive (not-yet-closed) browser instances.voidloadDataWithBaseUrl(String baseUrl, String data, String mimeType, String encoding, String historyUrl) Loads a data string with an explicit base URL, mirroring Android WebView'sWebView.loadDataWithBaseURL(String, String, String, String, String).voidLoads an HTML string directly (served to the engine as a data: URL).voidloadHtmlWithBaseUrl(String html, String baseUrl) Convenience: load an HTML string with the given base URL (text/html, utf-8, history = baseUrl).voidNavigate to a URL.booleanonActivityResult(int requestCode, int resultCode, android.content.Intent data) Forward Activity result to the browser for intent handling (file picker, permissions, etc.).voidonPause()Convenience for "host is backgrounding": hide the page, suspend media and mute audio so inline audio/video actually stops (visibility HIDDEN alone keeps background audio playing).voidonResume()Convenience for "host is foregrounding": unmute, make the page visible and resume media suspended byonPause().voidpauseDownload(int id) Pause an in-progress download by its id.voidLoadsurlwith an HTTP POST body.voidprintToPdf(String filePath, CefriumBrowser.PdfCallback callback) Renders the current page to a PDF atfilePath(async).static voidShuts down render child-processes left orphaned after browsers were closed (e.g.voidreload()Reload the current page.voidrestoreNavigationState(byte[] state) Restores a navigation stack captured byserializeNavigationState().voidrestoreState(android.os.Bundle state) Restores state previously captured bysaveState()— re-navigates to the saved URL.voidresumeDownload(int id) Resume a paused download by its id.voidResumes media suspended bysuspendMedia()(resumes where it left off).android.os.BundleCaptures restorable browser state (the current URL) into a Bundle.voidsendDoubleClick(int x, int y) Double left click at (x, y).voidsendKeyEvent(int type, int modifiers, int windowsKeyCode, int nativeKeyCode, char character) Send a key event to the browser (OSR).voidsendLeftClick(int x, int y) Left click at (x, y).voidsendMouseClick(int x, int y, int button) Click at (x, y) with the given button (down + up).voidsendMouseClick(int x, int y, int button, int clickCount, int modifiers) Click at (x, y) with a button, click count, and modifiers (down + up).voidsendMouseDown(int x, int y, int button, int modifiers) Press a mouse button at (x, y) without releasing it.voidsendMouseLeave(int x, int y) Signal the pointer leaving the view at (x, y) (clears:hover).voidsendMouseMove(int x, int y) Move the mouse pointer to (x, y).voidsendMouseMove(int x, int y, int modifiers) Move the pointer to (x, y) with modifier keys held (see MOUSE_MODIFIER_*).voidsendMouseUp(int x, int y, int button, int modifiers) Release a mouse button at (x, y).voidsendMouseWheel(int x, int y, int deltaX, int deltaY) Scroll the mouse wheel at (x, y).voidsendMouseWheel(int x, int y, int deltaX, int deltaY, int modifiers) Scroll the mouse wheel at (x, y) with modifier keys held.voidsendRightClick(int x, int y) Right click at (x, y).voidsendSwipe(float x1, float y1, float x2, float y2, int steps) Swipe from (x1, y1) to (x2, y2) as a down +stepsmoves + up -- drives scrolling/flinging.voidsendTap(float x, float y) Tap at (x, y): a finger down immediately followed by up.voidsendTouchDown(float x, float y) Press a finger down at (x, y).voidsendTouchEvent(int action, float x, float y, int pointerId) Forward a touch event to the browser.voidsendTouchMove(float x, float y) Move the pressed finger to (x, y).voidsendTouchUp(float x, float y) Lift the finger at (x, y).byte[]Serializes this tab's full back/forward navigation stack (each entry's URL and blink PageState, plus the current index) for session restore.voidsetAudioHandler(CefriumAudioHandler handler) Sets the audio handler.voidsetAudioMuted(boolean muted) Mutes/unmutes ALL audio output of the page (keeps media decoding/playing, just silenced).voidsetCallback(CefriumBrowser.Callback callback) Set a unified callback for all browser events.voidsetCommandHandler(CefriumCommandHandler handler) Sets the Chrome command handler.voidsetContentSetting(String requestingUrl, int permission, int value) Sets a per-origin web-permission content setting without showing a prompt.voidSets a session cookie forurl(domain/path inferred from the URL).voidSets a session cookie forurlwith explicit attributes.voidsetCookieFilterEnabled(boolean enabled) Enable the opt-in per-cookie access filter (CefriumRequestHandler.onCanSendCookie(String, String, String)/onCanSaveCookie).voidsetDarkMode(boolean dark) Set dark mode via CEF API (CefRequestContext::SetChromeColorSchemeMode).voidSets the device chooser handler (null = cancel all device requests).voidsetDialogHandler(CefriumDialogHandler handler) Sets the file-chooser dialog handler (<input type=file>).voidsetDisplayHandler(CefriumDisplayHandler handler) Sets the display handler (favicon, progress, console, status, media).voidSet the controllable download handler (allow/deny + cancel/pause/resume).voidsetDragHandler(CefriumDragHandler handler) Sets the drag handler.voidsetFocusHandler(CefriumFocusHandler handler) Sets the focus handler.voidsetFrameHandler(CefriumFrameHandler handler) Sets the frame lifecycle handler.voidSets the HTTP auth handler (null = cancel every auth challenge).voidsetJavaScriptEnabled(boolean enabled) Enables/disables JavaScript at runtime (Emulation.setScriptExecutionDisabled).voidSets a custom JS-dialog handler (null = default Android AlertDialog).voidsetKeyboardHandler(CefriumKeyboardHandler handler) Sets the keyboard handler (intercept keys before the page).voidsetLoadHandler(CefriumLoadHandler handler) Sets the per-frame load handler (load start / error).voidsetMediaSessionActivity(android.app.PendingIntent activity) Sets the PendingIntent fired when the user taps this browser's media control (notification / lock-screen player).voidsetMediaSessionEnabled(boolean enabled) Enables system media controls (lock-screen + notification shade) for this browser's playback, driven by the page'snavigator.mediaSession.voidSet the listener for context menu events.voidSet the listener for download progress updates.voidSet the listener for find-in-page results.voidSet a listener for fullscreen mode changes.voidSet a listener for loading state changes.voidSet a listener notified when a renderer process for this browser dies.voidSet a listener for network request interception.voidSet a listener for title changes.voidSet a listener for URL changes during navigation.voidsetPageVisible(boolean visible) Sets the page's visibility (compositor + Page Visibility APIdocument.hidden).voidSets the permission handler (null = deny all web permission requests).voidsetPinchToZoomEnabled(boolean enabled) Enables or disables pinch-to-zoom (and page zoom) for arbitrary page content.voidSets a popup handler (null = load popups in this browser).booleanConvenience: route all traffic through a fixed proxy"host:port".booleanConfigures the proxy for this browser's request context.voidsetPullToRefreshEnabled(boolean enabled) Enable pull-to-refresh: an overscroll-down gesture at the top of the page reloads it (Chrome-style).voidRegisters the handler forwindow.cefriumQuerycalls.voidsetRenderHandler(CefriumRenderHandler handler) Set the render handler to receive painted frames (OSR mode only).voidsetRequestHandler(CefriumRequestHandler handler) voidsetRequestInterceptor(CefriumBrowser.RequestInterceptor interceptor) Sets a programmatic request interceptor (null clears it).voidsetResponseTapEnabled(boolean enabled) Enable the opt-in response-body tap (CefriumRequestHandler.onResponseData(String, ByteBuffer)).voidSets the SSL/certificate error handler (null = cancel on every cert error).voidsetUserAgentOverride(String userAgent) Overrides the User-Agent at runtime (Emulation.setUserAgentOverride).voidsetZoomLevel(double zoomLevel) Sets the zoom level (0 = 100%; factor = 1.2^level).voidstartDownload(String url) Force a download ofurl.voidHard-stops all media players (not resumable likesuspendMedia()) and mutes audio.voidstopFinding(boolean clearSelection) Stop the current find-in-page search.voidStops the current load.voidStops the page's media session and dismisses its media notification.voidSuspends active media (audio + video) at the browser-process level (MediaSession Suspend == the audio-focus-loss path).static intTotal live RenderFrameHosts across all renderer processes -- the real "working frame" count (host pages + iframes).static intRenderer processes that currently host ZERO frames -- reuse "zombies" the pool's reap targets.
-
Field Details
-
TERMINATION_ABNORMAL
public static final int TERMINATION_ABNORMALTermination status: process exited abnormally.- See Also:
-
TERMINATION_KILLED
public static final int TERMINATION_KILLEDTermination status: process was killed (e.g. by the OS low-memory killer).- See Also:
-
TERMINATION_CRASHED
public static final int TERMINATION_CRASHEDTermination status: process crashed.- See Also:
-
TERMINATION_OOM
public static final int TERMINATION_OOMTermination status: process ran out of memory.- See Also:
-
SAME_SITE_UNSPECIFIED
public static final int SAME_SITE_UNSPECIFIED- See Also:
-
SAME_SITE_NONE
public static final int SAME_SITE_NONE- See Also:
-
SAME_SITE_LAX
public static final int SAME_SITE_LAX- See Also:
-
SAME_SITE_STRICT
public static final int SAME_SITE_STRICT- See Also:
-
JS_DIALOG_ALERT
public static final int JS_DIALOG_ALERTalert()- See Also:
-
JS_DIALOG_CONFIRM
public static final int JS_DIALOG_CONFIRMconfirm()- See Also:
-
JS_DIALOG_PROMPT
public static final int JS_DIALOG_PROMPTprompt()- See Also:
-
PERMISSION_GEOLOCATION
public static final int PERMISSION_GEOLOCATIONPermission types (bitmask, from cef_permission_request_types_t).- See Also:
-
PERMISSION_CAMERA
public static final int PERMISSION_CAMERA- See Also:
-
PERMISSION_MICROPHONE
public static final int PERMISSION_MICROPHONE- See Also:
-
PERMISSION_NOTIFICATIONS
public static final int PERMISSION_NOTIFICATIONS- See Also:
-
PERMISSION_CLIPBOARD
public static final int PERMISSION_CLIPBOARDClipboard read (navigator.clipboard.readText). Writing needs no prompt.- See Also:
-
PERMISSION_NFC
public static final int PERMISSION_NFCWeb NFC (NDEFReader scan/write). Also declareandroid.permission.NFCin your manifest and have NFC enabled on the device. Grant this in yourCefriumBrowser.PermissionHandler(or pre-authorize viasetContentSetting(String, int, int)withSETTING_ALLOW).- See Also:
-
SETTING_DEFAULT
public static final int SETTING_DEFAULTContent setting values forsetContentSetting(String, int, int).- See Also:
-
SETTING_ALLOW
public static final int SETTING_ALLOW- See Also:
-
SETTING_BLOCK
public static final int SETTING_BLOCK- See Also:
-
SETTING_ASK
public static final int SETTING_ASK- See Also:
-
PROXY_DIRECT
Proxy modes forsetProxy(String, String)(Chromium proxy modes).- See Also:
-
PROXY_SYSTEM
- See Also:
-
PROXY_AUTO_DETECT
- See Also:
-
PROXY_FIXED
- See Also:
-
PROXY_PAC
- See Also:
-
DEVICE_BLUETOOTH
public static final int DEVICE_BLUETOOTHDevice chooser kinds, passed toCefriumBrowser.DeviceChooserHandler.- See Also:
-
DEVICE_USB
public static final int DEVICE_USB- See Also:
-
DEVICE_SERIAL
public static final int DEVICE_SERIAL- See Also:
-
QM_CAN_CUT
public static final int QM_CAN_CUTQuick-menu edit-state flag: Cut is available (matches CEF QM_EDITFLAG_CAN_CUT).- See Also:
-
QM_CAN_COPY
public static final int QM_CAN_COPYQuick-menu edit-state flag: Copy is available.- See Also:
-
QM_CAN_PASTE
public static final int QM_CAN_PASTEQuick-menu edit-state flag: Paste is available.- See Also:
-
TEXT_INPUT_MODE_DEFAULT
public static final int TEXT_INPUT_MODE_DEFAULTDefault input mode (a normal focused field): show the keyboard.- See Also:
-
TEXT_INPUT_MODE_NONE
public static final int TEXT_INPUT_MODE_NONENo virtual keyboard (nothing focused, or inputmode="none"): hide it.- See Also:
-
TEXT_INPUT_MODE_TEXT
public static final int TEXT_INPUT_MODE_TEXTPlain text keyboard.- See Also:
-
TEXT_INPUT_MODE_TEL
public static final int TEXT_INPUT_MODE_TELTelephone keypad.- See Also:
-
TEXT_INPUT_MODE_URL
public static final int TEXT_INPUT_MODE_URLURL keyboard.- See Also:
-
TEXT_INPUT_MODE_EMAIL
public static final int TEXT_INPUT_MODE_EMAILEmail keyboard.- See Also:
-
TEXT_INPUT_MODE_NUMERIC
public static final int TEXT_INPUT_MODE_NUMERICNumeric keyboard.- See Also:
-
TEXT_INPUT_MODE_DECIMAL
public static final int TEXT_INPUT_MODE_DECIMALDecimal keyboard.- See Also:
-
TEXT_INPUT_MODE_SEARCH
public static final int TEXT_INPUT_MODE_SEARCHSearch keyboard.- See Also:
-
KEY_RAW_DOWN
public static final int KEY_RAW_DOWNKey event type: raw key down (matches CEFKEYEVENT_RAWKEYDOWN).- See Also:
-
KEY_DOWN
public static final int KEY_DOWNKey event type: key down (matches CEFKEYEVENT_KEYDOWN).- See Also:
-
KEY_UP
public static final int KEY_UPKey event type: key up (matches CEFKEYEVENT_KEYUP).- See Also:
-
KEY_CHAR
public static final int KEY_CHARKey event type: character (matches CEFKEYEVENT_CHAR).- See Also:
-
MOUSE_BUTTON_LEFT
public static final int MOUSE_BUTTON_LEFTMouse button for the click APIs (matches CEF's MBT_LEFT/MIDDLE/RIGHT).- See Also:
-
MOUSE_BUTTON_MIDDLE
public static final int MOUSE_BUTTON_MIDDLE- See Also:
-
MOUSE_BUTTON_RIGHT
public static final int MOUSE_BUTTON_RIGHT- See Also:
-
MOUSE_MODIFIER_SHIFT
public static final int MOUSE_MODIFIER_SHIFTModifier bit flags for mouse events; OR them together (0 = none).- See Also:
-
MOUSE_MODIFIER_CTRL
public static final int MOUSE_MODIFIER_CTRL- See Also:
-
MOUSE_MODIFIER_ALT
public static final int MOUSE_MODIFIER_ALT- See Also:
-
-
Constructor Details
-
CefriumBrowser
public CefriumBrowser()Create a new off-screen browser with default settings. -
CefriumBrowser
public CefriumBrowser(int width, int height) Create a new off-screen browser with specified viewport size. Device scale factor defaults to 1.0 (desktop). For mobile, useCefriumBrowser(int, int, float).- Parameters:
width- Viewport width in physical pixels.height- Viewport height in physical pixels.
-
CefriumBrowser
public CefriumBrowser(int width, int height, float scale) Create a new off-screen browser with specified viewport size and device scale factor.The scale factor controls how CSS pixels map to physical pixels. For example, on a 1080px wide screen with scale 2.75, the CSS viewport is ~393px — triggering mobile layouts.
- Parameters:
width- Viewport width in physical pixels.height- Viewport height in physical pixels.scale- Device scale factor (e.g., 2.75 for Xiaomi Redmi Note 13 Pro).
-
-
Method Details
-
setRenderHandler
Set the render handler to receive painted frames (OSR mode only). Each frame is a BGRA pixel buffer with dimensions matching the viewport size set in the constructor.- Parameters:
handler- The handler to receive OnPaint callbacks, or null to stop.- See Also:
-
loadUrl
Navigate to a URL. Supports http://, https://, file://, and data: URLs. If the scheme is omitted, https:// is NOT added automatically — pass the full URL.- Parameters:
url- The URL to load.
-
goBack
public void goBack()Navigate back in history. No-op ifcanGoBack()is false. -
goForward
public void goForward()Navigate forward in history. No-op if there is no forward history. -
setPullToRefreshEnabled
public void setPullToRefreshEnabled(boolean enabled) Enable pull-to-refresh: an overscroll-down gesture at the top of the page reloads it (Chrome-style). Off by default. Call this BEFORE the page loads (the handler is bound once, when the WebContents connects); it must not be toggled on a live WebContents. -
setDarkMode
public void setDarkMode(boolean dark) Set dark mode via CEF API (CefRequestContext::SetChromeColorSchemeMode). Call after browser is created and loaded.- Parameters:
dark- true for dark mode, false for light mode.
-
setCallback
Set a unified callback for all browser events. This is the recommended way to handle events. Individual setOnXxxListener methods are also available for convenience. -
setOnUrlChangedListener
Set a listener for URL changes during navigation. -
setOnTitleChangedListener
Set a listener for title changes. -
setOnFullscreenChangedListener
Set a listener for fullscreen mode changes. -
setOnRequestInterceptedListener
Set a listener for network request interception. Called for EVERY request — use for network inspection, debugging, or custom request auditing. -
getUrl
The current top-level URL, ornullbefore the first navigation. -
saveState
public android.os.Bundle saveState()Captures restorable browser state (the current URL) into a Bundle. Call fromActivity.onSaveInstanceStateand pass the result torestoreState(Bundle)after recreating the browser. -
restoreState
public void restoreState(android.os.Bundle state) Restores state previously captured bysaveState()— re-navigates to the saved URL. No-op ifstateis null or holds no saved URL. -
setOnLoadingStateChangedListener
Set a listener for loading state changes. -
setOnRenderProcessTerminatedListener
public void setOnRenderProcessTerminatedListener(CefriumBrowser.OnRenderProcessTerminatedListener listener) Set a listener notified when a renderer process for this browser dies. The native CefRequestHandler is always installed, so no extra wiring is needed -- the callback fires whenever the renderer terminates. -
reload
public void reload()Reload the current page. Uses CefBrowserHost::Reload (ignores cache). -
evaluateJavaScript
Execute JavaScript in the browser's main frame (fire-and-forget). Uses CefFrame::ExecuteJavaScript. The script's return value is not delivered back to the caller; a result-returning JS bridge is a separate feature built on CefMessageRouter.- Parameters:
script- JavaScript source to execute. Ignored if null.
-
setQueryHandler
Registers the handler forwindow.cefriumQuerycalls. -
setCookie
-
setCookie
public void setCookie(String url, String name, String value, boolean secure, boolean httpOnly, int sameSite) Sets a session cookie forurlwith explicit attributes. Use this for cookies a third-party/cross-site context must send (e.g. a consent cookie an embedded iframe needs): passsecure=trueandsameSite=SAME_SITE_NONE-- Chromium rejectsSameSite=NonewithoutSecure. domain/path are inferred from the URL. -
getCookies
Reads cookies visible tourl; the callback fires on the UI thread. -
deleteCookies
-
flushCookies
public void flushCookies()Persists the cookie store to disk. -
clearCache
public void clearCache()Clears the browser's HTTP cache. -
printToPdf
Renders the current page to a PDF atfilePath(async). -
setUserAgentOverride
Overrides the User-Agent at runtime (Emulation.setUserAgentOverride). -
setJavaScriptEnabled
public void setJavaScriptEnabled(boolean enabled) Enables/disables JavaScript at runtime (Emulation.setScriptExecutionDisabled). -
setZoomLevel
public void setZoomLevel(double zoomLevel) Sets the zoom level (0 = 100%; factor = 1.2^level). -
setPinchToZoomEnabled
public void setPinchToZoomEnabled(boolean enabled) Enables or disables pinch-to-zoom (and page zoom) for arbitrary page content. Enabled by default, matching a normal browser.When disabled, a small script is injected on every load-finish that forces a non-user-scalable viewport (
user-scalable=no, maximum-scale=1) and blocks the multi-touch pinch gesture. This is applied on top of whatever viewport the page declares, so it works for pages you do not control. If you DO control the HTML, declaring that viewport meta yourself is equivalent and takes effect from first paint.Because the neutralizer runs at load-finish (not document-start), a page could in principle be pinched during the brief pre-load window; for a hard guarantee from first paint, ship the viewport meta in the page.
- Parameters:
enabled- true to allow zoom (default), false to disable it.
-
isPinchToZoomEnabled
public boolean isPinchToZoomEnabled()- Returns:
- whether pinch/page zoom is currently enabled (default true).
-
loadHtml
Loads an HTML string directly (served to the engine as a data: URL). -
loadDataWithBaseUrl
public void loadDataWithBaseUrl(String baseUrl, String data, String mimeType, String encoding, String historyUrl) Loads a data string with an explicit base URL, mirroring Android WebView'sWebView.loadDataWithBaseURL(String, String, String, String, String). Unlike WebView, Cefrium delivers the content as a GENUINE network response atbaseUrl(not adata:document), so the loaded document has a real, network-served origin ==baseUrl. This is what lets inline embedded players that require a network-served parent -- notably the YouTube IFrame player -- play; adata:document is rejected by such players (Error 152), which is why the same content fails under WebView'sloadDataWithBaseURL.Origin guidance: pass your own app origin as
baseUrl(as any website embedding YouTube does), e.g."https://app.example.com"-- NOT"https://www.youtube.com". YouTube rejects same-origin self-embedding with Error 152.- Parameters:
baseUrl- network origin for the document, e.g."https://app.example.com"data- the HTML (or other) content to loadmimeType- content type, e.g."text/html"(defaults to text/html if null/empty)encoding- charset, e.g."utf-8"(defaults to utf-8 if null/empty)historyUrl- URL used for the document's virtual/history URL (defaults to baseUrl if null/empty)
-
loadHtmlWithBaseUrl
Convenience: load an HTML string with the given base URL (text/html, utf-8, history = baseUrl). The document is served from a real network origin ==baseUrl, so an inline YouTube IFrame embedded inhtmlplays. Pass YOUR OWN app origin asbaseUrl, e.g.loadHtmlWithBaseUrl("<iframe src='https://www.youtube.com/embed/ID'></iframe>", "https://app.example.com")-- not"https://www.youtube.com"(YouTube rejects same-origin self-embedding). SeeloadDataWithBaseUrl(String, String, String, String, String). -
postUrl
Loadsurlwith an HTTP POST body. -
stopLoading
public void stopLoading()Stops the current load. -
setRequestInterceptor
Sets a programmatic request interceptor (null clears it). -
setJsDialogHandler
Sets a custom JS-dialog handler (null = default Android AlertDialog). -
setPermissionHandler
Sets the permission handler (null = deny all web permission requests). -
setContentSetting
Sets a per-origin web-permission content setting without showing a prompt. Lets an app pre-grant (or block) a permission for an origin it trusts — e.g. allow Web Notifications for your own web app sonew Notification(...)works without a runtime prompt.- Parameters:
requestingUrl- the origin URL, e.g."https://example.com"permission- one of thePERMISSION_*constants (PERMISSION_NOTIFICATIONS,PERMISSION_GEOLOCATION,PERMISSION_CAMERA,PERMISSION_MICROPHONE,PERMISSION_NFC)value- one of theSETTING_*constants (SETTING_ALLOW,SETTING_BLOCK,SETTING_ASK,SETTING_DEFAULT)
-
setProxy
Configures the proxy for this browser's request context. [mode] is one of thePROXY_*constants; [server] is"host:port"(or"scheme://host:port") forPROXY_FIXED, the PAC URL forPROXY_PAC, and ignored otherwise. Returns false if the preference could not be applied. Useful for kiosk/enterprise deployments. -
setProxy
Convenience: route all traffic through a fixed proxy"host:port". -
clearProxy
public boolean clearProxy()Convenience: disable proxying (direct connection). -
setDeviceChooserHandler
Sets the device chooser handler (null = cancel all device requests). -
setSslErrorHandler
Sets the SSL/certificate error handler (null = cancel on every cert error). -
setHttpAuthHandler
Sets the HTTP auth handler (null = cancel every auth challenge). -
setPopupHandler
Sets a popup handler (null = load popups in this browser). -
canGoBack
public boolean canGoBack()- Returns:
- true if the browser can navigate back.
-
suspendMedia
public void suspendMedia()Suspends active media (audio + video) at the browser-process level (MediaSession Suspend == the audio-focus-loss path). Position is preserved;resumeMedia()resumes. Works even after the renderer JS is suspended -- unlikeevaluateJavaScript("...pause()"), which is queued and never runs once backgrounded. -
resumeMedia
public void resumeMedia()Resumes media suspended bysuspendMedia()(resumes where it left off). -
setAudioMuted
public void setAudioMuted(boolean muted) Mutes/unmutes ALL audio output of the page (keeps media decoding/playing, just silenced). Use this for a "go quiet but keep position/time advancing" policy; usesuspendMedia()to actually pause. -
isAudioMuted
public boolean isAudioMuted()Whether the page's audio is currently muted viasetAudioMuted(boolean). -
isPlayingAudio
public boolean isPlayingAudio()Whether this browser currently has audible media playing -- at least one audio media session that is not paused. Backed by the media-session playback observer (setMediaSessionEnabled(boolean)). Lets a multi-tab host avoid discarding/closing a tab that is actively playing sound (background music or video). Returnsfalsewhen media session is disabled. -
setPageVisible
public void setPageVisible(boolean visible) Sets the page's visibility (compositor + Page Visibility APIdocument.hidden). HIDDEN saves GPU/battery and firesvisibilitychange, but does NOT by itself stop audio. -
stopAllMedia
public void stopAllMedia()Hard-stops all media players (not resumable likesuspendMedia()) and mutes audio. For "fully release audio on background" when you do not need to resume in place. -
stopMediaSession
public void stopMediaSession()Stops the page's media session and dismisses its media notification. UnlikestopAllMedia()(which pauses + mutes, leaving a paused notification), this clears the session -- for a host navigating away from a video screen that wants the tray notification gone. Operates at the WebContents level, so it also stops media in cross-origin iframes (e.g. a YouTube embed) that page JS cannot reach. -
onPause
public void onPause()Convenience for "host is backgrounding": hide the page, suspend media and mute audio so inline audio/video actually stops (visibility HIDDEN alone keeps background audio playing). Resumable viaonResume(). Call from Activity.onPause()/onStop(); the ComposeCefriumViewwires this automatically (see itsbackgroundMediaPolicy). -
onResume
public void onResume()Convenience for "host is foregrounding": unmute, make the page visible and resume media suspended byonPause(). Call from Activity.onResume()/onStart(); wired automatically byCefriumView. -
reapUnusedRenderers
public static void reapUnusedRenderers()Shuts down render child-processes left orphaned after browsers were closed (e.g. LRU eviction in a browser pool). Closing a browser destroys its WebContents but Chromium may keep the child process around; on process-per-browser devices the sandboxed process count then grows. This reaps processes with zero frames only (never a live renderer), after a short delay to let the just-closed browser tear down. Memory-neutral but keeps the process count bounded. Safe no-op on shared-renderer devices. -
activeRenderProcessCount
public static int activeRenderProcessCount()Exact number of live renderer processes the engine currently has -- countsRenderProcessHostonly, so utility/network/audio/storage and GPU child processes are NOT included (this is the clean renderer count, unlikeps | grep sandboxed_processwhich mixes them all). Excludes the spare renderer. After a browser pool settles this is approximately itsmaxAlive. Diagnostic; call on the main thread (returns -1 otherwise). -
zeroFrameRenderProcessCount
public static int zeroFrameRenderProcessCount()Renderer processes that currently host ZERO frames -- reuse "zombies" the pool's reap targets. A high value while a pool runs means orphaned renderers are lingering (reusable but not freed). Main thread only (-1 otherwise). Diagnostic. -
totalRenderFrameHostCount
public static int totalRenderFrameHostCount()Total live RenderFrameHosts across all renderer processes -- the real "working frame" count (host pages + iframes). If this grows as you open pages and never drops, the closed pages' frames are NOT being destroyed. Main thread only (-1 otherwise). Diagnostic. -
closedBrowserCount
public static int closedBrowserCount()Cumulative number of browsers that have finished closing (theirOnBeforeClosefired). If this does NOT grow as a pool evicts browsers,close()is not completing -- the page leaks. Diagnostic. -
liveBrowserCount
public static int liveBrowserCount()Live (not-yet-closed) browser instances. Diagnostic. -
close
public void close()Close this browser and release all native resources. After calling this method, no other methods may be called on this instance. For Surface mode, also removes the rendering views. -
captureBitmap
Captures the current page to aBitmap, delivered asynchronously on the main thread. In off-screen mode the next painted frame is returned; in Surface mode the visible surface is copied viaPixelCopy. The callback receives null if capture is unavailable. -
invalidate
public void invalidate()Force the browser to repaint. Call this if you need an updated frame (e.g. after content changes). -
imeSetComposition
Set (or update) the current IME composition. Maps to anInputConnection.setComposingTextcall.- Parameters:
text- The full composing text (underlined/marked in the page).selStart- Selection/caret start withintext.selEnd- Selection/caret end withintext.
-
imeCommitText
Commit text, ending any active composition. Maps to anInputConnection.commitTextcall.- Parameters:
text- The text to commit.relativeCursorPos- New caret position relative to the inserted text (1places the caret right after it).
-
imeFinishComposingText
public void imeFinishComposingText(boolean keepSelection) Complete the current composition, keeping the composed text. Maps toInputConnection.finishComposingText.- Parameters:
keepSelection- Whether to keep the current selection after finishing.
-
imeCancelComposition
public void imeCancelComposition()Cancel the current composition, discarding the composed text. -
sendKeyEvent
public void sendKeyEvent(int type, int modifiers, int windowsKeyCode, int nativeKeyCode, char character) Send a key event to the browser (OSR). Needed for backspace, enter, arrows and any keystroke not produced through composition. MirrorsCefBrowserHost::SendKeyEvent.A typical character keystroke is three events:
KEY_RAW_DOWN,KEY_CHAR(withcharCodeset), thenKEY_UP.- Parameters:
type- One ofKEY_RAW_DOWN,KEY_DOWN,KEY_UP,KEY_CHAR.modifiers- CEF event flags (modifier bits), or 0.windowsKeyCode- Windows virtual-key code (what Blink expects).nativeKeyCode- Raw Android key code, or 0.character- Produced character (forKEY_CHAR), or 0.
-
sendTouchEvent
public void sendTouchEvent(int action, float x, float y, int pointerId) Forward a touch event to the browser.- Parameters:
action- 0=DOWN, 1=UP, 2=MOVE, 3=CANCELx- X coordinate in browser viewport pixelsy- Y coordinate in browser viewport pixelspointerId- Pointer ID for multi-touch
-
sendTouchDown
public void sendTouchDown(float x, float y) Press a finger down at (x, y). Pair withsendTouchUp(float, float)(withsendTouchMove(float, float)in between) for drags/swipes, or usesendTap(float, float). -
sendTouchMove
public void sendTouchMove(float x, float y) Move the pressed finger to (x, y). -
sendTouchUp
public void sendTouchUp(float x, float y) Lift the finger at (x, y). -
sendTap
public void sendTap(float x, float y) Tap at (x, y): a finger down immediately followed by up. Synthesizes a click on the element at that point (the touch-automation equivalent ofsendLeftClick(int, int)). -
sendSwipe
public void sendSwipe(float x1, float y1, float x2, float y2, int steps) Swipe from (x1, y1) to (x2, y2) as a down +stepsmoves + up -- drives scrolling/flinging.stepscontrols smoothness (>= 1). -
sendMouseMove
public void sendMouseMove(int x, int y) Move the mouse pointer to (x, y). Drivesmousemoveand:hover-- state that touch input cannot express.- Parameters:
x- X coordinate in browser-viewport pixels.y- Y coordinate in browser-viewport pixels.
-
sendMouseMove
public void sendMouseMove(int x, int y, int modifiers) Move the pointer to (x, y) with modifier keys held (see MOUSE_MODIFIER_*). -
sendMouseLeave
public void sendMouseLeave(int x, int y) Signal the pointer leaving the view at (x, y) (clears:hover). -
sendMouseClick
public void sendMouseClick(int x, int y, int button) Click at (x, y) with the given button (down + up).- Parameters:
button- one of MOUSE_BUTTON_LEFT / MOUSE_BUTTON_MIDDLE / MOUSE_BUTTON_RIGHT.
-
sendMouseClick
public void sendMouseClick(int x, int y, int button, int clickCount, int modifiers) Click at (x, y) with a button, click count, and modifiers (down + up).- Parameters:
clickCount- 1 = single, 2 = double, 3 = triple.modifiers- OR of MOUSE_MODIFIER_* (0 = none).
-
sendLeftClick
public void sendLeftClick(int x, int y) Left click at (x, y). -
sendRightClick
public void sendRightClick(int x, int y) Right click at (x, y). Also opens the context menu, routed throughCefContextMenuHandler(see setOnContextMenuListener). -
sendDoubleClick
public void sendDoubleClick(int x, int y) Double left click at (x, y). -
sendMouseDown
public void sendMouseDown(int x, int y, int button, int modifiers) Press a mouse button at (x, y) without releasing it. Pair withsendMouseUp(int, int, int, int)(with interveningsendMouseMove(int, int)calls) to synthesize a drag. -
sendMouseUp
public void sendMouseUp(int x, int y, int button, int modifiers) Release a mouse button at (x, y). -
sendMouseWheel
public void sendMouseWheel(int x, int y, int deltaX, int deltaY) Scroll the mouse wheel at (x, y).deltaX/deltaYare the scroll deltas in pixels (a typical wheel notch is ~120). -
sendMouseWheel
public void sendMouseWheel(int x, int y, int deltaX, int deltaY, int modifiers) Scroll the mouse wheel at (x, y) with modifier keys held. -
getBlockedCount
public int getBlockedCount()Get the number of blocked ad/tracking requests since the browser was created. Cefrium includes a built-in network-level ad blocker using EasyList rules.- Returns:
- Number of blocked requests, or 0 if the browser is closed.
-
createWithSurface
Create a browser that renders directly to an Android Surface. Enables video playback, audio, and hardware-accelerated compositing.All Chromium rendering infrastructure (WindowAndroid, ContentViewRenderView, ContentView) is created and managed internally. The browser view is added to the Activity's content.
CefriumBrowser browser = CefriumBrowser.createWithSurface(this); browser.setOnUrlChangedListener(url -> urlBar.setText(url)); browser.loadUrl("https://example.com");- Parameters:
activity- The Activity to render in. A FrameLayout container is returned viagetSurfaceContainer().- Returns:
- A new CefriumBrowser instance with Surface rendering.
-
createWithSurface
LikecreateWithSurface(android.app.Activity)but for a private (incognito) tab. Incognito browsers share one off-the-record session that is isolated from normal tabs; their cookies, history and cache live only in memory and are cleared when the last incognito browser is closed.- Parameters:
activity- The Activity to render in.incognito- true for a private / off-the-record browser.- Returns:
- A new CefriumBrowser instance with Surface rendering.
-
isIncognito
public boolean isIncognito()- Returns:
- true if this is a private (incognito) browser.
-
onActivityResult
public boolean onActivityResult(int requestCode, int resultCode, android.content.Intent data) Forward Activity result to the browser for intent handling (file picker, permissions, etc.). Call this from your Activity's onActivityResult.- Returns:
- true if the result was handled by the browser.
-
getSurfaceContainer
public android.widget.FrameLayout getSurfaceContainer()Get the container View for Surface rendering. Add this to your Activity's layout.- Returns:
- FrameLayout containing the browser surface.
-
setMediaSessionEnabled
public void setMediaSessionEnabled(boolean enabled) Enables system media controls (lock-screen + notification shade) for this browser's playback, driven by the page'snavigator.mediaSession. Requires thePOST_NOTIFICATIONSruntime permission on Android 13+. Safe to call before or after the page loads. -
setMediaSessionActivity
public void setMediaSessionActivity(android.app.PendingIntent activity) Sets the PendingIntent fired when the user taps this browser's media control (notification / lock-screen player). Lets a multi-tab host route the tap to the exact tab that is playing. Passnullto revert to the app launcher. Safe to call before or after the media session is created. -
setOnFindResultListener
Set the listener for find-in-page results. -
find
Search for text in the current page. Uses CEF API: CefBrowserHost::Find.- Parameters:
text- Text to search for. Empty string stops the search.forward- true to search forward, false to search backward.matchCase- true for case-sensitive search.findNext- true if continuing a previous search (next/prev).
-
stopFinding
public void stopFinding(boolean clearSelection) Stop the current find-in-page search. Uses CEF API: CefBrowserHost::StopFinding.- Parameters:
clearSelection- true to clear the selection highlight.
-
setOnDownloadListener
Set the listener for download progress updates. -
setDownloadHandler
Set the controllable download handler (allow/deny + cancel/pause/resume). Passnullto remove it (downloads then auto-start, as with the legacyCefriumBrowser.OnDownloadListener). -
cancelDownload
public void cancelDownload(int id) Cancel an in-progress download by itsid. Safe to call from any thread; a no-op if the download is already finished. Useful to wire a "Cancel" action on a download notification without holding theCefriumBrowser.DownloadItem. -
pauseDownload
public void pauseDownload(int id) Pause an in-progress download by its id. SeecancelDownload(int). -
resumeDownload
public void resumeDownload(int id) Resume a paused download by its id. SeecancelDownload(int). -
setDisplayHandler
Sets the display handler (favicon, progress, console, status, media). -
setLoadHandler
Sets the per-frame load handler (load start / error). -
setResponseTapEnabled
public void setResponseTapEnabled(boolean enabled) Enable the opt-in response-body tap (CefriumRequestHandler.onResponseData(String, ByteBuffer)). Off by default; enabling it copies each response body chunk across JNI (a hot path). Requires a request handler set to receive the data. -
setCookieFilterEnabled
public void setCookieFilterEnabled(boolean enabled) Enable the opt-in per-cookie access filter (CefriumRequestHandler.onCanSendCookie(String, String, String)/onCanSaveCookie). Off by default; enabling it calls the handler per cookie (a hot path). -
setRequestHandler
-
setKeyboardHandler
Sets the keyboard handler (intercept keys before the page). -
setFocusHandler
Sets the focus handler. -
setDragHandler
Sets the drag handler. -
setAudioHandler
Sets the audio handler. OPT-IN and exclusive: a non-null handler REDIRECTS the page's audio to it (it stops playing through the speakers); pass null to disable and restore normal playback. -
setFrameHandler
Sets the frame lifecycle handler. -
setCommandHandler
Sets the Chrome command handler. -
setDialogHandler
Sets the file-chooser dialog handler (<input type=file>). -
fileDialogResult
Delivers a file-chooser selection (empty/null cancels). SeeCefriumDialogHandler. -
downloadImage
Fetches an image (e.g. a favicon URL fromCefriumDisplayHandler.onFaviconUrlChanged(String[])) to a Bitmap.- Parameters:
url- Image URL.maxSize- Max edge in DIP (0 = no limit).callback- Delivered on the main thread; bitmap is null on failure.
-
exitFullscreen
public void exitFullscreen()Programmatically exit HTML fullscreen (e.g. from the back button). -
startDownload
Force a download ofurl. -
setOnContextMenuListener
Set the listener for context menu events. -
contextMenuCommand
public void contextMenuCommand(int commandId) Send the user's context menu selection back to CEF. Use -1 to cancel.- Parameters:
commandId- The selected command ID, or -1 to cancel.
-