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 |
| 91 | browser process lifecycle. |
| 92 | |
| 93 | ```c++ |
| 94 | // ChromeBrowserMainParts::PreMainMessageLoopRunImpl(): |
| 95 | content::WebUIControllerFactory::RegisterFactory( |
| 96 | ChromeWebUIControllerFactory::GetInstance()); |
| 97 | ``` |
| 98 | |
| 99 | When a URL is requested, a new renderer is created to load the URL, and a |
| 100 | corresponding class in the browser is set up to handle messages from the |
| 101 | renderer to the browser (a `RenderFrameHost`). |
| 102 | |
| 103 | The URL of the request is inspected: |
| 104 | |
| 105 | ```c++ |
| 106 | if (url.SchemeIs("chrome") && url.host_piece() == "donuts") // chrome://donuts |
| 107 | return &NewWebUI<DonutsUI>; |
| 108 | return nullptr; // Not a known host; no special access. |
| 109 | ``` |
| 110 | |
| 111 | and if a factory knows how to handle a host (returns a `WebUIFactoryFunction`), |
| 112 | the navigation machinery [grants the renderer process WebUI |
| 113 | bindings](#bindings) via the child security policy. |
| 114 | |
| 115 | ```c++ |
| 116 | // RenderFrameHostImpl::AllowBindings(): |
| 117 | if (bindings_flags & BINDINGS_POLICY_WEB_UI) { |
dbeam | 8b52edff | 2017-06-16 22:36:18 | [diff] [blame] | 118 | ChildProcessSecurityPolicyImpl::GetInstance()->GrantWebUIBindings( |
| 119 | GetProcess()->GetID()); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 120 | } |
| 121 | ``` |
| 122 | |
| 123 | The factory creates a [`WebUIController`](#WebUIController) for a tab. |
| 124 | Here's an example: |
| 125 | |
| 126 | ```c++ |
| 127 | // Controller for chrome://donuts. |
| 128 | class DonutsUI : public content::WebUIController { |
| 129 | public: |
| 130 | DonutsUI(content::WebUI* web_ui) : content::WebUIController(web_ui) { |
| 131 | content::WebUIDataSource* source = |
| 132 | content::WebUIDataSource::Create("donuts"); // "donuts" == hostname |
| 133 | source->AddString("mmmDonuts", "Mmm, donuts!"); // Translations. |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 134 | source->AddResourcePath("", IDR_DONUTS_HTML); // Home page. |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 135 | content::WebUIDataSource::Add(source); |
| 136 | |
| 137 | // Handles messages from JavaScript to C++ via chrome.send(). |
Jeremy Roman | e0760a40 | 2018-03-02 18:19:40 | [diff] [blame] | 138 | web_ui->AddMessageHandler(std::make_unique<OvenHandler>()); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 139 | } |
| 140 | }; |
| 141 | ``` |
| 142 | |
| 143 | If we assume the contents of `IDR_DONUTS_HTML` yields: |
| 144 | |
| 145 | ```html |
| 146 | <h1>$i18n{mmmDonuts}</h1> |
| 147 | ``` |
| 148 | |
| 149 | Visiting `chrome://donuts` should show in something like: |
| 150 | |
| 151 | <div style="border: 1px solid black; padding: 10px;"> |
| 152 | <h1>Mmmm, donuts!</h1> |
| 153 | </div> |
| 154 | |
| 155 | Delicious success. |
| 156 | |
Christopher Lam | 50ab1e9 | 2019-10-29 04:33:16 | [diff] [blame] | 157 | By default $i18n{} escapes strings for HTML. $i18nRaw{} can be used for |
| 158 | translations that embed HTML, and $i18nPolymer{} can be used for Polymer |
| 159 | bindings. See |
| 160 | [this comment](https://bugs.chromium.org/p/chromium/issues/detail?id=1010815#c1) |
| 161 | for more information. |
| 162 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 163 | ## C++ classes |
| 164 | |
| 165 | ### WebUI |
| 166 | |
| 167 | `WebUI` is a high-level class and pretty much all HTML-based Chrome UIs have |
| 168 | one. `WebUI` lives in the browser process, and is owned by a `RenderFrameHost`. |
| 169 | `WebUI`s have a concrete implementation (`WebUIImpl`) in `content/` and are |
| 170 | created in response to navigation events. |
| 171 | |
| 172 | A `WebUI` knows very little about the page it's showing, and it owns a |
| 173 | [`WebUIController`](#WebUIController) that is set after creation based on the |
| 174 | hostname of a requested URL. |
| 175 | |
| 176 | A `WebUI` *can* handle messages itself, but often defers these duties to |
| 177 | separate [`WebUIMessageHandler`](#WebUIMessageHandler)s, which are generally |
| 178 | designed for handling messages on certain topics. |
| 179 | |
| 180 | A `WebUI` can be created speculatively, and are generally fairly lightweight. |
| 181 | Heavier duty stuff like hard initialization logic or accessing services that may |
| 182 | have side effects are more commonly done in a |
| 183 | [`WebUIController`](#WebUIController) or |
| 184 | [`WebUIMessageHandler`s](#WebUIMessageHandler). |
| 185 | |
| 186 | `WebUI` are created synchronously on the UI thread in response to a URL request, |
| 187 | and are re-used where possible between navigations (i.e. refreshing a page). |
| 188 | Because they run in a separate process and can exist before a corresponding |
| 189 | renderer process has been created, special care is required to communicate with |
| 190 | the renderer if reliable message passing is required. |
| 191 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 192 | ### WebUIController |
| 193 | |
| 194 | A `WebUIController` is the brains of the operation, and is responsible for |
| 195 | application-specific logic, setting up translations and resources, creating |
| 196 | message handlers, and potentially responding to requests dynamically. In complex |
| 197 | pages, logic is often split across multiple |
| 198 | [`WebUIMessageHandler`s](#WebUIMessageHandler) instead of solely in the |
| 199 | controller for organizational benefits. |
| 200 | |
| 201 | A `WebUIController` is owned by a [`WebUI`](#WebUI), and is created and set on |
| 202 | an existing [`WebUI`](#WebUI) when the correct one is determined via URL |
| 203 | inspection (i.e. chrome://settings creates a generic [`WebUI`](#WebUI) with a |
| 204 | settings-specific `WebUIController`). |
| 205 | |
| 206 | ### WebUIDataSource |
| 207 | |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 208 | The `WebUIDataSource` class provides a place for data to live for WebUI pages. |
| 209 | |
| 210 | Examples types of data stored in this class are: |
| 211 | |
| 212 | * static resources (i.e. .html files packed into bundles and pulled off of disk) |
| 213 | * translations |
| 214 | * dynamic feature values (i.e. whether a feature is enabled) |
| 215 | |
| 216 | Data sources are set up in the browser process (in C++) and are accessed by |
| 217 | loading URLs from the renderer. |
| 218 | |
| 219 | Below is an example of a simple data source (in this case, Chrome's history |
| 220 | page): |
| 221 | |
| 222 | ```c++ |
| 223 | content::WebUIDataSource* source = content::WebUIDataSource::Create("history"); |
| 224 | |
| 225 | source->AddResourcePath("sign_in_promo.svg", IDR_HISTORY_SIGN_IN_PROMO_SVG); |
| 226 | source->AddResourcePath("synced_tabs.html", IDR_HISTORY_SYNCED_TABS_HTML); |
| 227 | |
| 228 | source->AddString("title", IDS_HISTORY_TITLE); |
| 229 | source->AddString("moreFromThisSite", IDS_HISTORY_MORE_FROM_THIS_SITE); |
| 230 | |
| 231 | source->AddBoolean("showDateRanges", |
| 232 | base::FeatureList::IsEnabled(features::kHistoryShowDateRanges)); |
| 233 | |
| 234 | webui::SetupWebUIDataSource( |
| 235 | source, base::make_span(kHistoryResources, kHistoryResourcesSize), |
| 236 | kGeneratedPath, IDR_HISTORY_HISTORY_HTML); |
| 237 | |
| 238 | content::WebUIDataSource::Add(source); |
| 239 | ``` |
| 240 | |
| 241 | For more about each of the methods called on `WebUIDataSource` and the utility |
| 242 | method that performs additional configuration, see [DataSources](#DataSources) |
| 243 | and [WebUIDataSourceUtils](#WebUIDataSourceUtils) |
| 244 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 245 | ### WebUIMessageHandler |
| 246 | |
| 247 | Because some pages have many messages or share code that sends messages, message |
| 248 | handling is often split into discrete classes called `WebUIMessageHandler`s. |
| 249 | These handlers respond to specific invocations from JavaScript. |
| 250 | |
| 251 | So, the given C++ code: |
| 252 | |
| 253 | ```c++ |
| 254 | void OvenHandler::RegisterMessages() { |
Ayu Ishii | 3374343 | 2021-02-03 19:05:01 | [diff] [blame] | 255 | web_ui()->RegisterMessageCallback( |
| 256 | "bakeDonuts", |
| 257 | base::BindRepeating(&OvenHandler::HandleBakeDonuts, |
| 258 | base::Unretained(this))); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 259 | } |
| 260 | |
Moe Ahmadi | de590186 | 2022-02-25 21:56:23 | [diff] [blame] | 261 | void OvenHandler::HandleBakeDonuts(const base::Value::List& args) { |
Michael Giuffrida | 1493829 | 2019-05-31 21:30:23 | [diff] [blame] | 262 | AllowJavascript(); |
| 263 | |
Lei Zhang | 72347ebdd | 2021-11-16 16:40:02 | [diff] [blame] | 264 | // IMPORTANT: Fully validate `args`. |
cammie | 720e8acd | 2021-08-25 19:15:45 | [diff] [blame] | 265 | CHECK_EQ(1u, args.size()); |
Lei Zhang | 72347ebdd | 2021-11-16 16:40:02 | [diff] [blame] | 266 | int num_donuts = args[0].GetInt(); |
| 267 | CHECK_GT(num_donuts, 0); |
| 268 | GetOven()->BakeDonuts(num_donuts); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 269 | } |
| 270 | ``` |
| 271 | |
| 272 | Can be triggered in JavaScript with this example code: |
| 273 | |
| 274 | ```js |
| 275 | $('bakeDonutsButton').onclick = function() { |
| 276 | chrome.send('bakeDonuts', [5]); // bake 5 donuts! |
| 277 | }; |
| 278 | ``` |
| 279 | |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 280 | ## Data Sources |
| 281 | |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 282 | ### WebUIDataSource::Create() |
| 283 | |
| 284 | This is a factory method required to create a WebUIDataSource instance. The |
| 285 | argument to `Create()` is typically the host name of the page. Caller owns the |
| 286 | result. |
| 287 | |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 288 | ### WebUIDataSource::Add() |
| 289 | |
| 290 | Once you've created and added some things to a data source, it'll need to be |
| 291 | "added". This means transferring ownership. In practice, the data source is |
| 292 | created in the browser process on the UI thread and transferred to the IO |
| 293 | thread. Additionally, calling `Add()` will overwrite any existing data source |
| 294 | with the same name. |
| 295 | |
| 296 | <div class="note"> |
| 297 | It's unsafe to keep references to a <code>WebUIDataSource</code> after calling |
| 298 | <code>Add()</code>. Don't do this. |
| 299 | </div> |
| 300 | |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 301 | ### WebUIDataSource::AddLocalizedString() |
| 302 | |
| 303 | Using an int reference to a grit string (starts with "IDS" and lives in a .grd |
| 304 | or .grdp file), adding a string with a key name will be possible to reference |
| 305 | via the `$i18n{}` syntax (and will be replaced when requested) or later |
| 306 | dynamically in JavaScript via `loadTimeData.getString()` (or `getStringF`). |
| 307 | |
Lei Zhang | 5b20508 | 2022-01-25 18:08:38 | [diff] [blame] | 308 | ### WebUIDataSource::AddLocalizedStrings() |
| 309 | |
| 310 | Many Web UI data sources need to be set up with a large number of localized |
| 311 | strings. Instead of repeatedly calling <code>AddLocalizedString()</code>, create |
| 312 | an array of all the strings and use <code>AddLocalizedStrings()</code>: |
| 313 | |
| 314 | ```c++ |
| 315 | static constexpr webui::LocalizedString kStrings[] = { |
| 316 | // Localized strings (alphabetical order). |
| 317 | {"actionMenuDescription", IDS_HISTORY_ACTION_MENU_DESCRIPTION}, |
| 318 | {"ariaRoleDescription", IDS_HISTORY_ARIA_ROLE_DESCRIPTION}, |
| 319 | {"bookmarked", IDS_HISTORY_ENTRY_BOOKMARKED}, |
| 320 | }; |
| 321 | source->AddLocalizedStrings(kStrings); |
| 322 | ``` |
| 323 | |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 324 | ### WebUIDataSource::AddResourcePath() |
| 325 | |
| 326 | Using an int reference to a grit resource (starts with "IDR" and lives in a .grd |
| 327 | or .grdp file), adds a resource to the UI with the specified path. |
| 328 | |
| 329 | It's generally a good idea to call <code>AddResourcePath()</code> with the empty |
| 330 | path and a resource ID that should be served as the "catch all" resource to |
| 331 | respond with. This resource will be served for requests like "chrome://history", |
| 332 | or "chrome://history/pathThatDoesNotExist". It will not be served for requests |
| 333 | that look like they are attempting to fetch a specific file, like |
| 334 | "chrome://history/file\_that\_does\_not\_exist.js". This is so that if a user |
| 335 | enters a typo when trying to load a subpage like "chrome://history/syncedTabs" |
| 336 | they will be redirected to the main history page, instead of seeing an error, |
| 337 | but incorrect imports in the source code will fail, so that they can be more |
| 338 | easily found and corrected. |
| 339 | |
Lei Zhang | 5b20508 | 2022-01-25 18:08:38 | [diff] [blame] | 340 | ### WebUIDataSource::AddResourcePaths() |
| 341 | |
| 342 | Similar to the localized strings, many Web UIs need to add a large number of |
| 343 | resource paths. In this case, use <code>AddResourcePaths()</code> to |
| 344 | replace repeated calls to <code>AddResourcePath()</code>. |
| 345 | |
| 346 | ```c++ |
| 347 | static constexpr webui::ResourcePath kResources[] = { |
| 348 | {"browser_api.js", IDR_BROWSER_API_JS}, |
| 349 | {"constants.js", IDR_CONSTANTS_JS}, |
| 350 | {"controller.js", IDR_CONTROLLER_JS}, |
| 351 | }; |
| 352 | source->AddResourcePaths(kResources); |
| 353 | ``` |
| 354 | |
| 355 | The same method can be leveraged for cases that directly use constants defined |
| 356 | by autogenerated grit resources map header files. For example, the autogenerated |
| 357 | print\_preview\_resources\_map.h header defines a |
| 358 | <code>webui::ResourcePath</code> array named <code>kPrintPreviewResources</code> |
| 359 | and a <code>size\_t kPrintPreviewResourcesSize</code>. All the resources in this |
| 360 | resource map can be added as follows: |
| 361 | |
| 362 | ```c++ |
| 363 | source->AddResourcePaths( |
| 364 | base::make_span(kPrintPreviewResources, kPrintPreviewResourcesSize)); |
| 365 | ``` |
| 366 | |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 367 | ### WebUIDataSource::AddBoolean() |
| 368 | |
| 369 | Often a page needs to know whether a feature is enabled. This is a good use case |
| 370 | for `WebUIDataSource::AddBoolean()`. Then, in the Javascript, one can write |
| 371 | code like this: |
| 372 | |
| 373 | ```js |
| 374 | if (loadTimeData.getBoolean('myFeatureIsEnabled')) { |
| 375 | ... |
| 376 | } |
| 377 | ``` |
| 378 | |
| 379 | <div class="note"> |
| 380 | Data sources are not recreated on refresh, and therefore values that are dynamic |
| 381 | (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^] | 382 | be preferable to use <code>sendWithPromise()</code> to initialize dynamic |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 383 | values and call <code>FireWebUIListener()</code> to update them. |
| 384 | |
| 385 | If you really want or need to use <code>AddBoolean()</code> for a dynamic value, |
| 386 | make sure to call <code>WebUIDataSource::Update()</code> when the value changes. |
| 387 | </div> |
| 388 | |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 389 | ## WebUI utils for working with data sources |
| 390 | |
| 391 | chrome/browser/ui/webui/webui\_util.\* contains a number of methods to simplify |
| 392 | common configuration tasks. |
| 393 | |
Rebekah Potter | 5691cab | 2020-10-29 21:30:35 | [diff] [blame] | 394 | ### webui::SetupWebUIDataSource() |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 395 | |
Rebekah Potter | 5691cab | 2020-10-29 21:30:35 | [diff] [blame] | 396 | This method performs common configuration tasks on a data source for a Web UI |
| 397 | that uses JS modules. When creating a Web UI that uses JS modules, use this |
| 398 | utility instead of duplicating the configuration steps it performs elsewhere. |
| 399 | Specific setup steps include: |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 400 | |
| 401 | * Setting the content security policy to allow the data source to load only |
| 402 | resources from its own host (e.g. chrome://history), chrome://resources, and |
| 403 | chrome://test (used to load test files). |
| 404 | * Enabling i18n template replacements by calling <code>UseStringsJs()</code> and |
| 405 | <code>EnableReplaceI18nInJS()</code> on the data source. |
| 406 | * Adding the test loader files to the data source, so that test files can be |
| 407 | loaded as JS modules. |
| 408 | * Setting the resource to load for the empty path. |
Rebekah Potter | 5691cab | 2020-10-29 21:30:35 | [diff] [blame] | 409 | * Adding all resources from a GritResourceMap. |
rbpotter | f50e025 | 2020-09-14 16:38:33 | [diff] [blame] | 410 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 411 | ## Browser (C++) → Renderer (JS) |
| 412 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 413 | ### WebUIMessageHandler::AllowJavascript() |
| 414 | |
Adam Langley | 81be073 | 2019-03-06 18:38:45 | [diff] [blame] | 415 | A tab that has been used for settings UI may be reloaded, or may navigate to an |
| 416 | external origin. In both cases, one does not want callbacks from C++ to |
| 417 | Javascript to run. In the former case, the callbacks will occur when the |
| 418 | Javascript doesn't expect them. In the latter case, sensitive information may be |
| 419 | delivered to an untrusted origin. |
| 420 | |
| 421 | Therefore each message handler maintains |
| 422 | [a boolean](https://cs.chromium.org/search/?q=WebUIMessageHandler::javascript_allowed_) |
| 423 | that describes whether delivering callbacks to Javascript is currently |
| 424 | appropriate. This boolean is set by calling `AllowJavascript`, which should be |
| 425 | done when handling a call from Javascript, because that indicates that the page |
| 426 | is ready for the subsequent callback. (See |
| 427 | [design doc](https://drive.google.com/open?id=1z1diKvwgMmn4YFzlW1kss0yHmo8yy68TN_FUhUzRz7Q).) |
| 428 | If the tab navigates or reloads, |
| 429 | [`DisallowJavascript`](https://cs.chromium.org/search/?q=WebUIMessageHandler::DisallowJavascript) |
| 430 | is called to clear the flag. |
| 431 | |
| 432 | Therefore, before each callback from C++ to Javascript, the flag must be tested |
| 433 | by calling |
| 434 | [`IsJavascriptAllowed`](https://cs.chromium.org/search/?q=WebUIMessageHandler::IsJavascriptAllowed). |
| 435 | If false, then the callback must be dropped. (When the flag is false, calling |
| 436 | [`ResolveJavascriptCallback`](https://cs.chromium.org/search/?q=WebUIMessageHandler::ResolveJavascriptCallback) |
| 437 | will crash. See |
| 438 | [design doc](https://docs.google.com/document/d/1udXoW3aJL0-l5wrbsOg5bpYWB0qOCW5K7yXpv4tFeA8).) |
| 439 | |
| 440 | Also beware of [ABA](https://en.wikipedia.org/wiki/ABA_problem) issues: Consider |
| 441 | the case where an asynchronous operation is started, the settings page is |
| 442 | reloaded, and the user triggers another operation using the original message |
| 443 | handler. The `javascript_allowed_` boolean will be true, but the original |
| 444 | callback should still be dropped because it relates to a operation that was |
| 445 | discarded by the reload. (Reloading settings UI does _not_ cause message handler |
| 446 | objects to be deleted.) |
| 447 | |
| 448 | Thus a message handler may override |
| 449 | [`OnJavascriptDisallowed`](https://cs.chromium.org/search/?q=WebUIMessageHandler::OnJavascriptDisallowed) |
| 450 | to learn when pending callbacks should be canceled. |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 451 | |
| 452 | In the JS: |
| 453 | |
| 454 | ```js |
| 455 | window.onload = function() { |
| 456 | app.initialize(); |
| 457 | chrome.send('startPilotLight'); |
| 458 | }; |
| 459 | ``` |
| 460 | |
| 461 | In the C++: |
| 462 | |
| 463 | ```c++ |
| 464 | void OvenHandler::HandleStartPilotLight(cont base::ListValue* /*args*/) { |
| 465 | AllowJavascript(); |
| 466 | // CallJavascriptFunction() and FireWebUIListener() are now safe to do. |
| 467 | GetOven()->StartPilotLight(); |
| 468 | } |
| 469 | ``` |
| 470 | |
| 471 | <div class="note"> |
| 472 | Relying on the <code>'load'</code> event or browser-side navigation callbacks to |
| 473 | detect page readiness omits <i>application-specific</i> initialization, and a |
| 474 | custom <code>'initialized'</code> message is often necessary. |
| 475 | </div> |
| 476 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 477 | ### WebUIMessageHandler::CallJavascriptFunction() |
| 478 | |
| 479 | When the browser process needs to tell the renderer/JS of an event or otherwise |
| 480 | execute code, it can use `CallJavascriptFunction()`. |
| 481 | |
| 482 | <div class="note"> |
| 483 | Javascript must be <a href="#AllowJavascript">allowed</a> to use |
| 484 | <code>CallJavscriptFunction()</code>. |
| 485 | </div> |
| 486 | |
| 487 | ```c++ |
| 488 | void OvenHandler::OnPilotLightExtinguished() { |
| 489 | CallJavascriptFunction("app.pilotLightExtinguished"); |
| 490 | } |
| 491 | ``` |
| 492 | |
| 493 | This works by crafting a string to be evaluated in the renderer. Any arguments |
| 494 | to the call are serialized to JSON and the parameter list is wrapped with |
| 495 | |
| 496 | ``` |
| 497 | // See WebUI::GetJavascriptCall() for specifics: |
| 498 | "functionCallName(" + argumentsAsJson + ")" |
| 499 | ``` |
| 500 | |
| 501 | and sent to the renderer via a `FrameMsg_JavaScriptExecuteRequest` IPC message. |
| 502 | |
| 503 | While this works, it implies that: |
| 504 | |
| 505 | * a global method must exist to successfully run the Javascript request |
| 506 | * any method can be called with any parameter (far more access than required in |
| 507 | practice) |
| 508 | |
| 509 | ^ These factors have resulted in less use of `CallJavascriptFunction()` in the |
| 510 | webui codebase. This functionality can easily be accomplished with the following |
| 511 | alternatives: |
| 512 | |
| 513 | * [`FireWebUIListener()`](#FireWebUIListener) allows easily notifying the page |
| 514 | when an event occurs in C++ and is more loosely coupled (nothing blows up if |
| 515 | the event dispatch is ignored). JS subscribes to notifications via |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame^] | 516 | [`addWebUIListener`](#addWebUIListener). |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 517 | * [`ResolveJavascriptCallback`](#ResolveJavascriptCallback) and |
| 518 | [`RejectJavascriptCallback`](#RejectJavascriptCallback) are useful |
| 519 | when Javascript requires a response to an inquiry about C++-canonical state |
| 520 | (i.e. "Is Autofill enabled?", "Is the user incognito?") |
| 521 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 522 | ### WebUIMessageHandler::FireWebUIListener() |
| 523 | |
| 524 | `FireWebUIListener()` is used to notify a registered set of listeners that an |
| 525 | event has occurred. This is generally used for events that are not guaranteed to |
| 526 | happen in timely manner, or may be caused to happen by unpredictable events |
| 527 | (i.e. user actions). |
| 528 | |
| 529 | Here's some example to detect a change to Chrome's theme: |
| 530 | |
| 531 | ```js |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame^] | 532 | addWebUIListener("theme-changed", refreshThemeStyles); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 533 | ``` |
| 534 | |
| 535 | This Javascript event listener can be triggered in C++ via: |
| 536 | |
| 537 | ```c++ |
| 538 | void MyHandler::OnThemeChanged() { |
| 539 | FireWebUIListener("theme-changed"); |
| 540 | } |
| 541 | ``` |
| 542 | |
| 543 | Because it's not clear when a user might want to change their theme nor what |
| 544 | theme they'll choose, this is a good candidate for an event listener. |
| 545 | |
| 546 | If you simply need to get a response in Javascript from C++, consider using |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame^] | 547 | [`sendWithPromise()`](#sendWithPromise) and |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 548 | [`ResolveJavascriptCallback`](#ResolveJavascriptCallback). |
| 549 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 550 | ### WebUIMessageHandler::OnJavascriptAllowed() |
| 551 | |
| 552 | `OnJavascriptDisallowed()` is a lifecycle method called in response to |
| 553 | [`AllowJavascript()`](#AllowJavascript). It is a good place to register |
| 554 | observers of global services or other callbacks that might call at unpredictable |
| 555 | times. |
| 556 | |
| 557 | For example: |
| 558 | |
| 559 | ```c++ |
| 560 | class MyHandler : public content::WebUIMessageHandler { |
| 561 | MyHandler() { |
| 562 | GetGlobalService()->AddObserver(this); // <-- DON'T DO THIS. |
| 563 | } |
| 564 | void OnGlobalServiceEvent() { |
| 565 | FireWebUIListener("global-thing-happened"); |
| 566 | } |
| 567 | }; |
| 568 | ``` |
| 569 | |
| 570 | Because browser-side C++ handlers are created before a renderer is ready, the |
| 571 | above code may result in calling [`FireWebUIListener`](#FireWebUIListener) |
| 572 | before the renderer is ready, which may result in dropped updates or |
| 573 | accidentally running Javascript in a renderer that has navigated to a new URL. |
| 574 | |
| 575 | A safer way to set up communication is: |
| 576 | |
| 577 | ```c++ |
| 578 | class MyHandler : public content::WebUIMessageHandler { |
| 579 | public: |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 580 | void OnJavascriptAllowed() override { |
Sigurdur Asgeirsson | fb9a9f7 | 2021-05-20 20:45:17 | [diff] [blame] | 581 | observation_.Observe(GetGlobalService()); // <-- DO THIS. |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 582 | } |
| 583 | void OnJavascriptDisallowed() override { |
Sigurdur Asgeirsson | fb9a9f7 | 2021-05-20 20:45:17 | [diff] [blame] | 584 | observation_.Reset(); // <-- AND THIS. |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 585 | } |
Sigurdur Asgeirsson | fb9a9f7 | 2021-05-20 20:45:17 | [diff] [blame] | 586 | base::ScopedObservation<MyHandler, GlobalService> observation_{this}; // <-- ALSO HANDY. |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 587 | ``` |
| 588 | when a renderer has been created and the |
| 589 | document has loaded enough to signal to the C++ that it's ready to respond to |
| 590 | messages. |
| 591 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 592 | ### WebUIMessageHandler::OnJavascriptDisallowed() |
| 593 | |
| 594 | `OnJavascriptDisallowed` is a lifecycle method called when it's unclear whether |
| 595 | it's safe to send JavaScript messsages to the renderer. |
| 596 | |
| 597 | There's a number of situations that result in this method being called: |
| 598 | |
| 599 | * renderer doesn't exist yet |
| 600 | * renderer exists but isn't ready |
Michael Giuffrida | 1493829 | 2019-05-31 21:30:23 | [diff] [blame] | 601 | * renderer is ready but application-specific JS isn't ready yet |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 602 | * tab refresh |
| 603 | * renderer crash |
| 604 | |
| 605 | Though it's possible to programmatically disable Javascript, it's uncommon to |
| 606 | need to do so. |
| 607 | |
| 608 | Because there's no single strategy that works for all cases of a renderer's |
| 609 | state (i.e. queueing vs dropping messages), these lifecycle methods were |
| 610 | introduced so a WebUI application can implement these decisions itself. |
| 611 | |
| 612 | Often, it makes sense to disconnect from observers in |
| 613 | `OnJavascriptDisallowed()`: |
| 614 | |
| 615 | ```c++ |
| 616 | void OvenHandler::OnJavascriptDisallowed() { |
Sigurdur Asgeirsson | fb9a9f7 | 2021-05-20 20:45:17 | [diff] [blame] | 617 | scoped_oven_observation_.Reset() |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 618 | } |
| 619 | ``` |
| 620 | |
| 621 | Because `OnJavascriptDisallowed()` is not guaranteed to be called before a |
| 622 | `WebUIMessageHandler`'s destructor, it is often advisable to use some form of |
| 623 | scoped observer that automatically unsubscribes on destruction but can also |
| 624 | imperatively unsubscribe in `OnJavascriptDisallowed()`. |
| 625 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 626 | ### WebUIMessageHandler::RejectJavascriptCallback() |
| 627 | |
| 628 | This method is called in response to |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame^] | 629 | [`sendWithPromise()`](#sendWithPromise) to reject the issued Promise. This |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 630 | runs the rejection (second) callback in the [Promise's |
| 631 | executor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) |
| 632 | and any |
| 633 | [`catch()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch) |
| 634 | callbacks in the chain. |
| 635 | |
| 636 | ```c++ |
| 637 | void OvenHandler::HandleBakeDonuts(const base::ListValue* args) { |
Michael Giuffrida | 1493829 | 2019-05-31 21:30:23 | [diff] [blame] | 638 | AllowJavascript(); |
| 639 | if (!GetOven()->HasGas()) { |
| 640 | RejectJavascriptCallback(args->GetList()[0], |
| 641 | base::StringValue("need gas to cook the donuts!")); |
| 642 | } |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 643 | ``` |
| 644 | |
| 645 | This method is basically just a |
| 646 | [`CallJavascriptFunction()`](#CallJavascriptFunction) wrapper that calls a |
| 647 | global "cr.webUIResponse" method with a success value of false. |
| 648 | |
| 649 | ```c++ |
| 650 | // WebUIMessageHandler::RejectJavascriptCallback(): |
| 651 | CallJavascriptFunction("cr.webUIResponse", callback_id, base::Value(false), |
dbeam | 8b52edff | 2017-06-16 22:36:18 | [diff] [blame] | 652 | response); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 653 | ``` |
| 654 | |
| 655 | See also: [`ResolveJavascriptCallback`](#ResolveJavascriptCallback) |
| 656 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 657 | ### WebUIMessageHandler::ResolveJavascriptCallback() |
| 658 | |
| 659 | This method is called in response to |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame^] | 660 | [`sendWithPromise()`](#sendWithPromise) to fulfill an issued Promise, |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 661 | often with a value. This results in runnings any fulfillment (first) callbacks |
| 662 | in the associate Promise executor and any registered |
| 663 | [`then()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) |
| 664 | callbacks. |
| 665 | |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame^] | 666 | So, given this TypeScript code: |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 667 | |
| 668 | ```js |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame^] | 669 | sendWithPromise('bakeDonuts').then(function(numDonutsBaked: number) { |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 670 | shop.donuts += numDonutsBaked; |
| 671 | }); |
| 672 | ``` |
| 673 | |
| 674 | Some handling C++ might do this: |
| 675 | |
| 676 | ```c++ |
| 677 | void OvenHandler::HandleBakeDonuts(const base::ListValue* args) { |
Michael Giuffrida | 1493829 | 2019-05-31 21:30:23 | [diff] [blame] | 678 | AllowJavascript(); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 679 | double num_donuts_baked = GetOven()->BakeDonuts(); |
Toby Huang | 97ce1d5d | 2021-07-13 01:38:58 | [diff] [blame] | 680 | ResolveJavascriptCallback(args->GetList()[0], base::Value(num_donuts_baked)); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 681 | } |
| 682 | ``` |
| 683 | |
| 684 | ## Renderer (JS) → Browser (C++) |
| 685 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 686 | ### chrome.send() |
| 687 | |
| 688 | When the JavaScript `window` object is created, a renderer is checked for [WebUI |
| 689 | bindings](#bindings). |
| 690 | |
| 691 | ```c++ |
| 692 | // RenderFrameImpl::DidClearWindowObject(): |
| 693 | if (enabled_bindings_ & BINDINGS_POLICY_WEB_UI) |
| 694 | WebUIExtension::Install(frame_); |
| 695 | ``` |
| 696 | |
| 697 | If the bindings exist, a global `chrome.send()` function is exposed to the |
| 698 | renderer: |
| 699 | |
| 700 | ```c++ |
| 701 | // WebUIExtension::Install(): |
Dan Elphick | 258bbaf | 2019-02-01 17:37:35 | [diff] [blame] | 702 | v8::Local<v8::Object> chrome = GetOrCreateChromeObject(isolate, context); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 703 | chrome->Set(gin::StringToSymbol(isolate, "send"), |
dbeam | 8b52edff | 2017-06-16 22:36:18 | [diff] [blame] | 704 | gin::CreateFunctionTemplate( |
Ayu Ishii | 3374343 | 2021-02-03 19:05:01 | [diff] [blame] | 705 | isolate, |
| 706 | base::BindRepeating(&WebUIExtension::Send))->GetFunction()); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 707 | ``` |
| 708 | |
| 709 | The `chrome.send()` method takes a message name and argument list. |
| 710 | |
| 711 | ```js |
| 712 | chrome.send('messageName', [arg1, arg2, ...]); |
| 713 | ``` |
| 714 | |
| 715 | 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] | 716 | `FrameHostMsg_WebUISend` IPC message from the renderer to the browser. |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 717 | |
| 718 | ```c++ |
| 719 | // In the renderer (WebUIExtension::Send()): |
Lukasz Anforowicz | 0292310 | 2017-10-09 18:11:37 | [diff] [blame] | 720 | render_frame->Send(new FrameHostMsg_WebUISend(render_frame->GetRoutingID(), |
| 721 | frame->GetDocument().Url(), |
| 722 | message, *content)); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 723 | ``` |
| 724 | ```c++ |
| 725 | // In the browser (WebUIImpl::OnMessageReceived()): |
Lukasz Anforowicz | 0292310 | 2017-10-09 18:11:37 | [diff] [blame] | 726 | IPC_MESSAGE_HANDLER(FrameHostMsg_WebUISend, OnWebUISend) |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 727 | ``` |
| 728 | |
| 729 | The browser-side code does a map lookup for the message name and calls the found |
| 730 | callback with the deserialized arguments: |
| 731 | |
| 732 | ```c++ |
| 733 | // WebUIImpl::ProcessWebUIMessage(): |
| 734 | message_callbacks_.find(message)->second.Run(&args); |
| 735 | ``` |
| 736 | |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame^] | 737 | ### addWebUIListener() |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 738 | |
| 739 | WebUI listeners are a convenient way for C++ to inform JavaScript of events. |
| 740 | |
| 741 | Older WebUI code exposed public methods for event notification, similar to how |
| 742 | responses to [chrome.send()](#chrome_send) used to work. They both |
Ian Barkley-Yeung | 4f4f71d | 2020-06-09 00:38:13 | [diff] [blame] | 743 | resulted in global namespace pollution, but it was additionally hard to stop |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 744 | listening for events in some cases. **cr.addWebUIListener** is preferred in new |
| 745 | code. |
| 746 | |
| 747 | Adding WebUI listeners creates and inserts a unique ID into a map in JavaScript, |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame^] | 748 | just like [sendWithPromise()](#sendWithPromise). |
| 749 | |
| 750 | addWebUIListener can be imported from 'chrome://resources/js/cr.m.js'. |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 751 | |
| 752 | ```js |
| 753 | // addWebUIListener(): |
| 754 | webUIListenerMap[eventName] = webUIListenerMap[eventName] || {}; |
| 755 | webUIListenerMap[eventName][createUid()] = callback; |
| 756 | ``` |
| 757 | |
| 758 | The C++ responds to a globally exposed function (`cr.webUIListenerCallback`) |
| 759 | with an event name and a variable number of arguments. |
| 760 | |
| 761 | ```c++ |
| 762 | // WebUIMessageHandler: |
| 763 | template <typename... Values> |
| 764 | void FireWebUIListener(const std::string& event_name, const Values&... values) { |
| 765 | CallJavascriptFunction("cr.webUIListenerCallback", base::Value(event_name), |
| 766 | values...); |
| 767 | } |
| 768 | ``` |
| 769 | |
| 770 | C++ handlers call this `FireWebUIListener` method when an event occurs that |
| 771 | should be communicated to the JavaScript running in a tab. |
| 772 | |
| 773 | ```c++ |
| 774 | void OvenHandler::OnBakingDonutsFinished(size_t num_donuts) { |
Toby Huang | 97ce1d5d | 2021-07-13 01:38:58 | [diff] [blame] | 775 | FireWebUIListener("donuts-baked", base::Value(num_donuts)); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 776 | } |
| 777 | ``` |
| 778 | |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame^] | 779 | TypeScript can listen for WebUI events via: |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 780 | |
| 781 | ```js |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame^] | 782 | let donutsReady: number = 0; |
| 783 | addWebUIListener('donuts-baked', function(numFreshlyBakedDonuts: number) { |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 784 | donutsReady += numFreshlyBakedDonuts; |
| 785 | }); |
| 786 | ``` |
| 787 | |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame^] | 788 | ### sendWithPromise() |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 789 | |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame^] | 790 | `sendWithPromise()` is a wrapper around `chrome.send()`. It's used when |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 791 | triggering a message requires a response: |
| 792 | |
| 793 | ```js |
| 794 | chrome.send('getNumberOfDonuts'); // No easy way to get response! |
| 795 | ``` |
| 796 | |
| 797 | In older WebUI pages, global methods were exposed simply so responses could be |
| 798 | sent. **This is discouraged** as it pollutes the global namespace and is harder |
| 799 | to make request specific or do from deeply nested code. |
| 800 | |
| 801 | In newer WebUI pages, you see code like this: |
| 802 | |
| 803 | ```js |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame^] | 804 | sendWithPromise('getNumberOfDonuts').then(function(numDonuts: number) { |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 805 | alert('Yay, there are ' + numDonuts + ' delicious donuts left!'); |
| 806 | }); |
| 807 | ``` |
| 808 | |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame^] | 809 | Note that sendWithPromise can be imported from 'chrome://resources/js/cr.m.js'; |
| 810 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 811 | On the C++ side, the message registration is similar to |
| 812 | [`chrome.send()`](#chrome_send) except that the first argument in the |
| 813 | message handler's list is a callback ID. That ID is passed to |
| 814 | `ResolveJavascriptCallback()`, which ends up resolving the `Promise` in |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame^] | 815 | JavaScript/TypeScript and calling the `then()` function. |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 816 | |
| 817 | ```c++ |
| 818 | void DonutHandler::HandleGetNumberOfDonuts(const base::ListValue* args) { |
Michael Giuffrida | 1493829 | 2019-05-31 21:30:23 | [diff] [blame] | 819 | AllowJavascript(); |
| 820 | |
| 821 | const base::Value& callback_id = args->GetList()[0]; |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 822 | size_t num_donuts = GetOven()->GetNumberOfDonuts(); |
Toby Huang | 97ce1d5d | 2021-07-13 01:38:58 | [diff] [blame] | 823 | ResolveJavascriptCallback(callback_id, base::Value(num_donuts)); |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 824 | } |
| 825 | ``` |
| 826 | |
| 827 | Under the covers, a map of `Promise`s are kept in JavaScript. |
| 828 | |
| 829 | The callback ID is just a namespaced, ever-increasing number. It's used to |
| 830 | insert a `Promise` into the JS-side map when created. |
| 831 | |
| 832 | ```js |
rbpotter | acc480cd | 2022-03-04 08:42:19 | [diff] [blame^] | 833 | // sendWithPromise(): |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 834 | var id = methodName + '_' + uidCounter++; |
| 835 | chromeSendResolverMap[id] = new PromiseResolver; |
| 836 | chrome.send(methodName, [id].concat(args)); |
| 837 | ``` |
| 838 | |
| 839 | The corresponding number is used to look up a `Promise` and reject or resolve it |
| 840 | when the outcome is known. |
| 841 | |
| 842 | ```js |
| 843 | // cr.webUIResponse(): |
| 844 | var resolver = chromeSendResolverMap[id]; |
| 845 | if (success) |
| 846 | resolver.resolve(response); |
| 847 | else |
| 848 | resolver.reject(response); |
| 849 | ``` |
| 850 | |
| 851 | This approach still relies on the C++ calling a globally exposed method, but |
| 852 | reduces the surface to only a single global (`cr.webUIResponse`) instead of |
| 853 | many. It also makes per-request responses easier, which is helpful when multiple |
| 854 | are in flight. |
| 855 | |
Lukasz Anforowicz | 11e5953 | 2018-10-23 22:46:21 | [diff] [blame] | 856 | |
| 857 | ## Security considerations |
| 858 | |
| 859 | Because WebUI pages are highly privileged, they are often targets for attack, |
| 860 | since taking control of a WebUI page can sometimes be sufficient to escape |
| 861 | Chrome's sandbox. To make sure that the special powers granted to WebUI pages |
| 862 | are safe, WebUI pages are restricted in what they can do: |
| 863 | |
Nasko Oskov | 24fc53c5 | 2021-01-08 10:02:36 | [diff] [blame] | 864 | * WebUI pages cannot embed http/https resources |
Lukasz Anforowicz | 11e5953 | 2018-10-23 22:46:21 | [diff] [blame] | 865 | * WebUI pages cannot issue http/https fetches |
| 866 | |
| 867 | 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] | 868 | way to do this is by using an `<iframe>` tag. Chrome's security model gives |
| 869 | process isolation between the WebUI and the web content. However, some extra |
| 870 | precautions need to be taken, because there are properties of the page that are |
| 871 | accessible cross-origin and malicious code can take advantage of such data to |
| 872 | attack the WebUI. Here are some things to keep in mind: |
Lukasz Anforowicz | 11e5953 | 2018-10-23 22:46:21 | [diff] [blame] | 873 | |
Nasko Oskov | 24fc53c5 | 2021-01-08 10:02:36 | [diff] [blame] | 874 | * The WebUI page can receive postMessage payloads from the web and should |
| 875 | ensure it verifies any messages as they are not trustworthy. |
| 876 | * The entire frame tree is visible to the embedded web content, including |
| 877 | ancestor origins. |
| 878 | * The web content runs in the same StoragePartition and Profile as the WebUI, |
| 879 | which reflect where the WebUI page was loaded (e.g., the default profile, |
| 880 | Incognito, etc). The corresponding user credentials will thus be available to |
| 881 | the web content inside the WebUI, possibly showing the user as signed in. |
Lukasz Anforowicz | 11e5953 | 2018-10-23 22:46:21 | [diff] [blame] | 882 | |
Nasko Oskov | 24fc53c5 | 2021-01-08 10:02:36 | [diff] [blame] | 883 | Note: WebUIs have a default Content Security Policy which disallows embedding |
| 884 | any frames. If you want to include any web content in an <iframe> you will need |
| 885 | to update the policy for your WebUI. When doing so, allow only known origins and |
| 886 | avoid making the policy more permissive than strictly necessary. |
Lukasz Anforowicz | 11e5953 | 2018-10-23 22:46:21 | [diff] [blame] | 887 | |
Nasko Oskov | 24fc53c5 | 2021-01-08 10:02:36 | [diff] [blame] | 888 | Alternatively, a `<webview>` tag can be used, which runs in a separate |
| 889 | StoragePartition, a separate frame tree, and restricts postMessage communication |
| 890 | by default. However, `<webview>` does not support Site Isolation and |
| 891 | therefore it is not advisable to use for any sensitive content. |
Lukasz Anforowicz | 11e5953 | 2018-10-23 22:46:21 | [diff] [blame] | 892 | |
Ian Barkley-Yeung | 20a8ff7 | 2021-07-01 01:06:35 | [diff] [blame] | 893 | ## JavaScript Error Reporting |
| 894 | |
| 895 | By default, errors in the JavaScript of a WebUI page will generate error reports |
| 896 | which appear in Google's internal crash/ reports page. These error reports will |
| 897 | only be generated for Google Chrome builds, not Chromium or other Chromium-based |
| 898 | browsers. |
| 899 | |
| 900 | Specifically, an error report will be generated when the JavaScript for a |
| 901 | WebUI-based chrome:// page does one of the following: |
| 902 | * Generates an uncaught exception, |
| 903 | * Has a promise which is rejected, and no rejection handler is provided, or |
| 904 | * Calls `console.error()`. |
| 905 | |
| 906 | Such errors will appear alongside other crashes in the |
| 907 | `product_name=Chrome_ChromeOS` or `product_name=Chrome_Linux` lists on crash/. |
| 908 | The signature of the error is simply the error message. To avoid |
| 909 | spamming the system, only one error report with a given message will be |
| 910 | generated per hour. |
| 911 | |
| 912 | If you are getting error reports for an expected condition, you can turn off the |
| 913 | reports simply by changing `console.error()` into `console.warn()`. |
| 914 | |
| 915 | If you wish to get more control of the JavaScript error messages, for example |
| 916 | to change the product name or to add additional data, you may wish to switch to |
| 917 | using `CrashReportPrivate.reportError()`. If you do so, be sure to override |
| 918 | `WebUIController::IsJavascriptErrorReportingEnabled()` to return false for your |
| 919 | page; this will avoid generating redundant error reports. |
| 920 | |
| 921 | Known issues: |
| 922 | 1. Error reporting is currently enabled only on ChromeOS and Linux. |
| 923 | 2. Errors are only reported for chrome:// URLs. |
| 924 | 3. Unhandled promise rejections do not have a good stack. |
| 925 | 4. The line numbers and column numbers in the stacks are for the minified |
| 926 | JavaScript and do not correspond to the line and column numbers of the |
| 927 | original source files. |
| 928 | 5. Error messages with variable strings do not group well. For example, if the |
| 929 | error message includes the name of a network, each network name will be its |
| 930 | own signature. |
| 931 | |
Lukasz Anforowicz | 11e5953 | 2018-10-23 22:46:21 | [diff] [blame] | 932 | |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 933 | ## See also |
| 934 | |
Amos Lim | f916d57 | 2018-05-21 23:10:35 | [diff] [blame] | 935 | * WebUI's C++ code follows the [Chromium C++ styleguide](../styleguide/c++/c++.md). |
Dan Beam | 079d5c1 | 2017-06-16 19:23:30 | [diff] [blame] | 936 | * WebUI's HTML/CSS/JS code follows the [Chromium Web |
| 937 | Development Style Guide](../styleguide/web/web.md) |
| 938 | |
| 939 | |
| 940 | <script> |
| 941 | let nameEls = Array.from(document.querySelectorAll('[id], a[name]')); |
| 942 | let names = nameEls.map(nameEl => nameEl.name || nameEl.id); |
| 943 | |
| 944 | let localLinks = Array.from(document.querySelectorAll('a[href^="#"]')); |
| 945 | let hrefs = localLinks.map(a => a.href.split('#')[1]); |
| 946 | |
| 947 | hrefs.forEach(href => { |
| 948 | if (names.includes(href)) |
| 949 | console.info('found: ' + href); |
| 950 | else |
| 951 | console.error('broken href: ' + href); |
| 952 | }) |
| 953 | </script> |