There are two common ways you can expose your C++ to JavaScript:
- using
web_ui()->RegisterMessageCallback
inside the WebUI (example) - 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 usingchrome.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')
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
- For an overview of WebUI, check out WebUI Explainer
- For more information about Extension APIs, check out Extension API Functions
- For how Brave builds WebUI resources, check out WebUI Builds, Paths and Resources