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