Menu

Embedding

Embed a browser in your window

Place Chromium browsers inside windows your app owns, keep them laid out and close them cleanly.

An app started with App::start_embedded owns its windows. Kurogane opens none. AppInstance::create_child_browser places a browser inside a window of yours as a native child window. Your app decides where it sits, when it moves and when it closes.

Use it for a web view inside an existing app, such as a settings panel in a game or a tool window.

A complete example

This winit app embeds one browser that fills its window. It pumps Chromium as Drive Chromium from winit does:

use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant};

use kurogane::{App, AppInstance, BrowserBounds, BrowserHandle, PumpRequest};
use winit::application::ApplicationHandler;
use winit::event::WindowEvent;
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop, EventLoopProxy};
use winit::window::{Window, WindowId};

const MAX_PUMP_DELAY: Duration = Duration::from_millis(1000 / 30);

struct Host {
    runtime: AppInstance,
    window: Option<Window>,
    browser: Option<BrowserHandle>,
    next_pump: Instant,
}

impl ApplicationHandler<Instant> for Host {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        if self.window.is_some() {
            return;
        }
        let window = event_loop.create_window(Window::default_attributes().with_title("Host")).unwrap();
        match self.runtime.create_child_browser(&window, client_bounds(&window), "app://app/index.html") {
            Ok(browser) => self.browser = Some(browser),
            Err(e) => eprintln!("the browser could not be created:\n{e}"),
        }
        self.window = Some(window);
    }

    fn user_event(&mut self, _: &ActiveEventLoop, deadline: Instant) {
        self.next_pump = self.next_pump.min(deadline);
    }

    fn window_event(&mut self, _: &ActiveEventLoop, _: WindowId, event: WindowEvent) {
        match event {
            WindowEvent::CloseRequested => {
                // Start closing the browsers; the window stays until they're gone
                self.runtime.handle().close_all_browsers(true);
            }
            WindowEvent::Resized(_) => {
                // Chromium placed the browser once; keep it filling the window
                if let (Some(browser), Some(window)) = (&self.browser, &self.window) {
                    browser.set_bounds(client_bounds(window));
                }
            }
            _ => {}
        }
    }

    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
        let now = Instant::now();
        if now >= self.next_pump {
            self.next_pump = now + MAX_PUMP_DELAY;
            self.runtime.pump();
        }
        if self.runtime.should_shutdown() {
            self.window = None;
            self.runtime.shutdown();
            event_loop.exit();
            return;
        }
        event_loop.set_control_flow(ControlFlow::WaitUntil(self.next_pump));
    }
}

/// Returns the window's client area in the units a child browser takes.
fn client_bounds(window: &Window) -> BrowserBounds {
    let size = window.inner_size();
    #[cfg(target_os = "macos")]
    let size = size.to_logical::<u32>(window.scale_factor());
    BrowserBounds { x: 0, y: 0, width: size.width as i32, height: size.height as i32 }
}

fn main() {
    let wake: Arc<OnceLock<EventLoopProxy<Instant>>> = Arc::default();

    let runtime = App::new("content")
        .scheduler({
            let wake = wake.clone();
            move |request: PumpRequest| {
                if let Some(proxy) = wake.get() {
                    let _ = proxy.send_event(request.deadline(Instant::now()));
                }
            }
        })
        .start_embedded()
        .expect("Kurogane failed to start");

    // Chromium takes an X11 window as a parent on Linux
    #[cfg(target_os = "linux")]
    let event_loop = {
        use winit::platform::x11::EventLoopBuilderExtX11;
        EventLoop::<Instant>::with_user_event().with_x11().build()
    };
    #[cfg(target_os = "macos")]
    let event_loop = {
        use winit::platform::macos::EventLoopBuilderExtMacOS;
        EventLoop::<Instant>::with_user_event().with_default_menu(false).build()
    };
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    let event_loop = EventLoop::<Instant>::with_user_event().build();
    let event_loop = event_loop.unwrap();
    let _ = wake.set(event_loop.create_proxy());

    let mut host = Host { runtime, window: None, browser: None, next_pump: Instant::now() };
    event_loop.run_app(&mut host).unwrap();
}

The same works with any window that hands out a raw_window_handle window handle.

Keep the browser laid out

Chromium places a child browser once, at the BrowserBounds you give create_child_browser:

  • Windows and Linux. The browser doesn’t follow your window. Call BrowserHandle::set_bounds whenever its place changes. A browser that fills the window needs it on every resize.
  • macOS. The browser stretches with its parent view by itself. set_bounds places it anywhere else.

Bounds are in your window’s own coordinates. They’re pixels from the top-left of the client area on Windows and X11. On macOS they’re points in the parent view. That’s why the example converts winit’s inner_size with to_logical. A width or height below one counts as one.

BrowserHandle::notify_move_or_resize_started tells the browser your window is about to move or resize. Chromium uses it on Windows and Linux.

Several browsers in one window

Each create_child_browser call places another browser. Give each its own bounds and keep each one’s BrowserHandle to lay it out. A closed browser takes only its own child window. Your window stays open with the others in it.

AppInstance::create_child_browser_with_request_context gives a browser its own cookie and cache partition.

Linux needs an X11 parent

Chromium takes an X11 window as the parent. winit’s with_x11() gives one. In a Wayland session that window runs under XWayland.

A Wayland surface can’t be a parent. create_child_browser refuses it with RuntimeError::UnsupportedParentWindow. For the same reason Kurogane runs Chromium itself on X11 in an embedded app. Under Wayland it would draw the page beside your window instead of inside it.

Close the browsers before the window

Closing is asynchronous. A close request starts it and the pump finishes it:

  1. On your window’s close request, call close_all_browsers(true). Don’t leave the loop yet.
  2. Keep pumping. The browsers close inside pump.
  3. Once should_shutdown turns true, release your window, call AppInstance::shutdown and leave the loop.

Your window must outlive the browsers in it. End on should_shutdown, not on a flag of your own. On macOS Quit closes every browser without a close request to your window. See Lifecycle and shutdown.

What differs from Kurogane’s windows

Behavior Embedded browser
Start window none; App::window is a configuration error
Chromium’s keyboard shortcuts none run; on_key still sees every key
Ctrl+C no handler; your app handles it
Drags from other apps reach on_drag_enter
Title changes reach on_title_change with no window; title your window yourself
Fullscreen Kurogane doesn’t resize the browser; your app does
Context menu Kurogane’s menu, drawn by Chromium; & in labels is removed
on_window_closing not asked