Skip to content

Exposing CPP functions to JavaScript for a WebUI

Brian Clifton edited this page Apr 14, 2021 · 3 revisions

There are two common ways you can expose your C++ to JavaScript:

  1. using web_ui()->RegisterMessageCallback inside the WebUI (example)
  2. exposing the functionality via extension methods (example). Notice that a context can be given for when this would be in scope (allowlist for which extension IDs have access, matches for which pages have access, etc)

The WebUI can then access that method in JavaScript.

  • When using RegisterMessageCallback, you would access using chrome.send. For example: chrome.send('setBraveThemeType', 'Dark'). For situations needing to use a promise, you'd be able to use something like:
    import {sendWithPromise} from 'chrome://resources/js/cr.m.js';
    // ..
    return sendWithPromise('getBraveThemeType')
    
  • When using extension methods, you'd use the path you exposed. For example: chrome.braveTheme.setBraveThemeType('Dark')

Which is preferred?

We should always prefer using RegisterMessageCallback in a WebUI. Additionally, we should avoid creating any new features as part of an extension including the Brave extension.

An exception can be made for using an extension API on a WebUI page if:

  • We need to call the API from an extension page as well (prevent having to duplicate code) AND
  • The page isn't / won't be used on Android

If those two criteria can't be met, the WebUI should be using RegisterMessageCallback to register methods for use with chrome.send

Related

Clone this wiki locally