Package com.cefrium

Class CefriumBrowser

java.lang.Object
com.cefrium.CefriumBrowser

public class CefriumBrowser extends Object
A browser instance backed by Chromium via CEF (Chromium Embedded Framework).

Two rendering modes are available:

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:
  • Field Details

  • 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, use CefriumBrowser(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

      public void setRenderHandler(CefriumRenderHandler handler)
      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

      public void loadUrl(String url)
      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 if canGoBack() 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

      public void setCallback(CefriumBrowser.Callback callback)
      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

      public void setOnUrlChangedListener(CefriumBrowser.OnUrlChangedListener listener)
      Set a listener for URL changes during navigation.
    • setOnTitleChangedListener

      public void setOnTitleChangedListener(CefriumBrowser.OnTitleChangedListener listener)
      Set a listener for title changes.
    • setOnFullscreenChangedListener

      public void setOnFullscreenChangedListener(CefriumBrowser.OnFullscreenChangedListener listener)
      Set a listener for fullscreen mode changes.
    • setOnRequestInterceptedListener

      public void setOnRequestInterceptedListener(CefriumBrowser.OnRequestInterceptedListener listener)
      Set a listener for network request interception. Called for EVERY request — use for network inspection, debugging, or custom request auditing.
    • getUrl

      public String getUrl()
      The current top-level URL, or null before the first navigation.
    • saveState

      public android.os.Bundle saveState()
      Captures restorable browser state (the current URL) into a Bundle. Call from Activity.onSaveInstanceState and pass the result to restoreState(android.os.Bundle) after recreating the browser.
    • restoreState

      public void restoreState(android.os.Bundle state)
      Restores state previously captured by saveState() — re-navigates to the saved URL. No-op if state is null or holds no saved URL.
    • serializeNavigationState

      public byte[] serializeNavigationState()
      Serializes this tab's full back/forward navigation stack (each entry's URL and blink PageState, plus the current index) for session restore. Returns null if there is nothing to save. Chrome-style tab restore: unlike saveState() (current URL only), the restored tab can navigate back. Restore with restoreNavigationState(byte[]) on a FRESH browser, before its first navigation.
    • restoreNavigationState

      public void restoreNavigationState(byte[] state)
      Restores a navigation stack captured by serializeNavigationState(). Must be called on a fresh browser (empty history) before its first navigation; no-op for null/empty input.
    • setOnLoadingStateChangedListener

      public void setOnLoadingStateChangedListener(CefriumBrowser.OnLoadingStateChangedListener listener)
      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

      public void evaluateJavaScript(String script)
      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

      public void setQueryHandler(CefriumBrowser.QueryHandler handler)
      Registers the handler for window.cefriumQuery calls.
    • setCookie

      public void setCookie(String url, String name, String value)
      Sets a session cookie for url (domain/path inferred from the URL).
    • setCookie

      public void setCookie(String url, String name, String value, boolean secure, boolean httpOnly, int sameSite)
      Sets a session cookie for url with explicit attributes. Use this for cookies a third-party/cross-site context must send (e.g. a consent cookie an embedded iframe needs): pass secure=true and sameSite=SAME_SITE_NONE -- Chromium rejects SameSite=None without Secure. domain/path are inferred from the URL.
    • getCookies

      public void getCookies(String url, CefriumBrowser.CookieCallback callback)
      Reads cookies visible to url; the callback fires on the UI thread.
    • deleteCookies

      public void deleteCookies(String url, String name)
      Deletes cookies for url; name null/empty = all for the URL.
    • flushCookies

      public void flushCookies()
      Persists the cookie store to disk.
    • clearCache

      public void clearCache()
      Clears the browser's HTTP cache.
    • printToPdf

      public void printToPdf(String filePath, CefriumBrowser.PdfCallback callback)
      Renders the current page to a PDF at filePath (async).
    • setUserAgentOverride

      public void setUserAgentOverride(String userAgent)
      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).
    • loadHtml

      public void loadHtml(String html)
      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's WebView.loadDataWithBaseURL(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String). Unlike WebView, Cefrium delivers the content as a GENUINE network response at baseUrl (not a data: 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; a data: document is rejected by such players (Error 152), which is why the same content fails under WebView's loadDataWithBaseURL.

      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 load
      mimeType - 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

      public void loadHtmlWithBaseUrl(String html, String baseUrl)
      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 in html plays. Pass YOUR OWN app origin as baseUrl, 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). See loadDataWithBaseUrl(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String).
    • postUrl

      public void postUrl(String url, byte[] postData)
      Loads url with an HTTP POST body.
    • stopLoading

      public void stopLoading()
      Stops the current load.
    • setRequestInterceptor

      public void setRequestInterceptor(CefriumBrowser.RequestInterceptor interceptor)
      Sets a programmatic request interceptor (null clears it).
    • setJsDialogHandler

      public void setJsDialogHandler(CefriumBrowser.JsDialogHandler handler)
      Sets a custom JS-dialog handler (null = default Android AlertDialog).
    • setPermissionHandler

      public void setPermissionHandler(CefriumBrowser.PermissionHandler handler)
      Sets the permission handler (null = deny all web permission requests).
    • setContentSetting

      public void setContentSetting(String requestingUrl, int permission, int value)
      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 so new Notification(...) works without a runtime prompt.
      Parameters:
      requestingUrl - the origin URL, e.g. "https://example.com"
      permission - one of the PERMISSION_* constants (PERMISSION_NOTIFICATIONS, PERMISSION_GEOLOCATION, PERMISSION_CAMERA, PERMISSION_MICROPHONE, PERMISSION_NFC)
      value - one of the SETTING_* constants (SETTING_ALLOW, SETTING_BLOCK, SETTING_ASK, SETTING_DEFAULT)
    • setProxy

      public boolean setProxy(String mode, String server)
      Configures the proxy for this browser's request context. [mode] is one of the PROXY_* constants; [server] is "host:port" (or "scheme://host:port") for PROXY_FIXED, the PAC URL for PROXY_PAC, and ignored otherwise. Returns false if the preference could not be applied. Useful for kiosk/enterprise deployments.
    • setProxy

      public boolean setProxy(String server)
      Convenience: route all traffic through a fixed proxy "host:port".
    • clearProxy

      public boolean clearProxy()
      Convenience: disable proxying (direct connection).
    • setDeviceChooserHandler

      public void setDeviceChooserHandler(CefriumBrowser.DeviceChooserHandler handler)
      Sets the device chooser handler (null = cancel all device requests).
    • setSslErrorHandler

      public void setSslErrorHandler(CefriumBrowser.SslErrorHandler handler)
      Sets the SSL/certificate error handler (null = cancel on every cert error).
    • setHttpAuthHandler

      public void setHttpAuthHandler(CefriumBrowser.HttpAuthHandler handler)
      Sets the HTTP auth handler (null = cancel every auth challenge).
    • setPopupHandler

      public void setPopupHandler(CefriumBrowser.PopupHandler handler)
      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 -- unlike evaluateJavaScript("...pause()"), which is queued and never runs once backgrounded.
    • resumeMedia

      public void resumeMedia()
      Resumes media suspended by suspendMedia() (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; use suspendMedia() to actually pause.
    • isAudioMuted

      public boolean isAudioMuted()
      Whether the page's audio is currently muted via setAudioMuted(boolean).
    • setPageVisible

      public void setPageVisible(boolean visible)
      Sets the page's visibility (compositor + Page Visibility API document.hidden). HIDDEN saves GPU/battery and fires visibilitychange, but does NOT by itself stop audio.
    • stopAllMedia

      public void stopAllMedia()
      Hard-stops all media players (not resumable like suspendMedia()) 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. Unlike stopAllMedia() (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 via onResume(). Call from Activity.onPause()/onStop(); the Compose CefriumView wires this automatically (see its backgroundMediaPolicy).
    • onResume

      public void onResume()
      Convenience for "host is foregrounding": unmute, make the page visible and resume media suspended by onPause(). Call from Activity.onResume()/onStart(); wired automatically by CefriumView.
    • 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 -- counts RenderProcessHost only, so utility/network/audio/storage and GPU child processes are NOT included (this is the clean renderer count, unlike ps | grep sandboxed_process which mixes them all). Excludes the spare renderer. After a browser pool settles this is approximately its maxAlive. 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 (their OnBeforeClose fired). 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

      public void captureBitmap(CefriumBrowser.BitmapCallback callback)
      Captures the current page to a Bitmap, delivered asynchronously on the main thread. In off-screen mode the next painted frame is returned; in Surface mode the visible surface is copied via PixelCopy. 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).
    • 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=CANCEL
      x - X coordinate in browser viewport pixels
      y - Y coordinate in browser viewport pixels
      pointerId - Pointer ID for multi-touch
    • 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

      public static CefriumBrowser createWithSurface(android.app.Activity activity)
      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 via getSurfaceContainer().
      Returns:
      A new CefriumBrowser instance with Surface rendering.
    • createWithSurface

      public static CefriumBrowser createWithSurface(android.app.Activity activity, boolean incognito)
      Like createWithSurface(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's navigator.mediaSession . Requires the POST_NOTIFICATIONS runtime permission on Android 13+. Safe to call before or after the page loads.
    • setOnFindResultListener

      public void setOnFindResultListener(CefriumBrowser.OnFindResultListener listener)
      Set the listener for find-in-page results.
    • find

      public void find(String text, boolean forward, boolean matchCase, boolean findNext)
      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

      public void setOnDownloadListener(CefriumBrowser.OnDownloadListener listener)
      Set the listener for download progress updates.
    • setOnContextMenuListener

      public void setOnContextMenuListener(CefriumBrowser.OnContextMenuListener listener)
      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.