Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1 | <style> |
| 2 | .note::before { |
| 3 | content: 'Note: '; |
| 4 | font-variant: small-caps; |
| 5 | font-style: italic; |
| 6 | } |
| 7 | |
| 8 | .doc h1 { |
| 9 | margin: 0; |
| 10 | } |
| 11 | </style> |
| 12 | |
| 13 | # WebUI Explainer |
| 14 | |
| 15 | [TOC] |
| 16 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 17 | ## What is "WebUI"? |
| 18 | |
| 19 | "WebUI" is a term used to loosely describe **parts of Chrome's UI |
| 20 | implemented with web technologies** (i.e. HTML, CSS, JavaScript). |
| 21 | |
| 22 | Examples of WebUI in Chromium: |
| 23 | |
| 24 | * Settings (chrome://settings) |
| 25 | * History (chrome://history) |
| 26 | * Downloads (chrome://downloads) |
| 27 | |
| 28 | <div class="note"> |
| 29 | Not all web-based UIs in Chrome have chrome:// URLs. |
| 30 | </div> |
| 31 | |
| 32 | This document explains how WebUI works. |
| 33 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 34 | ## What's different from a web page? |
| 35 | |
| 36 | WebUIs are granted super powers so that they can manage Chrome itself. For |
| 37 | example, it'd be very hard to implement the Settings UI without access to many |
| 38 | different privacy and security sensitive services. Access to these services are |
| 39 | not granted by default. |
| 40 | |
| 41 | Only special URLs are granted WebUI "bindings" via the child security process. |
| 42 | |
| 43 | Specifically, these bindings: |
| 44 | |
| 45 | * give a renderer access to load [`chrome:`](#chrome_urls) URLS |
| 46 | * this is helpful for shared libraries, i.e. `chrome://resources/` |
| 47 | * allow the browser to execute arbitrary JavaScript in that renderer via |
| 48 | [`CallJavascriptFunction()`](#CallJavascriptFunction) |
| 49 | * allow communicating from the renderer to the browser with |
| 50 | [`chrome.send()`](#chrome_send) and friends |
| 51 | * ignore content settings regarding showing images or executing JavaScript |
| 52 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 53 | ## How `chrome:` URLs work |
| 54 | |
| 55 | <div class="note"> |
| 56 | A URL is of the format <protocol>://<host>/<path>. |
| 57 | </div> |
| 58 | |
| 59 | A `chrome:` URL loads a file from disk, memory, or can respond dynamically. |
| 60 | |
| 61 | Because Chrome UIs generally need access to the browser (not just the current |
| 62 | tab), much of the C++ that handles requests or takes actions lives in the |
| 63 | browser process. The browser has many more privileges than a renderer (which is |
| 64 | sandboxed and doesn't have file access), so access is only granted for certain |
| 65 | URLs. |
| 66 | |
| 67 | ### `chrome:` protocol |
| 68 | |
| 69 | Chrome recognizes a list of special protocols, which it registers while starting |
| 70 | up. |
| 71 | |
| 72 | Examples: |
| 73 | |
James Lissiak | 28b21a6 | 2019-05-15 15:32:04 | [diff] [blame] | 74 | * devtools: |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 75 | * chrome-extensions: |
Adam Langley | 81be073 | 2019-03-06 18:38:45 | [diff] [blame] | 76 | * chrome: |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 77 | * file: |
| 78 | * view-source: |
| 79 | |
| 80 | This document mainly cares about the **chrome:** protocol, but others can also |
| 81 | be granted [WebUI bindings](#bindings) or have special |
| 82 | properties. |
| 83 | |
| 84 | ### `chrome:` hosts |
| 85 | |
| 86 | After registering the `chrome:` protocol, a set of factories are created. These |
| 87 | factories contain a list of valid host names. A valid hostname generates a |
| 88 | controller. |
| 89 | |
| 90 | In the case of `chrome:` URLs, these factories are registered early in the |
Rebekah Potter | 017ed54 | 2023-11-15 16:15:38 | [diff] [blame] | 91 | browser process lifecycle. Before the first `WebUIConfig` is registered, the |
| 92 | `WebUIConfigMap` instance is created. This map creates and registers a |
| 93 | factory (`WebUIConfigMapWebUIControllerFactory`) in its constructor. |
| 94 | This factory looks at the global `WebUIConfigMap`, which maps hosts to |
| 95 | `WebUIConfig`s, to see if any of the configs handle the requested URL. It calls |
| 96 | the method on the config to create the corresponding controller if it finds a |
| 97 | config to handle the URL. |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 98 | |
| 99 | ```c++ |
| 100 | // ChromeBrowserMainParts::PreMainMessageLoopRunImpl(): |
Rebekah Potter | 017ed54 | 2023-11-15 16:15:38 | [diff] [blame] | 101 | |
| 102 | // Legacy WebUIControllerFactory registration |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 103 | content::WebUIControllerFactory::RegisterFactory( |
| 104 | ChromeWebUIControllerFactory::GetInstance()); |
Rebekah Potter | 017ed54 | 2023-11-15 16:15:38 | [diff] [blame] | 105 | |
| 106 | // Factory for all WebUIs using WebUIConfig will be created here. |
| 107 | RegisterChromeWebUIConfigs(); |
| 108 | RegisterChromeUntrustedWebUIConfigs(); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 109 | ``` |
| 110 | |
| 111 | When a URL is requested, a new renderer is created to load the URL, and a |
| 112 | corresponding class in the browser is set up to handle messages from the |
| 113 | renderer to the browser (a `RenderFrameHost`). |
| 114 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 115 | ```c++ |
Rebekah Potter | 26b32f4 | 2023-10-31 20:36:47 | [diff] [blame] | 116 | auto* config = config_map_->GetConfig(browser_context, url); |
| 117 | if (!config) |
| 118 | return nullptr; // Not a known host; no special access. |
| 119 | |
| 120 | return config->CreateWebUIController(web_ui, url); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 121 | ``` |
| 122 | |
Rebekah Potter | 26b32f4 | 2023-10-31 20:36:47 | [diff] [blame] | 123 | Configs can be registered with the map by calling `map.AddWebUIConfig()` in |
| 124 | `chrome_web_ui_configs.cc`: |
| 125 | ```c++ |
| 126 | map.AddWebUIConfig(std::make_unique<donuts::DonutsUIConfig>()); |
| 127 | |
| 128 | ``` |
| 129 | |
| 130 | If a factory knows how to handle a host (returns a `WebUIFactoryFunction`), |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 131 | the navigation machinery [grants the renderer process WebUI |
| 132 | bindings](#bindings) via the child security policy. |
| 133 | |
| 134 | ```c++ |
| 135 | // RenderFrameHostImpl::AllowBindings(): |
Avi Drissman | 78865bbb | 2024-08-22 20:57:19 | [diff] [blame] | 136 | if (bindings_flags.Has(BindingsPolicyValue::kWebUi)) { |
dbeam | 8b52edff | 2017-06-16 22:36:18 | [diff] [blame] | 137 | ChildProcessSecurityPolicyImpl::GetInstance()->GrantWebUIBindings( |
Emily Andrews | d15fd76 | 2024-12-10 20:41:54 | [diff] [blame] | 138 | GetProcess()->GetDeprecatedID()); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 139 | } |
| 140 | ``` |
| 141 | |
Rebekah Potter | 26b32f4 | 2023-10-31 20:36:47 | [diff] [blame] | 142 | The factory creates a [`WebUIController`](#WebUIController) for a tab using |
| 143 | the WebUIConfig. |
| 144 | |
Mickey Burks | 463e6f5 | 2024-07-02 11:45:05 | [diff] [blame] | 145 | Here's an example using the DefaultWebUIConfig: |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 146 | |
| 147 | ```c++ |
Mickey Burks | 463e6f5 | 2024-07-02 11:45:05 | [diff] [blame] | 148 | class DonutsUI; |
| 149 | |
| 150 | // This would go in chrome/common/webui_url_constants.cc |
| 151 | namespace chrome { |
| 152 | const char kChromeUIDonutsHost[] = "donuts"; |
| 153 | } // namespace chrome |
| 154 | |
Rebekah Potter | 26b32f4 | 2023-10-31 20:36:47 | [diff] [blame] | 155 | // Config for chrome://donuts |
Mickey Burks | 463e6f5 | 2024-07-02 11:45:05 | [diff] [blame] | 156 | class DonutsUIConfig : public content::DefaultWebUIConfig<DonutsUI> { |
| 157 | public: |
| 158 | DonutsUIConfig() |
| 159 | : DefaultWebUIConfig(content::kChromeUIScheme, |
| 160 | chrome::kChromeUIDonutsHost) {} |
| 161 | }; |
Rebekah Potter | 26b32f4 | 2023-10-31 20:36:47 | [diff] [blame] | 162 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 163 | // Controller for chrome://donuts. |
| 164 | class DonutsUI : public content::WebUIController { |
| 165 | public: |
| 166 | DonutsUI(content::WebUI* web_ui) : content::WebUIController(web_ui) { |
| 167 | content::WebUIDataSource* source = |
Rebekah Potter | a894942 | 2023-01-05 18:44:13 | [diff] [blame] | 168 | content::WebUIDataSource::CreateAndAdd( |
| 169 | web_ui->GetWebContents()->GetBrowserContext(), |
| 170 | "donuts"); // "donuts" == hostname |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 171 | source->AddString("mmmDonuts", "Mmm, donuts!"); // Translations. |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 172 | source->AddResourcePath("", IDR_DONUTS_HTML); // Home page. |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 173 | |
| 174 | // Handles messages from JavaScript to C++ via chrome.send(). |
Jeremy Roman | e0760a40 | 2018-03-02 18:19:40 | [diff] [blame] | 175 | web_ui->AddMessageHandler(std::make_unique<OvenHandler>()); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 176 | } |
| 177 | }; |
| 178 | ``` |
| 179 | |
| 180 | If we assume the contents of `IDR_DONUTS_HTML` yields: |
| 181 | |
| 182 | ```html |
| 183 | <h1>$i18n{mmmDonuts}</h1> |
| 184 | ``` |
| 185 | |
| 186 | Visiting `chrome://donuts` should show in something like: |
| 187 | |
| 188 | <div style="border: 1px solid black; padding: 10px;"> |
| 189 | <h1>Mmmm, donuts!</h1> |
| 190 | </div> |
| 191 | |
| 192 | Delicious success. |
| 193 | |
Christopher Lam | 50ab1e9 | 2019-10-29 04:33:16 | [diff] [blame] | 194 | By default $i18n{} escapes strings for HTML. $i18nRaw{} can be used for |
| 195 | translations that embed HTML, and $i18nPolymer{} can be used for Polymer |
| 196 | bindings. See |
| 197 | [this comment](https://bugs.chromium.org/p/chromium/issues/detail?id=1010815#c1) |
| 198 | for more information. |
| 199 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 200 | ## C++ classes |
| 201 | |
| 202 | ### WebUI |
| 203 | |
| 204 | `WebUI` is a high-level class and pretty much all HTML-based Chrome UIs have |
| 205 | one. `WebUI` lives in the browser process, and is owned by a `RenderFrameHost`. |
| 206 | `WebUI`s have a concrete implementation (`WebUIImpl`) in `content/` and are |
| 207 | created in response to navigation events. |
| 208 | |
| 209 | A `WebUI` knows very little about the page it's showing, and it owns a |
| 210 | [`WebUIController`](#WebUIController) that is set after creation based on the |
| 211 | hostname of a requested URL. |
| 212 | |
| 213 | A `WebUI` *can* handle messages itself, but often defers these duties to |
| 214 | separate [`WebUIMessageHandler`](#WebUIMessageHandler)s, which are generally |
| 215 | designed for handling messages on certain topics. |
| 216 | |
| 217 | A `WebUI` can be created speculatively, and are generally fairly lightweight. |
| 218 | Heavier duty stuff like hard initialization logic or accessing services that may |
| 219 | have side effects are more commonly done in a |
| 220 | [`WebUIController`](#WebUIController) or |
| 221 | [`WebUIMessageHandler`s](#WebUIMessageHandler). |
| 222 | |
| 223 | `WebUI` are created synchronously on the UI thread in response to a URL request, |
dpapad | 32c8dd9 | 2025-01-22 19:05:16 | [diff] [blame] | 224 | and are reused where possible between navigations (i.e. refreshing a page). |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 225 | Because they run in a separate process and can exist before a corresponding |
| 226 | renderer process has been created, special care is required to communicate with |
| 227 | the renderer if reliable message passing is required. |
| 228 | |
Rebekah Potter | 26b32f4 | 2023-10-31 20:36:47 | [diff] [blame] | 229 | ### WebUIConfig |
| 230 | A `WebUIConfig` contains minimal possible logic and information for determining |
| 231 | whether a certain subclass of `WebUIController` should be created for a given |
| 232 | URL. |
| 233 | |
| 234 | A `WebUIConfig` holds information about the host and scheme (`chrome://` or |
Carlos Knippschild | e084bd2 | 2024-09-19 18:50:54 | [diff] [blame] | 235 | [`chrome-untrusted://`](chrome_untrusted.md)) that the controller serves. |
Rebekah Potter | 26b32f4 | 2023-10-31 20:36:47 | [diff] [blame] | 236 | |
| 237 | A `WebUIConfig` may contain logic to check if the WebUI is enabled for a given |
| 238 | `BrowserContext` and url (e.g., if relevant feature flags are enabled/disabled, |
| 239 | if the url path is valid, etc). |
| 240 | |
| 241 | A `WebUIConfig` can invoke the `WebUIController`'s constructor in its |
| 242 | `CreateWebUIControllerForURL` method. |
| 243 | |
| 244 | `WebUIConfig`s are created at startup when factories are registered, so should |
| 245 | be lightweight. |
| 246 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 247 | ### WebUIController |
| 248 | |
| 249 | A `WebUIController` is the brains of the operation, and is responsible for |
| 250 | application-specific logic, setting up translations and resources, creating |
| 251 | message handlers, and potentially responding to requests dynamically. In complex |
| 252 | pages, logic is often split across multiple |
| 253 | [`WebUIMessageHandler`s](#WebUIMessageHandler) instead of solely in the |
| 254 | controller for organizational benefits. |
| 255 | |
| 256 | A `WebUIController` is owned by a [`WebUI`](#WebUI), and is created and set on |
Rebekah Potter | 26b32f4 | 2023-10-31 20:36:47 | [diff] [blame] | 257 | an existing [`WebUI`](#WebUI) when the corresponding `WebUIConfig` is found in |
| 258 | the map matching the URL, or when the correct controller is determined via URL |
| 259 | inspection in `ChromeWebUIControllerFactory`. (i.e. chrome://settings creates |
| 260 | a generic [`WebUI`](#WebUI) with a settings-specific `WebUIController`). |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 261 | |
| 262 | ### WebUIDataSource |
| 263 | |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 264 | The `WebUIDataSource` class provides a place for data to live for WebUI pages. |
| 265 | |
| 266 | Examples types of data stored in this class are: |
| 267 | |
| 268 | * static resources (i.e. .html files packed into bundles and pulled off of disk) |
| 269 | * translations |
| 270 | * dynamic feature values (i.e. whether a feature is enabled) |
| 271 | |
| 272 | Data sources are set up in the browser process (in C++) and are accessed by |
| 273 | loading URLs from the renderer. |
| 274 | |
| 275 | Below is an example of a simple data source (in this case, Chrome's history |
| 276 | page): |
| 277 | |
| 278 | ```c++ |
Rebekah Potter | a894942 | 2023-01-05 18:44:13 | [diff] [blame] | 279 | content::WebUIDataSource* source = content::WebUIDataSource::CreateAndAdd( |
| 280 | Profile::FromWebUI(web_ui), "history"); |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 281 | |
| 282 | source->AddResourcePath("sign_in_promo.svg", IDR_HISTORY_SIGN_IN_PROMO_SVG); |
| 283 | source->AddResourcePath("synced_tabs.html", IDR_HISTORY_SYNCED_TABS_HTML); |
| 284 | |
| 285 | source->AddString("title", IDS_HISTORY_TITLE); |
| 286 | source->AddString("moreFromThisSite", IDS_HISTORY_MORE_FROM_THIS_SITE); |
| 287 | |
| 288 | source->AddBoolean("showDateRanges", |
| 289 | base::FeatureList::IsEnabled(features::kHistoryShowDateRanges)); |
| 290 | |
| 291 | webui::SetupWebUIDataSource( |
Mickey Burks | e714ad67 | 2024-10-16 20:40:54 | [diff] [blame] | 292 | source, base::span<const webui::ResourcePath>(kHistoryResources), |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 293 | kGeneratedPath, IDR_HISTORY_HISTORY_HTML); |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 294 | ``` |
| 295 | |
| 296 | For more about each of the methods called on `WebUIDataSource` and the utility |
| 297 | method that performs additional configuration, see [DataSources](#DataSources) |
| 298 | and [WebUIDataSourceUtils](#WebUIDataSourceUtils) |
| 299 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 300 | ### WebUIMessageHandler |
| 301 | |
| 302 | Because some pages have many messages or share code that sends messages, message |
| 303 | handling is often split into discrete classes called `WebUIMessageHandler`s. |
| 304 | These handlers respond to specific invocations from JavaScript. |
| 305 | |
| 306 | So, the given C++ code: |
| 307 | |
| 308 | ```c++ |
| 309 | void OvenHandler::RegisterMessages() { |
Ayu Ishii | 3374343 | 2021-02-03 19:05:01 | [diff] [blame] | 310 | web_ui()->RegisterMessageCallback( |
| 311 | "bakeDonuts", |
| 312 | base::BindRepeating(&OvenHandler::HandleBakeDonuts, |
| 313 | base::Unretained(this))); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 314 | } |
| 315 | |
Moe Ahmadi | de590186 | 2022-02-25 21:56:23 | [diff] [blame] | 316 | void OvenHandler::HandleBakeDonuts(const base::Value::List& args) { |
Michael Giuffrida | 1493829 | 2019-05-31 21:30:23 | [diff] [blame] | 317 | AllowJavascript(); |
| 318 | |
Lei Zhang | 72347ebdd | 2021-11-16 16:40:02 | [diff] [blame] | 319 | // IMPORTANT: Fully validate `args`. |
cammie | 720e8acd | 2021-08-25 19:15:45 | [diff] [blame] | 320 | CHECK_EQ(1u, args.size()); |
Lei Zhang | 72347ebdd | 2021-11-16 16:40:02 | [diff] [blame] | 321 | int num_donuts = args[0].GetInt(); |
| 322 | CHECK_GT(num_donuts, 0); |
| 323 | GetOven()->BakeDonuts(num_donuts); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 324 | } |
| 325 | ``` |
| 326 | |
| 327 | Can be triggered in JavaScript with this example code: |
| 328 | |
| 329 | ```js |
| 330 | $('bakeDonutsButton').onclick = function() { |
| 331 | chrome.send('bakeDonuts', [5]); // bake 5 donuts! |
| 332 | }; |
| 333 | ``` |
| 334 | |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 335 | ## Data Sources |
| 336 | |
Rebekah Potter | a894942 | 2023-01-05 18:44:13 | [diff] [blame] | 337 | ### WebUIDataSource::CreateAndAdd() |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 338 | |
Rebekah Potter | a894942 | 2023-01-05 18:44:13 | [diff] [blame] | 339 | This is a factory method required to create and add a WebUIDataSource. The first |
| 340 | argument to `Create()` is the browser context. The second argument is typically |
| 341 | the host name of the page. The caller does not own the result. |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 342 | |
Rebekah Potter | a894942 | 2023-01-05 18:44:13 | [diff] [blame] | 343 | Additionally, calling `CreateAndAdd()` will overwrite any existing data source |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 344 | with the same name. |
| 345 | |
| 346 | <div class="note"> |
| 347 | It's unsafe to keep references to a <code>WebUIDataSource</code> after calling |
| 348 | <code>Add()</code>. Don't do this. |
| 349 | </div> |
| 350 | |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 351 | ### WebUIDataSource::AddLocalizedString() |
| 352 | |
| 353 | Using an int reference to a grit string (starts with "IDS" and lives in a .grd |
| 354 | or .grdp file), adding a string with a key name will be possible to reference |
| 355 | via the `$i18n{}` syntax (and will be replaced when requested) or later |
| 356 | dynamically in JavaScript via `loadTimeData.getString()` (or `getStringF`). |
| 357 | |
Lei Zhang | 5b20508 | 2022-01-25 18:08:38 | [diff] [blame] | 358 | ### WebUIDataSource::AddLocalizedStrings() |
| 359 | |
| 360 | Many Web UI data sources need to be set up with a large number of localized |
| 361 | strings. Instead of repeatedly calling <code>AddLocalizedString()</code>, create |
| 362 | an array of all the strings and use <code>AddLocalizedStrings()</code>: |
| 363 | |
| 364 | ```c++ |
| 365 | static constexpr webui::LocalizedString kStrings[] = { |
| 366 | // Localized strings (alphabetical order). |
| 367 | {"actionMenuDescription", IDS_HISTORY_ACTION_MENU_DESCRIPTION}, |
| 368 | {"ariaRoleDescription", IDS_HISTORY_ARIA_ROLE_DESCRIPTION}, |
| 369 | {"bookmarked", IDS_HISTORY_ENTRY_BOOKMARKED}, |
| 370 | }; |
| 371 | source->AddLocalizedStrings(kStrings); |
| 372 | ``` |
| 373 | |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 374 | ### WebUIDataSource::AddResourcePath() |
| 375 | |
| 376 | Using an int reference to a grit resource (starts with "IDR" and lives in a .grd |
| 377 | or .grdp file), adds a resource to the UI with the specified path. |
| 378 | |
| 379 | It's generally a good idea to call <code>AddResourcePath()</code> with the empty |
| 380 | path and a resource ID that should be served as the "catch all" resource to |
| 381 | respond with. This resource will be served for requests like "chrome://history", |
| 382 | or "chrome://history/pathThatDoesNotExist". It will not be served for requests |
| 383 | that look like they are attempting to fetch a specific file, like |
| 384 | "chrome://history/file\_that\_does\_not\_exist.js". This is so that if a user |
| 385 | enters a typo when trying to load a subpage like "chrome://history/syncedTabs" |
| 386 | they will be redirected to the main history page, instead of seeing an error, |
| 387 | but incorrect imports in the source code will fail, so that they can be more |
| 388 | easily found and corrected. |
| 389 | |
Lei Zhang | 5b20508 | 2022-01-25 18:08:38 | [diff] [blame] | 390 | ### WebUIDataSource::AddResourcePaths() |
| 391 | |
| 392 | Similar to the localized strings, many Web UIs need to add a large number of |
| 393 | resource paths. In this case, use <code>AddResourcePaths()</code> to |
| 394 | replace repeated calls to <code>AddResourcePath()</code>. |
| 395 | |
| 396 | ```c++ |
| 397 | static constexpr webui::ResourcePath kResources[] = { |
| 398 | {"browser_api.js", IDR_BROWSER_API_JS}, |
| 399 | {"constants.js", IDR_CONSTANTS_JS}, |
| 400 | {"controller.js", IDR_CONTROLLER_JS}, |
| 401 | }; |
| 402 | source->AddResourcePaths(kResources); |
| 403 | ``` |
| 404 | |
| 405 | The same method can be leveraged for cases that directly use constants defined |
| 406 | by autogenerated grit resources map header files. For example, the autogenerated |
| 407 | print\_preview\_resources\_map.h header defines a |
| 408 | <code>webui::ResourcePath</code> array named <code>kPrintPreviewResources</code> |
| 409 | and a <code>size\_t kPrintPreviewResourcesSize</code>. All the resources in this |
| 410 | resource map can be added as follows: |
| 411 | |
| 412 | ```c++ |
| 413 | source->AddResourcePaths( |
Mickey Burks | e714ad67 | 2024-10-16 20:40:54 | [diff] [blame] | 414 | base::span<const webui::ResourcePath>(kPrintPreviewResources), |
Lei Zhang | 5b20508 | 2022-01-25 18:08:38 | [diff] [blame] | 415 | ``` |
| 416 | |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 417 | ### WebUIDataSource::AddBoolean() |
| 418 | |
| 419 | Often a page needs to know whether a feature is enabled. This is a good use case |
| 420 | for `WebUIDataSource::AddBoolean()`. Then, in the Javascript, one can write |
| 421 | code like this: |
| 422 | |
| 423 | ```js |
| 424 | if (loadTimeData.getBoolean('myFeatureIsEnabled')) { |
| 425 | ... |
| 426 | } |
| 427 | ``` |
| 428 | |
| 429 | <div class="note"> |
| 430 | Data sources are not recreated on refresh, and therefore values that are dynamic |
| 431 | (i.e. that can change while Chrome is running) may easily become stale. It may |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame] | 432 | be preferable to use <code>sendWithPromise()</code> to initialize dynamic |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 433 | values and call <code>FireWebUIListener()</code> to update them. |
| 434 | |
| 435 | If you really want or need to use <code>AddBoolean()</code> for a dynamic value, |
| 436 | make sure to call <code>WebUIDataSource::Update()</code> when the value changes. |
| 437 | </div> |
| 438 | |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 439 | ## WebUI utils for working with data sources |
| 440 | |
| 441 | chrome/browser/ui/webui/webui\_util.\* contains a number of methods to simplify |
| 442 | common configuration tasks. |
| 443 | |
Rebekah Potter | 5691cab | 2020-10-29 21:30:35 | [diff] [blame] | 444 | ### webui::SetupWebUIDataSource() |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 445 | |
Rebekah Potter | 5691cab | 2020-10-29 21:30:35 | [diff] [blame] | 446 | This method performs common configuration tasks on a data source for a Web UI |
| 447 | that uses JS modules. When creating a Web UI that uses JS modules, use this |
| 448 | utility instead of duplicating the configuration steps it performs elsewhere. |
| 449 | Specific setup steps include: |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 450 | |
| 451 | * Setting the content security policy to allow the data source to load only |
| 452 | resources from its own host (e.g. chrome://history), chrome://resources, and |
Rebekah Potter | 1ebb97f | 2023-10-25 15:38:45 | [diff] [blame] | 453 | chrome://webui-test (used to serve test files). |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 454 | * Enabling i18n template replacements by calling <code>UseStringsJs()</code> and |
| 455 | <code>EnableReplaceI18nInJS()</code> on the data source. |
| 456 | * Adding the test loader files to the data source, so that test files can be |
| 457 | loaded as JS modules. |
| 458 | * Setting the resource to load for the empty path. |
Rebekah Potter | 5691cab | 2020-10-29 21:30:35 | [diff] [blame] | 459 | * Adding all resources from a GritResourceMap. |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 460 | |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 461 | ## Browser (C++) and Renderer (JS) communication |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 462 | |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 463 | ### Mojo |
| 464 | |
| 465 | [Mojo](https://chromium.googlesource.com/chromium/src/+/master/mojo/README.md) |
| 466 | is used for IPC throughout Chromium, and should generally be used for new |
| 467 | WebUIs to communicate between the browser (C++) and the renderer (JS/TS). To |
| 468 | use Mojo, you will need to: |
| 469 | |
| 470 | * Write an interface definition for the JS/C++ interface in a mojom file |
| 471 | * Add a build target in the BUILD.gn file to autogenerate C++ and TypeScript |
| 472 | code ("bindings"). |
| 473 | * Bind the interface on the C++ side and implement any methods to send or |
| 474 | receive information from TypeScript. |
| 475 | * Add the TypeScript bindings file to your WebUI's <code>ts_library()</code> |
| 476 | and use them in your TypeScript code. |
| 477 | |
| 478 | #### Mojo Interface Definition |
| 479 | Mojo interfaces are declared in mojom files. For WebUIs, these normally live |
| 480 | alongside the C++ code in chrome/browser/ui/webui. For example: |
| 481 | |
| 482 | **chrome/browser/ui/webui/donuts/donuts.mojom** |
| 483 | ``` |
| 484 | module donuts.mojom; |
| 485 | |
Rebekah Potter | 26b32f4 | 2023-10-31 20:36:47 | [diff] [blame] | 486 | // Factory ensures that the Page and PageHandler interfaces are always created |
| 487 | // together without requiring an initialization call from the WebUI to the |
| 488 | // handler. |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 489 | interface PageHandlerFactory { |
| 490 | CreatePageHandler(pending_remote<Page> page, |
| 491 | pending_receiver<PageHandler> handler); |
| 492 | }; |
| 493 | |
| 494 | // Called from TS side of chrome://donuts (Renderer -> Browser) |
| 495 | interface PageHandler { |
| 496 | StartPilotLight(); |
| 497 | |
| 498 | BakeDonuts(uint32 num_donuts); |
| 499 | |
| 500 | // Expects a response from the browser. |
| 501 | GetNumberOfDonuts() => (uint32 num_donuts); |
Kevin Graney | 1a0030f | 2023-10-24 23:31:17 | [diff] [blame] | 502 | }; |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 503 | |
| 504 | // Called from C++ side of chrome://donuts. (Browser -> Renderer) |
| 505 | interface Page { |
| 506 | DonutsBaked(uint32 num_donuts); |
Kevin Graney | 1a0030f | 2023-10-24 23:31:17 | [diff] [blame] | 507 | }; |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 508 | ``` |
| 509 | |
| 510 | #### BUILD.gn mojo target |
| 511 | mojom() is the build rule used to generate mojo bindings. It can be set up as |
| 512 | follows: |
| 513 | |
| 514 | **chrome/browser/ui/webui/donuts/BUILD.gn** |
dpapad | 994a939 | 2025-03-25 00:21:43 | [diff] [blame] | 515 | ```python |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 516 | import("//mojo/public/tools/bindings/mojom.gni") |
| 517 | |
| 518 | mojom("mojo_bindings") { |
| 519 | sources = [ "donuts.mojom" ] |
| 520 | webui_module_path = "/" |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 521 | } |
| 522 | ``` |
| 523 | |
| 524 | #### Setting up C++ bindings |
| 525 | The WebUIController class should inherit from ui::MojoWebUIController and |
| 526 | from the PageHandlerFactory class defined in the mojom file. |
| 527 | |
| 528 | **chrome/browser/ui/webui/donuts/donuts_ui.h** |
| 529 | ```c++ |
| 530 | class DonutsPageHandler; |
| 531 | |
| 532 | class DonutsUI : public ui::MojoWebUIController, |
| 533 | public donuts::mojom::PageHandlerFactory { |
| 534 | public: |
| 535 | explicit DonutsUI(content::WebUI* web_ui); |
| 536 | |
| 537 | DonutsUI(const DonutsUI&) = delete; |
| 538 | DonutsUI& operator=(const DonutsUI&) = delete; |
| 539 | |
| 540 | ~DonutsUI() override; |
| 541 | |
| 542 | // Instantiates the implementor of the mojom::PageHandlerFactory mojo |
| 543 | // interface passing the pending receiver that will be internally bound. |
| 544 | void BindInterface( |
| 545 | mojo::PendingReceiver<donuts::mojom::PageHandlerFactory> receiver); |
| 546 | |
| 547 | private: |
| 548 | // donuts::mojom::PageHandlerFactory: |
| 549 | void CreatePageHandler( |
| 550 | mojo::PendingRemote<donuts::mojom::Page> page, |
| 551 | mojo::PendingReceiver<donuts::mojom::PageHandler> receiver) override; |
| 552 | |
| 553 | std::unique_ptr<DonutsPageHandler> page_handler_; |
| 554 | |
| 555 | mojo::Receiver<donuts::mojom::PageHandlerFactory> page_factory_receiver_{ |
| 556 | this}; |
| 557 | |
| 558 | WEB_UI_CONTROLLER_TYPE_DECL(); |
| 559 | }; |
| 560 | ``` |
| 561 | |
| 562 | **chrome/browser/ui/webui/donuts/donuts_ui.cc** |
| 563 | ```c++ |
| 564 | DonutsUI::DonutsUI(content::WebUI* web_ui) |
| 565 | : ui::MojoWebUIController(web_ui, true) { |
| 566 | // Normal constructor steps (e.g. setting up data source) go here. |
| 567 | } |
| 568 | |
| 569 | WEB_UI_CONTROLLER_TYPE_IMPL(DonutsUI) |
| 570 | |
| 571 | DonutsUI::~DonutsUI() = default; |
| 572 | |
| 573 | void DonutsUI::BindInterface( |
| 574 | mojo::PendingReceiver<donuts::mojom::PageHandlerFactory> receiver) { |
| 575 | page_factory_receiver_.reset(); |
| 576 | page_factory_receiver_.Bind(std::move(receiver)); |
| 577 | } |
| 578 | |
| 579 | void DonutsUI::CreatePageHandler( |
| 580 | mojo::PendingRemote<donuts::mojom::Page> page, |
| 581 | mojo::PendingReceiver<donuts::mojom::PageHandler> receiver) { |
| 582 | DCHECK(page); |
| 583 | page_handler_ = std::make_unique<DonutsPageHandler>( |
| 584 | std::move(receiver), std::move(page)); |
| 585 | } |
| 586 | ``` |
| 587 | |
| 588 | You also need to register the PageHandlerFactory to your controller in |
Jacob Stanley | 40be5eb | 2025-03-19 17:06:55 | [diff] [blame] | 589 | **chrome/browser/chrome_browser_interface_binders_webui.cc**: |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 590 | ```c++ |
| 591 | RegisterWebUIControllerInterfaceBinder<donuts::mojom::PageHandlerFactory, |
| 592 | DonutsUI>(map); |
| 593 | ``` |
| 594 | |
| 595 | #### Using C++ bindings for communication |
| 596 | The WebUI message handler should inherit from the Mojo PageHandler class. |
| 597 | |
| 598 | **chrome/browser/ui/webui/donuts/donuts_page_handler.h** |
| 599 | ```c++ |
| 600 | #include "chrome/browser/ui/webui/donuts/donuts.mojom.h" |
| 601 | #include "mojo/public/cpp/bindings/receiver.h" |
| 602 | #include "mojo/public/cpp/bindings/remote.h" |
| 603 | |
| 604 | class DonutsPageHandler : public donuts::mojom::PageHandler { |
| 605 | public: |
| 606 | DonutsPageHandler( |
| 607 | mojo::PendingReceiver<donuts::mojom::PageHandler> receiver, |
| 608 | mojo::PendingRemote<donuts::mojom::Page> page); |
| 609 | |
| 610 | DonutsPageHandler(const DonutsPageHandler&) = delete; |
| 611 | DonutsPageHandler& operator=(const DonutsPageHandler&) = delete; |
| 612 | |
| 613 | ~DonutsPageHandler() override; |
| 614 | |
| 615 | // Triggered by some outside event |
Mickey Burks | 463e6f5 | 2024-07-02 11:45:05 | [diff] [blame] | 616 | void OnBakingDonutsFinished(uint32_t num_donuts); |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 617 | |
| 618 | // donuts::mojom::PageHandler: |
| 619 | void StartPilotLight() override; |
| 620 | void BakeDonuts(uint32_t num_donuts) override; |
| 621 | void GetNumberOfDonuts(GetNumberOfDonutsCallback callback) override; |
Mickey Burks | 463e6f5 | 2024-07-02 11:45:05 | [diff] [blame] | 622 | |
| 623 | private: |
| 624 | mojo::Receiver<donuts::mojom::PageHandler> receiver_; |
| 625 | mojo::Remote<donuts::mojom::Page> page_; |
| 626 | }; |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 627 | ``` |
| 628 | |
| 629 | The message handler needs to implement all the methods on the PageHandler |
| 630 | interface. |
| 631 | |
| 632 | **chrome/browser/ui/webui/donuts/donuts_page_handler.cc** |
| 633 | ```c++ |
| 634 | DonutsPageHandler::DonutsPageHandler( |
| 635 | mojo::PendingReceiver<donuts::mojom::PageHandler> receiver, |
| 636 | mojo::PendingRemote<donuts::mojom::Page> page) |
| 637 | : receiver_(this, std::move(receiver)), |
| 638 | page_(std::move(page)) { |
| 639 | } |
| 640 | |
| 641 | DonutsPageHandler::~DonutsPageHandler() { |
| 642 | GetOven()->TurnOffGas(); |
| 643 | } |
| 644 | |
| 645 | // Triggered by outside asynchronous event; sends information to the renderer. |
| 646 | void DonutsPageHandler::OnBakingDonutsFinished(uint32_t num_donuts) { |
| 647 | page_->DonutsBaked(num_donuts); |
| 648 | } |
| 649 | |
| 650 | // Triggered by startPilotLight() call in TS. |
| 651 | void DonutsPageHandler::StartPilotLight() { |
| 652 | GetOven()->StartPilotLight(); |
| 653 | } |
| 654 | |
| 655 | // Triggered by bakeDonuts() call in TS. |
Mickey Burks | 463e6f5 | 2024-07-02 11:45:05 | [diff] [blame] | 656 | void DonutsPageHandler::BakeDonuts(uint32_t num_donuts) { |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 657 | GetOven()->BakeDonuts(); |
| 658 | } |
| 659 | |
| 660 | // Triggered by getNumberOfDonuts() call in TS; sends a response back to the |
| 661 | // renderer. |
| 662 | void DonutsPageHandler::GetNumberOfDonuts(GetNumberOfDonutsCallback callback) { |
| 663 | uint32_t result = GetOven()->GetNumberOfDonuts(); |
| 664 | std::move(callback).Run(result); |
| 665 | } |
| 666 | ``` |
| 667 | |
| 668 | #### Setting Up TypeScript bindings |
| 669 | |
| 670 | For WebUIs using the `build_webui()` rule, the TypeScript mojo bindings can be |
| 671 | added to the build and served from the root (e.g. |
| 672 | `chrome://donuts/donuts.mojom-webui.js`) by adding the following arguments to |
| 673 | `build_webui()`: |
| 674 | |
| 675 | **chrome/browser/resources/donuts/BUILD.gn** |
dpapad | 994a939 | 2025-03-25 00:21:43 | [diff] [blame] | 676 | ```python |
Mickey Burks | 463e6f5 | 2024-07-02 11:45:05 | [diff] [blame] | 677 | import("//ui/webui/resources/tools/build_webui.gni") |
| 678 | |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 679 | build_webui("build") { |
Mickey Burks | 463e6f5 | 2024-07-02 11:45:05 | [diff] [blame] | 680 | grd_prefix = "donuts" |
| 681 | |
| 682 | # You will add these files in the next step: |
dpapad | bb3ecad | 2025-04-10 19:30:39 | [diff] [blame] | 683 | ts_files = [ |
Mickey Burks | 463e6f5 | 2024-07-02 11:45:05 | [diff] [blame] | 684 | "donuts.ts", |
| 685 | "browser_proxy.ts", |
| 686 | ] |
| 687 | |
Ryan Sultanem | bd4c2a0 | 2024-09-26 16:50:39 | [diff] [blame] | 688 | ts_deps = [ "//ui/webui/resources/mojo:build_ts" ] |
| 689 | |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 690 | mojo_files_deps = |
| 691 | [ "//chrome/browser/ui/webui/donuts:mojo_bindings_ts__generator" ] |
| 692 | mojo_files = [ |
| 693 | "$root_gen_dir/chrome/browser/ui/webui/donuts/donuts.mojom-webui.ts", |
| 694 | ] |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 695 | } |
| 696 | ``` |
| 697 | |
| 698 | It is often helpful to wrap the TypeScript side of Mojo setup in a BrowserProxy |
| 699 | class: |
| 700 | |
| 701 | **chrome/browser/resources/donuts/browser_proxy.ts** |
| 702 | ```js |
Mickey Burks | 463e6f5 | 2024-07-02 11:45:05 | [diff] [blame] | 703 | import {PageCallbackRouter, PageHandlerFactory, PageHandlerRemote} from './donuts.mojom-webui.js'; |
| 704 | import type {PageHandlerInterface} from './donuts.mojom-webui.js'; |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 705 | |
Mickey Burks | 463e6f5 | 2024-07-02 11:45:05 | [diff] [blame] | 706 | // Exporting the interface helps when creating a TestBrowserProxy wrapper. |
| 707 | export interface BrowserProxy { |
| 708 | callbackRouter: PageCallbackRouter; |
| 709 | handler: PageHandlerInterface; |
| 710 | } |
| 711 | |
| 712 | export class BrowserProxyImpl implements BrowserProxy { |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 713 | callbackRouter: PageCallbackRouter; |
| 714 | handler: PageHandlerInterface; |
| 715 | |
Mickey Burks | 463e6f5 | 2024-07-02 11:45:05 | [diff] [blame] | 716 | private constructor() { |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 717 | this.callbackRouter = new PageCallbackRouter(); |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 718 | this.handler = new PageHandlerRemote(); |
Mickey Burks | 463e6f5 | 2024-07-02 11:45:05 | [diff] [blame] | 719 | PageHandlerFactory.getRemote().createPageHandler( |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 720 | this.callbackRouter.$.bindNewPipeAndPassRemote(), |
| 721 | (this.handler as PageHandlerRemote).$.bindNewPipeAndPassReceiver()); |
| 722 | } |
| 723 | |
| 724 | static getInstance(): BrowserProxy { |
| 725 | return instance || (instance = new BrowserProxy()); |
| 726 | } |
| 727 | |
Mickey Burks | 463e6f5 | 2024-07-02 11:45:05 | [diff] [blame] | 728 | static setInstance(proxy: BrowserProxy) { |
| 729 | instance = proxy; |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 730 | } |
| 731 | } |
| 732 | |
| 733 | let instance: BrowserProxy|null = null; |
| 734 | ``` |
| 735 | |
| 736 | #### Using TypeScript bindings for communication |
| 737 | The `callbackRouter` (`PageCallbackRouter`) can be used to add listeners for |
| 738 | asynchronous events sent from the browser. |
| 739 | |
| 740 | The `handler` (`PageHandlerRemote`) can be used to send messages from the |
| 741 | renderer to the browser. For interface methods that require a browser response, |
| 742 | calling the method returns a promise. The promise will be resolved with the |
| 743 | response from the browser. |
| 744 | |
| 745 | **chrome/browser/resources/donuts/donuts.ts** |
dpapad | 994a939 | 2025-03-25 00:21:43 | [diff] [blame] | 746 | ```ts |
Mickey Burks | 463e6f5 | 2024-07-02 11:45:05 | [diff] [blame] | 747 | import {BrowserProxyImpl} from './browser_proxy.js'; |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 748 | |
| 749 | let numDonutsBaked: number = 0; |
| 750 | |
| 751 | window.onload = function() { |
| 752 | // Other page initialization steps go here |
Mickey Burks | 463e6f5 | 2024-07-02 11:45:05 | [diff] [blame] | 753 | const proxy = BrowserProxyImpl.getInstance(); |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 754 | // Tells the browser to start the pilot light. |
| 755 | proxy.handler.startPilotLight(); |
| 756 | // Adds a listener for the asynchronous "donutsBaked" event. |
| 757 | proxy.callbackRouter.donutsBaked.addListener( |
| 758 | (numDonuts: number) => { |
| 759 | numDonutsBaked += numDonuts; |
| 760 | }); |
| 761 | }; |
| 762 | |
| 763 | function CheckNumberOfDonuts() { |
| 764 | // Requests the number of donuts from the browser, and alerts with the |
| 765 | // response. |
Mickey Burks | 463e6f5 | 2024-07-02 11:45:05 | [diff] [blame] | 766 | BrowserProxyImpl.getInstance().handler.getNumberOfDonuts().then( |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 767 | (numDonuts: number) => { |
| 768 | alert('Yay, there are ' + numDonuts + ' delicious donuts left!'); |
| 769 | }); |
| 770 | } |
| 771 | |
| 772 | function BakeDonuts(numDonuts: number) { |
| 773 | // Tells the browser to bake |numDonuts| donuts. |
Mickey Burks | 463e6f5 | 2024-07-02 11:45:05 | [diff] [blame] | 774 | BrowserProxyImpl.getInstance().handler.bakeDonuts(numDonuts); |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 775 | } |
| 776 | ``` |
| 777 | |
| 778 | ### Pre-Mojo alternative: chrome.send()/WebUIMessageHandler |
| 779 | Most Chrome WebUIs were added before the introduction of Mojo, and use the |
| 780 | older style WebUIMessageHandler + chrome.send() pattern. The following sections |
| 781 | detail the methods in WebUIMessageHandler and the corresponding communication |
| 782 | methods in TypeScript/JavaScript and how to use them. |
| 783 | |
| 784 | #### WebUIMessageHandler::AllowJavascript() |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 785 | |
Adam Langley | 81be073 | 2019-03-06 18:38:45 | [diff] [blame] | 786 | A tab that has been used for settings UI may be reloaded, or may navigate to an |
| 787 | external origin. In both cases, one does not want callbacks from C++ to |
| 788 | Javascript to run. In the former case, the callbacks will occur when the |
| 789 | Javascript doesn't expect them. In the latter case, sensitive information may be |
| 790 | delivered to an untrusted origin. |
| 791 | |
| 792 | Therefore each message handler maintains |
| 793 | [a boolean](https://cs.chromium.org/search/?q=WebUIMessageHandler::javascript_allowed_) |
| 794 | that describes whether delivering callbacks to Javascript is currently |
| 795 | appropriate. This boolean is set by calling `AllowJavascript`, which should be |
| 796 | done when handling a call from Javascript, because that indicates that the page |
| 797 | is ready for the subsequent callback. (See |
| 798 | [design doc](https://drive.google.com/open?id=1z1diKvwgMmn4YFzlW1kss0yHmo8yy68TN_FUhUzRz7Q).) |
| 799 | If the tab navigates or reloads, |
| 800 | [`DisallowJavascript`](https://cs.chromium.org/search/?q=WebUIMessageHandler::DisallowJavascript) |
| 801 | is called to clear the flag. |
| 802 | |
| 803 | Therefore, before each callback from C++ to Javascript, the flag must be tested |
| 804 | by calling |
| 805 | [`IsJavascriptAllowed`](https://cs.chromium.org/search/?q=WebUIMessageHandler::IsJavascriptAllowed). |
| 806 | If false, then the callback must be dropped. (When the flag is false, calling |
| 807 | [`ResolveJavascriptCallback`](https://cs.chromium.org/search/?q=WebUIMessageHandler::ResolveJavascriptCallback) |
| 808 | will crash. See |
| 809 | [design doc](https://docs.google.com/document/d/1udXoW3aJL0-l5wrbsOg5bpYWB0qOCW5K7yXpv4tFeA8).) |
| 810 | |
| 811 | Also beware of [ABA](https://en.wikipedia.org/wiki/ABA_problem) issues: Consider |
| 812 | the case where an asynchronous operation is started, the settings page is |
| 813 | reloaded, and the user triggers another operation using the original message |
| 814 | handler. The `javascript_allowed_` boolean will be true, but the original |
| 815 | callback should still be dropped because it relates to a operation that was |
| 816 | discarded by the reload. (Reloading settings UI does _not_ cause message handler |
| 817 | objects to be deleted.) |
| 818 | |
| 819 | Thus a message handler may override |
| 820 | [`OnJavascriptDisallowed`](https://cs.chromium.org/search/?q=WebUIMessageHandler::OnJavascriptDisallowed) |
| 821 | to learn when pending callbacks should be canceled. |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 822 | |
| 823 | In the JS: |
| 824 | |
| 825 | ```js |
| 826 | window.onload = function() { |
| 827 | app.initialize(); |
| 828 | chrome.send('startPilotLight'); |
| 829 | }; |
| 830 | ``` |
| 831 | |
| 832 | In the C++: |
| 833 | |
| 834 | ```c++ |
Lei Zhang | f48bb60e | 2022-12-09 17:42:44 | [diff] [blame] | 835 | void OvenHandler::HandleStartPilotLight(const base::Value::List& /*args*/) { |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 836 | AllowJavascript(); |
| 837 | // CallJavascriptFunction() and FireWebUIListener() are now safe to do. |
| 838 | GetOven()->StartPilotLight(); |
| 839 | } |
| 840 | ``` |
| 841 | |
| 842 | <div class="note"> |
| 843 | Relying on the <code>'load'</code> event or browser-side navigation callbacks to |
| 844 | detect page readiness omits <i>application-specific</i> initialization, and a |
| 845 | custom <code>'initialized'</code> message is often necessary. |
| 846 | </div> |
| 847 | |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 848 | #### WebUIMessageHandler::CallJavascriptFunction() |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 849 | |
| 850 | When the browser process needs to tell the renderer/JS of an event or otherwise |
| 851 | execute code, it can use `CallJavascriptFunction()`. |
| 852 | |
| 853 | <div class="note"> |
| 854 | Javascript must be <a href="#AllowJavascript">allowed</a> to use |
dpapad | 32c8dd9 | 2025-01-22 19:05:16 | [diff] [blame] | 855 | <code>CallJavascriptFunction()</code>. |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 856 | </div> |
| 857 | |
| 858 | ```c++ |
| 859 | void OvenHandler::OnPilotLightExtinguished() { |
| 860 | CallJavascriptFunction("app.pilotLightExtinguished"); |
| 861 | } |
| 862 | ``` |
| 863 | |
| 864 | This works by crafting a string to be evaluated in the renderer. Any arguments |
| 865 | to the call are serialized to JSON and the parameter list is wrapped with |
| 866 | |
dpapad | 994a939 | 2025-03-25 00:21:43 | [diff] [blame] | 867 | ```c++ |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 868 | // See WebUI::GetJavascriptCall() for specifics: |
| 869 | "functionCallName(" + argumentsAsJson + ")" |
| 870 | ``` |
| 871 | |
| 872 | and sent to the renderer via a `FrameMsg_JavaScriptExecuteRequest` IPC message. |
| 873 | |
| 874 | While this works, it implies that: |
| 875 | |
| 876 | * a global method must exist to successfully run the Javascript request |
| 877 | * any method can be called with any parameter (far more access than required in |
| 878 | practice) |
| 879 | |
| 880 | ^ These factors have resulted in less use of `CallJavascriptFunction()` in the |
| 881 | webui codebase. This functionality can easily be accomplished with the following |
| 882 | alternatives: |
| 883 | |
| 884 | * [`FireWebUIListener()`](#FireWebUIListener) allows easily notifying the page |
| 885 | when an event occurs in C++ and is more loosely coupled (nothing blows up if |
| 886 | the event dispatch is ignored). JS subscribes to notifications via |
Rebekah Potter | 952290e | 2022-11-18 09:07:28 | [diff] [blame] | 887 | [`addWebUiListener`](#addWebUiListener). |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 888 | * [`ResolveJavascriptCallback`](#ResolveJavascriptCallback) and |
| 889 | [`RejectJavascriptCallback`](#RejectJavascriptCallback) are useful |
| 890 | when Javascript requires a response to an inquiry about C++-canonical state |
| 891 | (i.e. "Is Autofill enabled?", "Is the user incognito?") |
| 892 | |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 893 | #### WebUIMessageHandler::FireWebUIListener() |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 894 | |
| 895 | `FireWebUIListener()` is used to notify a registered set of listeners that an |
| 896 | event has occurred. This is generally used for events that are not guaranteed to |
| 897 | happen in timely manner, or may be caused to happen by unpredictable events |
| 898 | (i.e. user actions). |
| 899 | |
| 900 | Here's some example to detect a change to Chrome's theme: |
| 901 | |
| 902 | ```js |
Rebekah Potter | 952290e | 2022-11-18 09:07:28 | [diff] [blame] | 903 | addWebUiListener("theme-changed", refreshThemeStyles); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 904 | ``` |
| 905 | |
| 906 | This Javascript event listener can be triggered in C++ via: |
| 907 | |
| 908 | ```c++ |
| 909 | void MyHandler::OnThemeChanged() { |
| 910 | FireWebUIListener("theme-changed"); |
| 911 | } |
| 912 | ``` |
| 913 | |
| 914 | Because it's not clear when a user might want to change their theme nor what |
| 915 | theme they'll choose, this is a good candidate for an event listener. |
| 916 | |
| 917 | If you simply need to get a response in Javascript from C++, consider using |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame] | 918 | [`sendWithPromise()`](#sendWithPromise) and |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 919 | [`ResolveJavascriptCallback`](#ResolveJavascriptCallback). |
| 920 | |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 921 | #### WebUIMessageHandler::OnJavascriptAllowed() |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 922 | |
| 923 | `OnJavascriptDisallowed()` is a lifecycle method called in response to |
| 924 | [`AllowJavascript()`](#AllowJavascript). It is a good place to register |
| 925 | observers of global services or other callbacks that might call at unpredictable |
| 926 | times. |
| 927 | |
| 928 | For example: |
| 929 | |
| 930 | ```c++ |
| 931 | class MyHandler : public content::WebUIMessageHandler { |
| 932 | MyHandler() { |
| 933 | GetGlobalService()->AddObserver(this); // <-- DON'T DO THIS. |
| 934 | } |
| 935 | void OnGlobalServiceEvent() { |
| 936 | FireWebUIListener("global-thing-happened"); |
| 937 | } |
| 938 | }; |
| 939 | ``` |
| 940 | |
| 941 | Because browser-side C++ handlers are created before a renderer is ready, the |
| 942 | above code may result in calling [`FireWebUIListener`](#FireWebUIListener) |
| 943 | before the renderer is ready, which may result in dropped updates or |
| 944 | accidentally running Javascript in a renderer that has navigated to a new URL. |
| 945 | |
| 946 | A safer way to set up communication is: |
| 947 | |
| 948 | ```c++ |
| 949 | class MyHandler : public content::WebUIMessageHandler { |
| 950 | public: |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 951 | void OnJavascriptAllowed() override { |
Sigurdur Asgeirsson | fb9a9f7 | 2021-05-20 20:45:17 | [diff] [blame] | 952 | observation_.Observe(GetGlobalService()); // <-- DO THIS. |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 953 | } |
| 954 | void OnJavascriptDisallowed() override { |
Sigurdur Asgeirsson | fb9a9f7 | 2021-05-20 20:45:17 | [diff] [blame] | 955 | observation_.Reset(); // <-- AND THIS. |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 956 | } |
Sigurdur Asgeirsson | fb9a9f7 | 2021-05-20 20:45:17 | [diff] [blame] | 957 | base::ScopedObservation<MyHandler, GlobalService> observation_{this}; // <-- ALSO HANDY. |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 958 | ``` |
| 959 | when a renderer has been created and the |
| 960 | document has loaded enough to signal to the C++ that it's ready to respond to |
| 961 | messages. |
| 962 | |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 963 | #### WebUIMessageHandler::OnJavascriptDisallowed() |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 964 | |
| 965 | `OnJavascriptDisallowed` is a lifecycle method called when it's unclear whether |
dpapad | 32c8dd9 | 2025-01-22 19:05:16 | [diff] [blame] | 966 | it's safe to send JavaScript messages to the renderer. |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 967 | |
| 968 | There's a number of situations that result in this method being called: |
| 969 | |
| 970 | * renderer doesn't exist yet |
| 971 | * renderer exists but isn't ready |
Michael Giuffrida | 1493829 | 2019-05-31 21:30:23 | [diff] [blame] | 972 | * renderer is ready but application-specific JS isn't ready yet |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 973 | * tab refresh |
| 974 | * renderer crash |
| 975 | |
| 976 | Though it's possible to programmatically disable Javascript, it's uncommon to |
| 977 | need to do so. |
| 978 | |
| 979 | Because there's no single strategy that works for all cases of a renderer's |
| 980 | state (i.e. queueing vs dropping messages), these lifecycle methods were |
| 981 | introduced so a WebUI application can implement these decisions itself. |
| 982 | |
| 983 | Often, it makes sense to disconnect from observers in |
| 984 | `OnJavascriptDisallowed()`: |
| 985 | |
| 986 | ```c++ |
| 987 | void OvenHandler::OnJavascriptDisallowed() { |
Sigurdur Asgeirsson | fb9a9f7 | 2021-05-20 20:45:17 | [diff] [blame] | 988 | scoped_oven_observation_.Reset() |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 989 | } |
| 990 | ``` |
| 991 | |
| 992 | Because `OnJavascriptDisallowed()` is not guaranteed to be called before a |
| 993 | `WebUIMessageHandler`'s destructor, it is often advisable to use some form of |
| 994 | scoped observer that automatically unsubscribes on destruction but can also |
| 995 | imperatively unsubscribe in `OnJavascriptDisallowed()`. |
| 996 | |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 997 | #### WebUIMessageHandler::RejectJavascriptCallback() |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 998 | |
| 999 | This method is called in response to |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame] | 1000 | [`sendWithPromise()`](#sendWithPromise) to reject the issued Promise. This |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1001 | runs the rejection (second) callback in the [Promise's |
| 1002 | executor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) |
| 1003 | and any |
| 1004 | [`catch()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch) |
| 1005 | callbacks in the chain. |
| 1006 | |
| 1007 | ```c++ |
Lei Zhang | f48bb60e | 2022-12-09 17:42:44 | [diff] [blame] | 1008 | void OvenHandler::HandleBakeDonuts(const base::Value::List& args) { |
Michael Giuffrida | 1493829 | 2019-05-31 21:30:23 | [diff] [blame] | 1009 | AllowJavascript(); |
| 1010 | if (!GetOven()->HasGas()) { |
Lei Zhang | f48bb60e | 2022-12-09 17:42:44 | [diff] [blame] | 1011 | RejectJavascriptCallback(args[0], |
Michael Giuffrida | 1493829 | 2019-05-31 21:30:23 | [diff] [blame] | 1012 | base::StringValue("need gas to cook the donuts!")); |
| 1013 | } |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1014 | ``` |
| 1015 | |
| 1016 | This method is basically just a |
| 1017 | [`CallJavascriptFunction()`](#CallJavascriptFunction) wrapper that calls a |
| 1018 | global "cr.webUIResponse" method with a success value of false. |
| 1019 | |
| 1020 | ```c++ |
| 1021 | // WebUIMessageHandler::RejectJavascriptCallback(): |
| 1022 | CallJavascriptFunction("cr.webUIResponse", callback_id, base::Value(false), |
dbeam | 8b52edff | 2017-06-16 22:36:18 | [diff] [blame] | 1023 | response); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1024 | ``` |
| 1025 | |
| 1026 | See also: [`ResolveJavascriptCallback`](#ResolveJavascriptCallback) |
| 1027 | |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 1028 | #### WebUIMessageHandler::ResolveJavascriptCallback() |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1029 | |
| 1030 | This method is called in response to |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame] | 1031 | [`sendWithPromise()`](#sendWithPromise) to fulfill an issued Promise, |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1032 | often with a value. This results in runnings any fulfillment (first) callbacks |
| 1033 | in the associate Promise executor and any registered |
| 1034 | [`then()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) |
| 1035 | callbacks. |
| 1036 | |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame] | 1037 | So, given this TypeScript code: |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1038 | |
| 1039 | ```js |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 1040 | sendWithPromise('bakeDonuts', [5]).then(function(numDonutsBaked: number) { |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1041 | shop.donuts += numDonutsBaked; |
| 1042 | }); |
| 1043 | ``` |
| 1044 | |
| 1045 | Some handling C++ might do this: |
| 1046 | |
| 1047 | ```c++ |
Lei Zhang | f48bb60e | 2022-12-09 17:42:44 | [diff] [blame] | 1048 | void OvenHandler::HandleBakeDonuts(const base::Value::List& args) { |
Michael Giuffrida | 1493829 | 2019-05-31 21:30:23 | [diff] [blame] | 1049 | AllowJavascript(); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1050 | double num_donuts_baked = GetOven()->BakeDonuts(); |
Lei Zhang | f48bb60e | 2022-12-09 17:42:44 | [diff] [blame] | 1051 | ResolveJavascriptCallback(args[0], base::Value(num_donuts_baked)); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1052 | } |
| 1053 | ``` |
| 1054 | |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 1055 | #### chrome.send() |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1056 | |
| 1057 | When the JavaScript `window` object is created, a renderer is checked for [WebUI |
| 1058 | bindings](#bindings). |
| 1059 | |
| 1060 | ```c++ |
| 1061 | // RenderFrameImpl::DidClearWindowObject(): |
Avi Drissman | 78865bbb | 2024-08-22 20:57:19 | [diff] [blame] | 1062 | if (enabled_bindings_.Has(BindingsPolicyValue::kWebUi)) |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1063 | WebUIExtension::Install(frame_); |
| 1064 | ``` |
| 1065 | |
| 1066 | If the bindings exist, a global `chrome.send()` function is exposed to the |
| 1067 | renderer: |
| 1068 | |
| 1069 | ```c++ |
| 1070 | // WebUIExtension::Install(): |
Dan Elphick | 258bbaf | 2019-02-01 17:37:35 | [diff] [blame] | 1071 | v8::Local<v8::Object> chrome = GetOrCreateChromeObject(isolate, context); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1072 | chrome->Set(gin::StringToSymbol(isolate, "send"), |
dbeam | 8b52edff | 2017-06-16 22:36:18 | [diff] [blame] | 1073 | gin::CreateFunctionTemplate( |
Ayu Ishii | 3374343 | 2021-02-03 19:05:01 | [diff] [blame] | 1074 | isolate, |
| 1075 | base::BindRepeating(&WebUIExtension::Send))->GetFunction()); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1076 | ``` |
| 1077 | |
| 1078 | The `chrome.send()` method takes a message name and argument list. |
| 1079 | |
| 1080 | ```js |
| 1081 | chrome.send('messageName', [arg1, arg2, ...]); |
| 1082 | ``` |
| 1083 | |
| 1084 | The message name and argument list are serialized to JSON and sent via the |
Lukasz Anforowicz | 0292310 | 2017-10-09 18:11:37 | [diff] [blame] | 1085 | `FrameHostMsg_WebUISend` IPC message from the renderer to the browser. |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1086 | |
| 1087 | ```c++ |
| 1088 | // In the renderer (WebUIExtension::Send()): |
Lukasz Anforowicz | 0292310 | 2017-10-09 18:11:37 | [diff] [blame] | 1089 | render_frame->Send(new FrameHostMsg_WebUISend(render_frame->GetRoutingID(), |
| 1090 | frame->GetDocument().Url(), |
| 1091 | message, *content)); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1092 | ``` |
| 1093 | ```c++ |
| 1094 | // In the browser (WebUIImpl::OnMessageReceived()): |
Lukasz Anforowicz | 0292310 | 2017-10-09 18:11:37 | [diff] [blame] | 1095 | IPC_MESSAGE_HANDLER(FrameHostMsg_WebUISend, OnWebUISend) |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1096 | ``` |
| 1097 | |
| 1098 | The browser-side code does a map lookup for the message name and calls the found |
| 1099 | callback with the deserialized arguments: |
| 1100 | |
| 1101 | ```c++ |
| 1102 | // WebUIImpl::ProcessWebUIMessage(): |
| 1103 | message_callbacks_.find(message)->second.Run(&args); |
| 1104 | ``` |
| 1105 | |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 1106 | #### addWebUiListener() |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1107 | |
| 1108 | WebUI listeners are a convenient way for C++ to inform JavaScript of events. |
| 1109 | |
| 1110 | Older WebUI code exposed public methods for event notification, similar to how |
| 1111 | responses to [chrome.send()](#chrome_send) used to work. They both |
Ian Barkley-Yeung | 4f4f71d | 2020-06-09 00:38:13 | [diff] [blame] | 1112 | resulted in global namespace pollution, but it was additionally hard to stop |
Rebekah Potter | 952290e | 2022-11-18 09:07:28 | [diff] [blame] | 1113 | listening for events in some cases. **addWebUiListener** is preferred in new |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1114 | code. |
| 1115 | |
| 1116 | Adding WebUI listeners creates and inserts a unique ID into a map in JavaScript, |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame] | 1117 | just like [sendWithPromise()](#sendWithPromise). |
| 1118 | |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 1119 | addWebUiListener can be imported from 'chrome://resources/js/cr.js'. |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1120 | |
| 1121 | ```js |
Rebekah Potter | 952290e | 2022-11-18 09:07:28 | [diff] [blame] | 1122 | // addWebUiListener(): |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1123 | webUIListenerMap[eventName] = webUIListenerMap[eventName] || {}; |
| 1124 | webUIListenerMap[eventName][createUid()] = callback; |
| 1125 | ``` |
| 1126 | |
| 1127 | The C++ responds to a globally exposed function (`cr.webUIListenerCallback`) |
| 1128 | with an event name and a variable number of arguments. |
| 1129 | |
| 1130 | ```c++ |
| 1131 | // WebUIMessageHandler: |
| 1132 | template <typename... Values> |
| 1133 | void FireWebUIListener(const std::string& event_name, const Values&... values) { |
| 1134 | CallJavascriptFunction("cr.webUIListenerCallback", base::Value(event_name), |
| 1135 | values...); |
| 1136 | } |
| 1137 | ``` |
| 1138 | |
| 1139 | C++ handlers call this `FireWebUIListener` method when an event occurs that |
| 1140 | should be communicated to the JavaScript running in a tab. |
| 1141 | |
| 1142 | ```c++ |
| 1143 | void OvenHandler::OnBakingDonutsFinished(size_t num_donuts) { |
Toby Huang | 97ce1d5d | 2021-07-13 01:38:58 | [diff] [blame] | 1144 | FireWebUIListener("donuts-baked", base::Value(num_donuts)); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1145 | } |
| 1146 | ``` |
| 1147 | |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame] | 1148 | TypeScript can listen for WebUI events via: |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1149 | |
| 1150 | ```js |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame] | 1151 | let donutsReady: number = 0; |
Rebekah Potter | 952290e | 2022-11-18 09:07:28 | [diff] [blame] | 1152 | addWebUiListener('donuts-baked', function(numFreshlyBakedDonuts: number) { |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1153 | donutsReady += numFreshlyBakedDonuts; |
| 1154 | }); |
| 1155 | ``` |
| 1156 | |
Rebekah Potter | 65c7cae | 2022-12-15 22:19:49 | [diff] [blame] | 1157 | #### sendWithPromise() |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1158 | |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame] | 1159 | `sendWithPromise()` is a wrapper around `chrome.send()`. It's used when |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1160 | triggering a message requires a response: |
| 1161 | |
| 1162 | ```js |
| 1163 | chrome.send('getNumberOfDonuts'); // No easy way to get response! |
| 1164 | ``` |
| 1165 | |
| 1166 | In older WebUI pages, global methods were exposed simply so responses could be |
| 1167 | sent. **This is discouraged** as it pollutes the global namespace and is harder |
| 1168 | to make request specific or do from deeply nested code. |
| 1169 | |
| 1170 | In newer WebUI pages, you see code like this: |
| 1171 | |
| 1172 | ```js |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame] | 1173 | sendWithPromise('getNumberOfDonuts').then(function(numDonuts: number) { |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1174 | alert('Yay, there are ' + numDonuts + ' delicious donuts left!'); |
| 1175 | }); |
| 1176 | ``` |
| 1177 | |
Rebekah Potter | 952290e | 2022-11-18 09:07:28 | [diff] [blame] | 1178 | Note that sendWithPromise can be imported from 'chrome://resources/js/cr.js'; |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame] | 1179 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1180 | On the C++ side, the message registration is similar to |
| 1181 | [`chrome.send()`](#chrome_send) except that the first argument in the |
| 1182 | message handler's list is a callback ID. That ID is passed to |
| 1183 | `ResolveJavascriptCallback()`, which ends up resolving the `Promise` in |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame] | 1184 | JavaScript/TypeScript and calling the `then()` function. |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1185 | |
| 1186 | ```c++ |
Lei Zhang | f48bb60e | 2022-12-09 17:42:44 | [diff] [blame] | 1187 | void DonutHandler::HandleGetNumberOfDonuts(const base::Value::List& args) { |
Michael Giuffrida | 1493829 | 2019-05-31 21:30:23 | [diff] [blame] | 1188 | AllowJavascript(); |
| 1189 | |
Lei Zhang | f48bb60e | 2022-12-09 17:42:44 | [diff] [blame] | 1190 | const base::Value& callback_id = args[0]; |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1191 | size_t num_donuts = GetOven()->GetNumberOfDonuts(); |
Toby Huang | 97ce1d5d | 2021-07-13 01:38:58 | [diff] [blame] | 1192 | ResolveJavascriptCallback(callback_id, base::Value(num_donuts)); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1193 | } |
| 1194 | ``` |
| 1195 | |
| 1196 | Under the covers, a map of `Promise`s are kept in JavaScript. |
| 1197 | |
| 1198 | The callback ID is just a namespaced, ever-increasing number. It's used to |
| 1199 | insert a `Promise` into the JS-side map when created. |
| 1200 | |
| 1201 | ```js |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame] | 1202 | // sendWithPromise(): |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1203 | var id = methodName + '_' + uidCounter++; |
| 1204 | chromeSendResolverMap[id] = new PromiseResolver; |
| 1205 | chrome.send(methodName, [id].concat(args)); |
| 1206 | ``` |
| 1207 | |
| 1208 | The corresponding number is used to look up a `Promise` and reject or resolve it |
| 1209 | when the outcome is known. |
| 1210 | |
| 1211 | ```js |
| 1212 | // cr.webUIResponse(): |
| 1213 | var resolver = chromeSendResolverMap[id]; |
| 1214 | if (success) |
| 1215 | resolver.resolve(response); |
| 1216 | else |
| 1217 | resolver.reject(response); |
| 1218 | ``` |
| 1219 | |
| 1220 | This approach still relies on the C++ calling a globally exposed method, but |
| 1221 | reduces the surface to only a single global (`cr.webUIResponse`) instead of |
| 1222 | many. It also makes per-request responses easier, which is helpful when multiple |
| 1223 | are in flight. |
| 1224 | |
Lukasz Anforowicz | 11e5953 | 2018-10-23 22:46:21 | [diff] [blame] | 1225 | |
| 1226 | ## Security considerations |
| 1227 | |
| 1228 | Because WebUI pages are highly privileged, they are often targets for attack, |
| 1229 | since taking control of a WebUI page can sometimes be sufficient to escape |
| 1230 | Chrome's sandbox. To make sure that the special powers granted to WebUI pages |
| 1231 | are safe, WebUI pages are restricted in what they can do: |
| 1232 | |
Nasko Oskov | 24fc53c5 | 2021-01-08 10:02:36 | [diff] [blame] | 1233 | * WebUI pages cannot embed http/https resources |
Lukasz Anforowicz | 11e5953 | 2018-10-23 22:46:21 | [diff] [blame] | 1234 | * WebUI pages cannot issue http/https fetches |
| 1235 | |
| 1236 | In the rare case that a WebUI page really needs to include web content, the safe |
Nasko Oskov | 24fc53c5 | 2021-01-08 10:02:36 | [diff] [blame] | 1237 | way to do this is by using an `<iframe>` tag. Chrome's security model gives |
| 1238 | process isolation between the WebUI and the web content. However, some extra |
| 1239 | precautions need to be taken, because there are properties of the page that are |
| 1240 | accessible cross-origin and malicious code can take advantage of such data to |
| 1241 | attack the WebUI. Here are some things to keep in mind: |
Lukasz Anforowicz | 11e5953 | 2018-10-23 22:46:21 | [diff] [blame] | 1242 | |
Nasko Oskov | 24fc53c5 | 2021-01-08 10:02:36 | [diff] [blame] | 1243 | * The WebUI page can receive postMessage payloads from the web and should |
| 1244 | ensure it verifies any messages as they are not trustworthy. |
| 1245 | * The entire frame tree is visible to the embedded web content, including |
| 1246 | ancestor origins. |
| 1247 | * The web content runs in the same StoragePartition and Profile as the WebUI, |
| 1248 | which reflect where the WebUI page was loaded (e.g., the default profile, |
| 1249 | Incognito, etc). The corresponding user credentials will thus be available to |
| 1250 | the web content inside the WebUI, possibly showing the user as signed in. |
Lukasz Anforowicz | 11e5953 | 2018-10-23 22:46:21 | [diff] [blame] | 1251 | |
Nasko Oskov | 24fc53c5 | 2021-01-08 10:02:36 | [diff] [blame] | 1252 | Note: WebUIs have a default Content Security Policy which disallows embedding |
| 1253 | any frames. If you want to include any web content in an <iframe> you will need |
| 1254 | to update the policy for your WebUI. When doing so, allow only known origins and |
| 1255 | avoid making the policy more permissive than strictly necessary. |
Lukasz Anforowicz | 11e5953 | 2018-10-23 22:46:21 | [diff] [blame] | 1256 | |
Nasko Oskov | 24fc53c5 | 2021-01-08 10:02:36 | [diff] [blame] | 1257 | Alternatively, a `<webview>` tag can be used, which runs in a separate |
| 1258 | StoragePartition, a separate frame tree, and restricts postMessage communication |
Alex Moshchuk | 031f783 | 2023-04-04 16:59:07 | [diff] [blame] | 1259 | by default. Note that `<webview>` is only available on desktop platforms. |
Lukasz Anforowicz | 11e5953 | 2018-10-23 22:46:21 | [diff] [blame] | 1260 | |
Keren Zhu | 24f106e6 | 2024-12-12 21:06:39 | [diff] [blame] | 1261 | ## Error Reporting |
Ian Barkley-Yeung | 20a8ff7 | 2021-07-01 01:06:35 | [diff] [blame] | 1262 | |
Keren Zhu | 24f106e6 | 2024-12-12 21:06:39 | [diff] [blame] | 1263 | By default, DevTools error messages in a WebUI page will generate error reports |
| 1264 | and will appear in Google's internal [go/crash](http://go/crash) reports page. |
| 1265 | These error reports will only be generated for Google Chrome builds, not |
| 1266 | Chromium or other Chromium-based browsers. |
Ian Barkley-Yeung | 20a8ff7 | 2021-07-01 01:06:35 | [diff] [blame] | 1267 | |
Keren Zhu | 24f106e6 | 2024-12-12 21:06:39 | [diff] [blame] | 1268 | Specifically, an error report will be generated when a WebUI-based chrome:// |
| 1269 | page does one of the following: |
Ian Barkley-Yeung | 20a8ff7 | 2021-07-01 01:06:35 | [diff] [blame] | 1270 | * Generates an uncaught exception, |
| 1271 | * Has a promise which is rejected, and no rejection handler is provided, or |
| 1272 | * Calls `console.error()`. |
Keren Zhu | 24f106e6 | 2024-12-12 21:06:39 | [diff] [blame] | 1273 | * Generates any other [error level](https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/public/mojom/devtools/console_message.mojom;l=11;drc=047c7dc4ee1ce908d7fea38ca063fa2f80f92c77) |
| 1274 | DevTools message, e.g. bad websocket. |
Ian Barkley-Yeung | 20a8ff7 | 2021-07-01 01:06:35 | [diff] [blame] | 1275 | |
Keren Zhu | 24f106e6 | 2024-12-12 21:06:39 | [diff] [blame] | 1276 | Such errors will appear alongside other crashes on [go/crash](http://go/crash) |
| 1277 | with a product data type of [JavascriptError](https://crash.corp.google.com/browse?q=product_name%3D%27Chrome_Mac%27+AND+EXISTS+%28SELECT+1+FROM+UNNEST%28productdata%29+WHERE+key%3D%27type%27+AND+value%3D%27JavascriptError%27%29&stbtiq=&reportid=&index=0). |
| 1278 | They will also appear locally on the chrome://crashes page. |
Ian Barkley-Yeung | 4340462 | 2022-03-25 00:00:44 | [diff] [blame] | 1279 | |
| 1280 | The signature of the error is the error message followed by the URL on which the |
| 1281 | error appeared. For example, if chrome://settings/lazy_load.js throws a |
| 1282 | TypeError with a message `Cannot read properties of null (reading 'select')` and |
Avi Drissman | 78865bbb | 2024-08-22 20:57:19 | [diff] [blame] | 1283 | does not catch it, the magic signature would be |
Ian Barkley-Yeung | 4340462 | 2022-03-25 00:00:44 | [diff] [blame] | 1284 | ``` |
| 1285 | Uncaught TypeError: Cannot read properties of null (reading 'select') (chrome://settings) |
| 1286 | ``` |
| 1287 | To avoid spamming the system, only one error report with a given message will be |
Ian Barkley-Yeung | 20a8ff7 | 2021-07-01 01:06:35 | [diff] [blame] | 1288 | generated per hour. |
| 1289 | |
| 1290 | If you are getting error reports for an expected condition, you can turn off the |
Ian Barkley-Yeung | 4340462 | 2022-03-25 00:00:44 | [diff] [blame] | 1291 | reports simply by changing `console.error()` into `console.warn()`. For |
| 1292 | instance, if JavaScript is calling `console.error()` when the user tries to |
| 1293 | connect to an unavailable WiFi network at the same time the page shows the user |
| 1294 | an error message, the `console.error()` should be replaced with a |
| 1295 | `console.warn()`. |
Ian Barkley-Yeung | 20a8ff7 | 2021-07-01 01:06:35 | [diff] [blame] | 1296 | |
| 1297 | If you wish to get more control of the JavaScript error messages, for example |
| 1298 | to change the product name or to add additional data, you may wish to switch to |
| 1299 | using `CrashReportPrivate.reportError()`. If you do so, be sure to override |
| 1300 | `WebUIController::IsJavascriptErrorReportingEnabled()` to return false for your |
| 1301 | page; this will avoid generating redundant error reports. |
| 1302 | |
Ian Barkley-Yeung | 4340462 | 2022-03-25 00:00:44 | [diff] [blame] | 1303 | ### Are JavaScript errors actually crashes? |
| 1304 | JavaScript errors are not "crashes" in the C++ sense. They do not stop a process |
| 1305 | from running, they do not cause a "sad tab" page. Some tooling refers to them as |
| 1306 | crashes because they are going through the same pipeline as the C++ crashes, and |
| 1307 | that pipeline was originally designed to handle crashes. |
| 1308 | |
| 1309 | ### How much impact does this JavaScript error have? |
| 1310 | That depends on the JavaScript error. In some cases, the errors have no user |
| 1311 | impact; for instance, the "unavailable WiFi network calling `console.error()`" |
| 1312 | example above. In other cases, JavaScript errors may be serious errors that |
| 1313 | block the user from completing critical user journeys. For example, if the |
| 1314 | JavaScript is supposed to un-hide one of several variants of settings page, but |
| 1315 | the JavaScript has an unhandled exception before un-hiding any of them, then |
| 1316 | the user will see a blank page and be unable to change that setting. |
| 1317 | |
| 1318 | Because it is difficult to automatically determine the severity of a given |
| 1319 | error, JavaScript errors are currently all classified as "WARNING" level when |
| 1320 | computing stability metrics. |
| 1321 | |
| 1322 | ### Known issues |
Keren Zhu | 24f106e6 | 2024-12-12 21:06:39 | [diff] [blame] | 1323 | 1. Android does not support error reporting. |
| 1324 | 2. Errors are only reported for chrome:// URLs, except for pages that don't |
| 1325 | create a WebUI object (chrome://dino and chrome://network-error). Other schemes, |
| 1326 | e.g. chrome-untrusted:// and chrome-extension:// are not supported either. |
Ian Barkley-Yeung | 20a8ff7 | 2021-07-01 01:06:35 | [diff] [blame] | 1327 | 3. Unhandled promise rejections do not have a good stack. |
| 1328 | 4. The line numbers and column numbers in the stacks are for the minified |
| 1329 | JavaScript and do not correspond to the line and column numbers of the |
| 1330 | original source files. |
| 1331 | 5. Error messages with variable strings do not group well. For example, if the |
| 1332 | error message includes the name of a network, each network name will be its |
| 1333 | own signature. |
| 1334 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1335 | ## See also |
| 1336 | |
dpapad | 0993479 | 2025-01-23 16:59:50 | [diff] [blame] | 1337 | * WebUI's C++ code follows the [Chromium C++ styleguide](../../styleguide/c++/c++.md). |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1338 | * WebUI's HTML/CSS/JS code follows the [Chromium Web |
dpapad | 0993479 | 2025-01-23 16:59:50 | [diff] [blame] | 1339 | Development Style Guide](../../styleguide/web/web.md) |
Rebekah Potter | 1ebb97f | 2023-10-25 15:38:45 | [diff] [blame] | 1340 | * Adding tests for WebUI pages: [Testing WebUI](./testing_webui.md) |
Hubert Chao | 6f79e2c | 2024-04-04 14:14:31 | [diff] [blame] | 1341 | * Demo WebUI widgets at `chrome://webui-gallery` (and source at |
| 1342 | [chrome/browser/resources/webui_gallery/](https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/resources/webui_gallery/)) |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 1343 | |
| 1344 | |
| 1345 | <script> |
| 1346 | let nameEls = Array.from(document.querySelectorAll('[id], a[name]')); |
| 1347 | let names = nameEls.map(nameEl => nameEl.name || nameEl.id); |
| 1348 | |
| 1349 | let localLinks = Array.from(document.querySelectorAll('a[href^="#"]')); |
| 1350 | let hrefs = localLinks.map(a => a.href.split('#')[1]); |
| 1351 | |
| 1352 | hrefs.forEach(href => { |
| 1353 | if (names.includes(href)) |
| 1354 | console.info('found: ' + href); |
| 1355 | else |
| 1356 | console.error('broken href: ' + href); |
| 1357 | }) |
| 1358 | </script> |