### Install Bubblewrap CLI Source: https://developer.chrome.google.cn/docs/android/trusted-web-activity/quick-start This command installs the Bubblewrap command-line interface globally using npm. Bubblewrap is a set of libraries and a CLI tool designed to help developers generate, build, and run Progressive Web Apps within Android applications using Trusted Web Activities. ```Shell npm i -g @bubblewrap/cli ``` -------------------------------- ### Install and Debug Trusted Web Activity Applications Source: https://developer.chrome.google.cn/docs/android/trusted-web-activity/quick-start These commands facilitate the installation of the generated APK onto a connected development device. Developers can use Bubblewrap's integrated install command or directly use the Android Debug Bridge (adb) tool. The 'adb logcat' command helps in debugging by filtering logs related to TWA provider selection, confirming which browser is handling the TWA. ```Shell bubblewrap install ``` ```Shell adb install app-release-signed.apk ``` ```Shell adb logcat -v brief | grep -e TWAProviderPicker ``` -------------------------------- ### Initialize and Build Bubblewrap Project Source: https://developer.chrome.google.cn/docs/android/trusted-web-activity/quick-start These commands are used to initialize a new Android project for a Progressive Web App (PWA) and then build it. The 'init' command reads a web manifest to configure the Android project, while 'build' generates the APK file. The generated APK is named 'app-release-signed.apk'. ```Shell bubblewrap init --manifest=https://my-twa.com/manifest.json ``` ```Shell bubblewrap build ``` -------------------------------- ### Install go/bundle CLI Tool Source: https://developer.chrome.google.cn/docs/web-platform/web-bundles This command installs the `go/bundle` command-line interface tool, which is the reference implementation for the Web Bundle specification built with Go. It fetches the tool from its GitHub repository, making it available for use in packaging web content. ```Go go get -u github.com/WICG/webpackage/go/bundle/cmd/... ``` -------------------------------- ### Example Identity Provider Configuration File Source: https://developer.chrome.google.cn/docs/privacy-sandbox/fedcm-developer-guide A comprehensive example of an Identity Provider's configuration file, detailing various endpoints, account labeling, and branding settings for FedCM integration. ```JSON { "accounts_endpoint": "/accounts.example", "client_metadata_endpoint": "/client_metadata.example", "id_assertion_endpoint": "/assertion.example", "disconnect_endpoint": "/disconnect.example", "login_url": "/login", "account_label": "developer", "supports_use_other_account": true, "branding": { "background_color": "green", "color": "#FFEEAA", "icons": [{ "url": "https://idp.example/icon.ico", "size": 25 }] } } ``` -------------------------------- ### messages.json Example with Multiple Messages Source: https://developer.chrome.google.cn/docs/extensions/how-to/ui/localization-message-formats Illustrates a complete `messages.json` file containing examples for `prompt_for_name`, `hello`, and `bye` messages. It demonstrates the use of `message`, `description`, and `placeholders` with content and example values, including how to reference substitution strings. ```JSON { "prompt_for_name": { "message": "What's your name?", "description": "Ask for the user's name" }, "hello": { "message": "Hello, $USER$", "description": "Greet the user", "placeholders": { "user": { "content": "$1", "example": "Cira" } } }, "bye": { "message": "Goodbye, $USER$. Come back to $OUR_SITE$ soon!", "description": "Say goodbye to the user", "placeholders": { "our_site": { "content": "Example.com" }, "user": { "content": "$1", "example": "Cira" } } } } ``` -------------------------------- ### Configure File Picker with Starting Directory (JavaScript) Source: https://developer.chrome.google.cn/docs/capabilities/web-apis/file-system-access This JavaScript snippet demonstrates how to use the `startIn` option with file picker methods like `self.showOpenFilePicker()` to suggest a default starting directory. This improves user experience by opening the file dialog in a relevant location, such as 'pictures' for an image editor or 'documents' for a text editor. It also shows how to use an existing `directoryHandle` as the `startIn` value. ```JavaScript const fileHandle = await self.showOpenFilePicker({ startIn: 'pictures' }); ``` ```JavaScript // Assume `directoryHandle` is a handle to a previously opened directory. const fileHandle = await self.showOpenFilePicker({ startIn: directoryHandle }); ``` -------------------------------- ### Open Onboarding Page on Extension Installation Source: https://developer.chrome.google.cn/docs/extensions/mv2/reference/tabs This JavaScript snippet demonstrates how to open a specific HTML page (e.g., an onboarding page) in a new tab when a Chrome extension is first installed. It uses the `chrome.runtime.onInstalled` listener and `chrome.tabs.create` to achieve this. ```JavaScript chrome.runtime.onInstalled.addListener(({reason}) => { if (reason === 'install') { chrome.tabs.create({ url: "onboarding.html" }); } }); ``` -------------------------------- ### Initialize Prompt API Session with Initial Prompts Source: https://developer.chrome.google.cn/docs/ai/session-management This JavaScript snippet demonstrates how to initialize a new session with the Prompt API using an 'initialPrompts' array. This sets the initial context for the AI model, guiding its responses from the start of the conversation. ```javascript const languageModel = await LanguageModel.create({ initialPrompts: [{ role: 'system', content: 'You are a helpful assistant and you speak like a pirate.' }], }); console.log(await languageModel.prompt('Tell me a joke.')); // 'Avast ye, matey! What do you call a lazy pirate?\n\nA **sail-bum!**\n\nAhoy // there, me hearties! Want to hear another one? \n' ``` -------------------------------- ### Basic FedCM Well-Known File Example Source: https://developer.chrome.google.cn/docs/privacy-sandbox/fedcm-developer-guide An example of a `/.well-known/web-identity` file content, specifying a single provider URL. This is the simplest configuration for an IdP using FedCM. ```JSON { "provider_urls": ["https://accounts.idp.example/config.json"] } ``` -------------------------------- ### Define Few-Shot Prompt for LLM Product Review Analysis Source: https://developer.chrome.google.cn/docs/ai/product-reviews-on-device This JavaScript snippet defines a multi-line string containing a few-shot prompt for a Large Language Model (LLM). The prompt instructs the LLM to analyze product reviews and assign an integer rating from 1 to 5, providing several examples of reviews with their corresponding analyses and ratings to guide the model's output. This approach is particularly useful for smaller LLMs like Gemma 2B, which benefit from detailed, example-driven instructions to achieve desired results. ```JavaScript const prompt = `Analyze a product review, and then based on your analysis give me the corresponding rating (integer). The rating should be an integer between 1 and 5. 1 is the worst rating, and 5 is the best rating. A strongly dissatisfied review that only mentions issues should have a rating of 1 (worst). A strongly satisfied review that only mentions positives and upsides should have a rating of 5 (best). Be opinionated. Use the full range of possible ratings (1 to 5). \n\n \n\n Here are some examples of reviews and their corresponding analyses and ratings: \n\n Review: 'Stylish and functional. Not sure how it'll handle rugged outdoor use, but it's perfect for urban exploring.' Analysis: The reviewer appreciates the product's style and basic functionality. They express some uncertainty about its ruggedness but overall find it suitable for their intended use, resulting in a positive, but not top-tier rating. Rating (integer): 4 \n\n Review: 'It's a solid backpack at a decent price. Does the job, but nothing particularly amazing about it.' Analysis: This reflects an average opinion. The backpack is functional and fulfills its essential purpose. However, the reviewer finds it unremarkable and lacking any standout features deserving of higher praise. Rating (integer): 3 \n\n Review: 'The waist belt broke on my first trip! Customer service was unresponsive too. Would not recommend.' Analysis: A serious product defect and poor customer service experience naturally warrants the lowest possible rating. The reviewer is extremely unsatisfied with both the product and the company. Rating (integer): 1 \n\n Review: 'Love how many pockets and compartments it has. Keeps everything organized on long trips. Durable too!' Analysis: The enthusiastic review highlights specific features the user loves (organization and durability), indicating great satisfaction with the product. This justifies the highest rating. Rating (integer): 5 \n\n Review: 'The straps are a bit flimsy, and they started digging into my shoulders under heavy loads.' Analysis: While not a totally negative review, a significant comfort issue leads the reviewer to rate the product poorly. The straps are a key component of a backpack, and their failure to perform well under load is a major flaw. Rating (integer): 1 \n\n Now, here is the review you need to assess: \n Review: "${review}" \n`; ``` -------------------------------- ### Guide Language Model Response with Assistant Prefix Source: https://developer.chrome.google.cn/docs/ai/prompt-api Demonstrates how to guide the language model's response by pre-filling part of the 'assistant' role message. Adding `prefix: true` to a trailing 'assistant'-role message helps steer the model towards a specific answer format or content. ```JavaScript const followup = await session.prompt([ { role: "user", content: "I'm nervous about my presentation tomorrow" }, { role: "assistant", content: "Presentations are tough!" } ]); ``` ```JavaScript const characterSheet = await session.prompt([ { role: 'user', content: 'Create a TOML character sheet for a gnome barbarian', }, { role: 'assistant', content: '```toml\n', prefix: true, }, ]); ``` -------------------------------- ### Browser Fetching IdP Configuration File via HTTP GET Source: https://developer.chrome.google.cn/docs/privacy-sandbox/fedcm-developer-guide This snippet illustrates the HTTP GET request made by the browser to fetch the IdP's configuration file. It highlights the absence of `Origin` and `Referer` headers and the presence of `Sec-Fetch-Dest: webidentity` for security, preventing the IdP from learning the request origin or referrer. ```HTTP GET /config.json HTTP/1.1 Host: accounts.idp.example Accept: application/json Sec-Fetch-Dest: webidentity ``` -------------------------------- ### Creating a Custom Workbox Strategy Source: https://developer.chrome.google.cn/docs/workbox/reference/workbox-strategies This example shows how to define a custom Workbox strategy by extending the `Strategy` base class from `workbox-strategies`. The `_handle` method is where the custom logic for handling requests should be implemented. ```JavaScript import {Strategy} from 'workbox-strategies'; class NewStrategy extends Strategy { _handle(request, handler) { // Define handling logic here } } ``` -------------------------------- ### Prepare Preact TodoMVC Project for Bundling Source: https://developer.chrome.google.cn/docs/web-platform/web-bundles These commands clone the `preact-todomvc` repository, navigate into its directory, install project dependencies using npm, and then build the web application. This prepares the necessary static assets and resources for packaging into a Web Bundle. ```Shell git clone https://github.com/developit/preact-todomvc.git ``` ```Shell cd preact-todomvc ``` ```npm npm i ``` ```npm npm run build ``` -------------------------------- ### Create Chrome Alarm on Extension Installation Source: https://developer.chrome.google.cn/docs/extensions/reference/api/alarms This JavaScript example shows how to create a recurring alarm named 'demo-default-alarm' with a 1-minute delay and period when the extension is first installed, using `chrome.alarms.create()`. ```JavaScript chrome.runtime.onInstalled.addListener(async ({ reason }) => { if (reason !== 'install') { return; } // Create an alarm so we have something to look at in the demo await chrome.alarms.create('demo-default-alarm', { delayInMinutes: 1, periodInMinutes: 1 }); }); ``` -------------------------------- ### WebGPU Surface Configuration and Main Loop (C++) Source: https://developer.chrome.google.cn/docs/web-platform/webgpu/build-app This C++ code snippet demonstrates how to initialize and configure a `wgpu::Surface` using `webgpu_glfw` for rendering. It includes setting up surface capabilities, format, and configuration, as well as integrating it into the main application loop for presenting textures. The `Start()` function initializes the GLFW window and WebGPU surface, then enters a loop to poll events, render, and present. ```C++ #include … wgpu::Surface surface; wgpu::TextureFormat format; void ConfigureSurface() { wgpu::SurfaceCapabilities capabilities; surface.GetCapabilities(adapter, &capabilities); format = capabilities.formats[0]; wgpu::SurfaceConfiguration config{.device = device, .format = format, .width = kWidth, .height = kHeight, .presentMode = wgpu::PresentMode::Fifo}; surface.Configure(&config); } void InitGraphics() { ConfigureSurface(); } void Render() { // TODO: Render a triangle using WebGPU. } void Start() { … surface = wgpu::glfw::CreateSurfaceForWindow(instance, window); InitGraphics(); while (!glfwWindowShouldClose(window)) { glfwPollEvents(); Render(); surface.Present(); instance.ProcessEvents(); } } ``` -------------------------------- ### Clear Browsing Data for Protected Web Origins Source: https://developer.chrome.google.cn/docs/extensions/mv2/reference/browsingData This example illustrates how to use the `originTypes` option to target data removal specifically for 'protectedWeb' origins, such as those installed as hosted applications. This is a destructive operation and should be used with caution, as it affects data for sites the user has explicitly 'installed'. ```JavaScript var callback = function () { // Do something clever here once data has been removed. }; var millisecondsPerWeek = 1000 * 60 * 60 * 24 * 7; var oneWeekAgo = (new Date()).getTime() - millisecondsPerWeek; chrome.browsingData.remove({ "since": oneWeekAgo, "originTypes": { "protectedWeb": true } }, { "appcache": true, "cache": true, "cacheStorage": true, "cookies": true, "downloads": true, "fileSystems": true, "formData": true, "history": true, "indexedDB": true, "localStorage": true, "passwords": true, "serviceWorkers": true, "webSQL": true }, callback); ``` -------------------------------- ### Initialize WebGPU Instance in C++ Source: https://developer.chrome.google.cn/docs/web-platform/webgpu/build-app This C++ code snippet demonstrates the initial setup for WebGPU by creating a global `wgpu::Instance` variable. The `Init()` function is responsible for calling `wgpu::CreateInstance()` with a descriptor that enables `timedWaitAnyEnable`, which is necessary for certain synchronization primitives. ```C++ #include wgpu::Instance instance; void Init() { wgpu::InstanceDescriptor instanceDesc{ .capabilities = {.timedWaitAnyEnable = true}}; instance = wgpu::CreateInstance(&instanceDesc); } int main() { Init(); Start(); } ``` -------------------------------- ### Configure package.json with Dependencies and Test Script Source: https://developer.chrome.google.cn/docs/extensions/mv3/tut_puppeteer-testing This snippet shows the updated `package.json` after installing Puppeteer and Jest. It includes the `puppeteer` dependency and defines a `start` script to run all Jest tests in the current directory. ```JSON { "name": "puppeteer-demo", "version": "1.0", "dependencies": { "puppeteer": "^24.8.1" }, "scripts": { "start": "jest ." } } ``` -------------------------------- ### PPB_FileSystem API Methods and Web API Equivalents Source: https://developer.chrome.google.cn/docs/native-client/migration Documentation for PPB_FileSystem methods, detailing their mapping to Emscripten and Web API functions, along with specific limitations or behavioral notes for each method. ```APIDOC PPB_FileSystem Methods: Create: - Emscripten: FS (partial) - Web API: window.requestFileSystem - Limitations: JS API does it in one step. Open: - Emscripten: GAP - Web API: window.requestFileSystem - Limitations: JS API does it in one step. GetType: - Emscripten: GAP - Web API: FileSystem.type - Limitations: None specified. ``` -------------------------------- ### Import Workbox-window with a JavaScript Bundler Source: https://developer.chrome.google.cn/docs/workbox/modules/workbox-window Shows how to import the `Workbox` class into a JavaScript file when using a bundler, after installing the package via npm. This snippet illustrates the basic setup for registering a Service Worker within a bundled application. ```JavaScript import {Workbox} from 'workbox-window'; if ('serviceWorker' in navigator) { const wb = new Workbox('/sw.js'); wb.register(); } ``` -------------------------------- ### Import Workbox-sw from CDN in Service Worker Source: https://developer.chrome.google.cn/docs/workbox/modules/workbox-sw This snippet demonstrates the simplest way to get started with `workbox-sw` by importing it directly from the Workbox CDN. This makes the global `workbox` namespace available, providing access to all Workbox modules. ```JavaScript importScripts( 'https://storage.googleapis.com/workbox-cdn/releases/6.4.1/workbox-sw.js' ); ``` -------------------------------- ### Defining Routes for Non-GET HTTP Methods in Workbox Source: https://developer.chrome.google.cn/docs/workbox/modules/workbox-routing By default, Workbox routes assume GET requests. This example demonstrates how to explicitly define routes for other HTTP methods, such as POST, by specifying the method as the third argument to `registerRoute`. ```javascript import {registerRoute} from 'workbox-routing'; registerRoute(matchCb, handlerCb, 'POST'); registerRoute(new RegExp('/api/.*\\.json'), handlerCb, 'POST'); ``` -------------------------------- ### Configure Workbox Strategy to Cache by Custom Header Source: https://developer.chrome.google.cn/docs/workbox/modules/workbox-cacheable-response This JavaScript example shows how to use `CacheableResponsePlugin` with a `StaleWhileRevalidate` strategy to cache responses based on a custom HTTP header. It caches responses for paths starting with `/path/to/api/` if they contain the header `X-Is-Cacheable` with the value `true`. ```javascript import {registerRoute} from 'workbox-routing'; import {StaleWhileRevalidate} from 'workbox-strategies'; import {CacheableResponsePlugin} from 'workbox-cacheable-response'; registerRoute( ({url}) => url.pathname.startsWith('/path/to/api/'), new StaleWhileRevalidate({ cacheName: 'api-cache', plugins: [ new CacheableResponsePlugin({ headers: { 'X-Is-Cacheable': 'true', }, }), ], }) ); ``` -------------------------------- ### Creating a WebGPU Render Pipeline with WGSL Shaders (C++) Source: https://developer.chrome.google.cn/docs/web-platform/webgpu/build-app This C++ code defines a WGSL vertex and fragment shader for drawing a red triangle. It then shows how to create a `wgpu::ShaderModule` from the shader code and construct a `wgpu::RenderPipeline` using the shader module and color target state. The `CreateRenderPipeline()` function is called within `InitGraphics()` to set up the pipeline. ```C++ wgpu::RenderPipeline pipeline; … const char shaderCode[] = R"( @vertex fn vertexMain(@builtin(vertex_index) i : u32) -> @builtin(position) vec4f { const pos = array(vec2f(0, 1), vec2f(-1, -1), vec2f(1, -1)); return vec4f(pos[i], 0, 1); } @fragment fn fragmentMain() -> @location(0) vec4f { return vec4f(1, 0, 0, 1); } )"; void CreateRenderPipeline() { wgpu::ShaderSourceWGSL wgsl{{.code = shaderCode}}; wgpu::ShaderModuleDescriptor shaderModuleDescriptor{.nextInChain = &wgsl}; wgpu::ShaderModule shaderModule = device.CreateShaderModule(&shaderModuleDescriptor); wgpu::ColorTargetState colorTargetState{.format = format}; wgpu::FragmentState fragmentState{ .module = shaderModule, .targetCount = 1, .targets = &colorTargetState}; wgpu::RenderPipelineDescriptor descriptor{.vertex = {.module = shaderModule}, .fragment = &fragmentState}; pipeline = device.CreateRenderPipeline(&descriptor); } void InitGraphics() { … CreateRenderPipeline(); } ``` -------------------------------- ### Example IME: Uppercase Conversion Source: https://developer.chrome.google.cn/docs/extensions/reference/api/input/ime This JavaScript code demonstrates a simple Input Method Editor (IME) that converts all typed lowercase letters to uppercase. It listens for focus events to get the current context ID and then processes keydown events, committing the uppercase version of 'a-z' characters. ```JavaScript var context_id = -1; chrome.input.ime.onFocus.addListener(function(context) { context_id = context.contextID; }); chrome.input.ime.onKeyEvent.addListener( function(engineID, keyData) { if (keyData.type == "keydown" && keyData.key.match(/^[a-z]$/)) { chrome.input.ime.commitText({"contextID": context_id, "text": keyData.key.toUpperCase()}); return true; } else { return false; } } ); ``` -------------------------------- ### PPB_Fullscreen API Methods and Web API Equivalents Source: https://developer.chrome.google.cn/docs/native-client/migration Documentation for PPB_Fullscreen methods, detailing their mapping to Emscripten and Web API functions, along with specific limitations or behavioral notes for each method. ```APIDOC PPB_Fullscreen Methods: IsFullScreen: - Emscripten: html5.h - Web API: Document.fullscreenEnabled - Limitations: None specified. SetFullscreen: - Emscripten: html5.h - Web API: Document.requestFullscreen - Limitations: None specified. GetScreenSize: - Emscripten: html5.h - Web API: Document.exitFullscreen - Limitations: None specified. ``` -------------------------------- ### Read a Bluetooth GATT Characteristic Value in JavaScript Source: https://developer.chrome.google.cn/docs/capabilities/bluetooth This example demonstrates how to read the value of a specific GATT characteristic from a connected Bluetooth device. It retrieves the primary service (e.g., 'battery_service') and then the desired characteristic (e.g., 'battery_level') before calling `readValue()` to get the current data. ```JavaScript navigator.bluetooth.requestDevice({ filters: [{ services: ['battery_service'] }] }) .then(device => device.gatt.connect()) .then(server => { // Getting Battery Service… return server.getPrimaryService('battery_service'); }) .then(service => { // Getting Battery Level Characteristic… return service.getCharacteristic('battery_level'); }) .then(characteristic => { // Reading Battery Level… return characteristic.readValue(); }) .then(value => { console.log(`Battery percentage is ${value.getUint8(0)}`); }) .catch(error => { console.error(error); }); ``` -------------------------------- ### Chrome Extension Manifest V3 Configuration Source: https://developer.chrome.google.cn/docs/extensions/get-started/tutorial/hello-world This JSON snippet defines the basic configuration for a Chrome Extension using Manifest V3. It specifies the extension's name, description, version, manifest version, and action properties including the default popup HTML file and icon. ```json { "name": "Hello Extensions", "description": "Base Level Extension", "version": "1.0", "manifest_version": 3, "action": { "default_popup": "hello.html", "default_icon": "hello_extensions.png" } } ``` -------------------------------- ### Example of a Broken Service Worker for Termination Testing Source: https://developer.chrome.google.cn/docs/extensions/how-to/test/test-serviceworker-termination-with-puppeteer This JavaScript code represents a simplified Chrome Extension Service Worker that stores data in a global variable upon installation and responds to messages with that data. It's designed to demonstrate a 'broken' state where data is lost upon service worker termination, highlighting the need for robust state management in extensions. ```JavaScript let data; chrome.runtime.onInstalled.addListener(() => { data = { version: chrome.runtime.getManifest().version }; }); chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { sendResponse(data.version); }); ``` -------------------------------- ### PPB_Gamepad API Methods and Web API Equivalents Source: https://developer.chrome.google.cn/docs/native-client/migration Documentation for PPB_Gamepad methods, detailing their mapping to Emscripten and Web API functions, along with specific limitations or behavioral notes for each method. ```APIDOC PPB_Gamepad Methods: Sample: - Emscripten: SDL - Web API: Gamepad.* - Limitations: Gamepad objects expose timestamps relative to navigationStart. This value is updated when data is received from the hardware: https://www.w3.org/TR/gamepad/#gamepad-interface ``` -------------------------------- ### Track Online/Offline Interactions with Google Analytics Custom Dimensions Source: https://developer.chrome.google.cn/docs/workbox/modules/workbox-google-analytics This example shows how to use Workbox Google Analytics with custom dimensions to differentiate between online and offline user interactions. It configures `parameterOverrides` to set a custom dimension (e.g., `cd1`) to 'offline' for requests replayed by the Service Worker, and provides an optional standard Google Analytics setup to set the same dimension to 'online' for initial, successful requests. ```JavaScript import * as googleAnalytics from 'workbox-google-analytics'; googleAnalytics.initialize({ parameterOverrides: { cd1: 'offline', }, }); ``` ```JavaScript ``` -------------------------------- ### Configure WebGPU Compute Pipeline Source: https://developer.chrome.google.cn/docs/capabilities/web-apis/gpu-compute This JavaScript snippet demonstrates how to create a `GPUComputePipeline` using `device.createComputePipeline`. It links the previously defined `bindGroupLayout` and the `shaderModule` (containing the WGSL code) to set up the complete compute pipeline, specifying the entry point for the compute shader. ```JavaScript const computePipeline = device.createComputePipeline({ layout: device.createPipelineLayout({ bindGroupLayouts: [bindGroupLayout] }), compute: { module: shaderModule, entryPoint: "main" } }); ``` -------------------------------- ### PPB_FileIO API Methods and Web API Equivalents Source: https://developer.chrome.google.cn/docs/native-client/migration Documentation for PPB_FileIO methods, detailing their mapping to Emscripten and Web API functions, along with specific limitations or behavioral notes for each method. ```APIDOC PPB_FileIO Methods: Create: - Emscripten: FS (partial) - Web API: window.chooseFileSystemEntries() - Limitations: 'create' and 'open' are used differently but serve the same purpose. Open: - Emscripten: FS (partial) - Web API: window.chooseFileSystemEntries() - Limitations: None specified. Query: - Emscripten: FS (partial) - Web API: Blob.size, FileSystemHandle.getFile(), FileSystemHandle.getDirectory(), File.lastModified - Limitations: GAP (partial) - Blob.type can also be used to check MIME type. Cannot determine file system type, creation time, and last access time using Native File System API. Touch: - Emscripten: FS (partial) - Web API: FileSystemDirectoryHandle.getFile("name", {create: true}) - Limitations: None specified. Read: - Emscripten: FS (partial) - Web API: Blob.slice().arrayBuffer() - Limitations: None specified. Write: - Emscripten: FS (partial) - Web API: FileSystemWriter.write() - Limitations: None specified. SetLength: - Emscripten: FS (partial) - Web API: FileSystemWriter.truncate() - Limitations: None specified. Flush: - Emscripten: GAP (partial) - Web API: GAP (partial) - When FileSystemWrite.close() is called, the system will flush the file - Limitations: This is by design, as Native File System API files are exposed to the operating system, so a Safe Browsing check is required before data is exposed to the OS. Close: - Emscripten: FS (partial) - Web API: FileSystemWriter.close() - Limitations: Does not cancel pending operations, but flushes all data written so far to disk. ReadToArray: - Emscripten: GAP - Web API: Blob.slice().arrayBuffer() or Blob.arrayBuffer() - Limitations: Allows multiple sub-range reads to be performed in parallel. ``` -------------------------------- ### File System Access API: Core Methods and Polyfill Alternatives Source: https://developer.chrome.google.cn/docs/capabilities/web-apis/file-system-access This section outlines key methods of the File System Access API and discusses potential polyfill alternatives for environments where the API is not fully supported. It highlights the limitations of these alternatives compared to the native API. ```APIDOC File System Access API Methods: showOpenFilePicker(options?: OpenFilePickerOptions): Promise - Displays a file picker that allows a user to select one or more files. - Parameters: - options: An object with properties like `multiple` (boolean), `excludeAcceptAllOption` (boolean), `types` (array of `FilePickerAcceptType`). - Returns: A Promise that resolves with an array of `FileSystemFileHandle` objects. - Polyfill Alternative: `` element. showSaveFilePicker(options?: SaveFilePickerOptions): Promise - Displays a file picker that allows a user to select a file to save to. - Parameters: - options: An object with properties like `suggestedName` (string), `types` (array of `FilePickerAcceptType`). - Returns: A Promise that resolves with a `FileSystemFileHandle` object. - Polyfill Alternative: `` element (triggers programmatic download, no overwrite). showDirectoryPicker(options?: DirectoryPickerOptions): Promise - Displays a directory picker that allows a user to select a directory. - Parameters: - options: An object with properties like `id` (string), `mode` ('read' | 'readwrite'), `startIn` (WellKnownDirectory | FileSystemHandle). - Returns: A Promise that resolves with a `FileSystemDirectoryHandle` object. - Polyfill Alternative: Non-standard `` element. ``` -------------------------------- ### Chrome Extension External Installation JSON (Supported Locales) Source: https://developer.chrome.google.cn/docs/extensions/mv2/external_extensions This JSON configuration snippet demonstrates how to restrict a Chrome extension's external installation to specific browser locales on Mac and Linux. The `supported_locales` field accepts an array of locale strings; if the browser's locale is not supported, the extension will be uninstalled. ```JSON { "external_update_url": "https://clients2.google.com/service/update2/crx", "supported_locales": [ "en", "fr", "de" ] } ``` -------------------------------- ### Windows Registry Configuration for Chrome Extension External Installation Source: https://developer.chrome.google.cn/docs/extensions/mv2/external_extensions This APIDOC entry describes the Windows Registry structure used for externally installing Chrome extensions. It specifies the required registry keys and values, including the `update_url` property that points to the Chrome Web Store for updates. This method is applicable for both 32-bit and 64-bit Windows systems. ```APIDOC Registry Key Paths: - 32-bit Windows: HKEY_LOCAL_MACHINE\Software\Google\Chrome\Extensions - 64-bit Windows: HKEY_LOCAL_MACHINE\Software\Wow6432Node\Google\Chrome\Extensions Configuration: Under the 'Extensions' key, create a new key (folder) named after your extension's ID (e.g., 'aaaaaaaaaabbbbbbbbbbcccccccccc'). Inside this extension ID key, create a string value named 'update_url' with the following data: Value Name: update_url Value Data: "https://clients2.google.com/service/update2/crx" Example Registry Entry (Conceptual JSON representation): { "update_url": "https://clients2.google.com/service/update2/crx" } ``` -------------------------------- ### Build Web Bundle (.wbn) File using gen-bundle Source: https://developer.chrome.google.cn/docs/web-platform/web-bundles This command utilizes the `gen-bundle` CLI tool to create a Web Bundle (.wbn) file. It specifies the build output directory, the base URL for the bundled content, the primary URL for the bundle, and the output filename for the generated Web Bundle. ```Shell gen-bundle -dir build -baseURL https://preact-todom.vc/ -primaryURL https://preact-todom.vc/ -o todomvc.wbn ``` -------------------------------- ### Chrome Extension External Installation JSON (Linux Local CRX) Source: https://developer.chrome.google.cn/docs/extensions/mv2/external_extensions This JSON configuration snippet is used on Linux to specify the local path and version of a Chrome extension's .crx file for external installation. It defines `external_crx` for the file path and `external_version` for the extension's version. Note that backslashes in paths must be escaped. ```JSON { "external_crx": "/home/share/extension.crx", "external_version": "1.0" } ``` -------------------------------- ### PPAPI Instance API Mappings Source: https://developer.chrome.google.cn/docs/native-client/migration Documents the PPB_Instance interface, detailing its methods, assumed execution threads, Emscripten equivalents, corresponding Web API functions, and any known limitations or partial support. ```APIDOC PPB_Instance Interface Methods: - BindGraphics - Assumed Thread: SDL - Emscripten: (None specified) - Web API: Canvas.getContext (invalid as binding is automatic). - Limitations: (None specified) - IsFullFrame - Assumed Thread: GAP - Emscripten: (None specified) - Web API: GAP - No equivalent functionality for MIME type handlers. - Limitations: NaCl applications can register to handle specific MIME types and own the entire document. - DidCreate - Assumed Thread: N/A - Emscripten: (None specified) - Web API: [key] - Limitations: With general DOM access, you can extract tag attributes. - DidDestroy - Assumed Thread: N/A - Emscripten: (None specified) - Web API: N/A - Limitations: Not triggered by NaCl. - DidChangeView - Assumed Thread: N/A - Emscripten: (None specified) - Web API: Element "resize" event - Limitations: (None specified) - DidChangeFocus - Assumed Thread: N/A - Emscripten: (None specified) - Web API: Element "focus" "focusin" "focusout" events - Limitations: (None specified) - HandleDocumentLoad - Assumed Thread: N/A - Emscripten: (None specified) - Web API: GAP - Cannot register as a MIME type handler - Limitations: NaCl modules (via app + manifest entry) can be set to handle specific MIME types. ``` -------------------------------- ### Configure VideoEncoder and check support Source: https://developer.chrome.google.cn/docs/web-platform/best-practices/webcodecs Demonstrates how to initialize a `VideoEncoder` with output and error handlers, and configure it with video parameters like codec, dimensions, bitrate, and framerate. It also shows how to use `VideoEncoder.isConfigSupported()` to check if the browser supports the desired configuration before proceeding. ```javascript const init = { output: handleChunk, error: (e) => { console.log(e.message); }, }; const config = { codec: "vp8", width: 640, height: 480, bitrate: 2_000_000, // 2 Mbps framerate: 30, }; const { supported } = await VideoEncoder.isConfigSupported(config); if (supported) { const encoder = new VideoEncoder(init); encoder.configure(config); } else { // Try another config. } ``` -------------------------------- ### Install Workbox-window via npm Source: https://developer.chrome.google.cn/docs/workbox/modules/workbox-window Instructions for installing the `workbox-window` package as a development dependency using npm. This is the standard approach for projects utilizing JavaScript bundlers like Webpack or Rollup. ```Shell npm install workbox-window ``` -------------------------------- ### 创建 LanguageModel 会话 Source: https://developer.chrome.google.cn/docs/extensions/ai/prompt-api 此 API 文档描述了 LanguageModel.create() 函数,用于创建新的语言模型会话。会话可以根据 topK 和 temperature 进行自定义,也可以通过 initialPrompts 提供初始上下文,或通过 signal 传递 AbortSignal 以控制会话生命周期。 ```APIDOC LanguageModel.create(options?: object) - 创建一个新的语言模型会话。 - 参数: - options (object, 可选): 配置会话的选项对象。 - temperature (number, 可选): 会话的温度值。必须与 topK 同时指定或同时省略。 - topK (number, 可选): 会话的 top-K 值。必须与 temperature 同时指定或同时省略。 - signal (AbortSignal, 可选): 用于销毁会话的 AbortSignal。 - initialPrompts (Array, 可选): 包含初始对话上下文的提示数组。 - role (string): 提示的角色 ('system', 'user', 'assistant')。 - content (string): 提示的内容。 - 返回值 (Promise): 一个表示新创建会话的 Promise。 - 示例: // 自定义会话 const params = await LanguageModel.params(); const slightlyHighTemperatureSession = await LanguageModel.create({ temperature: Math.max(params.defaultTemperature * 1.2, 2.0), topK: params.defaultTopK, }); // 使用 AbortSignal const controller = new AbortController(); stopButton.onclick = () => controller.abort(); const sessionWithSignal = await LanguageModel.create({ signal: controller.signal, }); // 使用初始提示 const sessionWithInitialPrompts = await LanguageModel.create({ initialPrompts: [ { role: 'system', content: 'You are a helpful and friendly assistant.' }, { role: 'user', content: 'What is the capital of Italy?' }, { role: 'assistant', content: 'The capital of Italy is Rome.'}, { role: 'user', content: 'What language is spoken there?' } ] }); ``` -------------------------------- ### Chrome Extension API (MV2) Source: https://developer.chrome.google.cn/docs/extensions/reference/declarativeWebRequest Provides general utility functions for managing the extension itself, such as getting its URL, checking if it's in incognito mode, or getting the background page. ```APIDOC extension - General utility functions for managing the extension. - Methods: getURL, getViews, getBackgroundPage, isAllowedIncognitoAccess, isAllowedFileSchemeAccess, setUpdateUrlData. - Events: onConnect, onConnectExternal, onMessage, onMessageExternal, onRequest, onRequestExternal. ``` -------------------------------- ### Bubblewrap CLI: Initialize Project with Web Manifest Source: https://developer.chrome.google.cn/docs/android/trusted-web-activity/query-parameters This command initializes a new Bubblewrap project, using the provided web manifest URL to set default values. The wizard will prompt for confirmation of the start_url, allowing the developer to append additional parameters. ```CLI bubblewrap init --manifest https://material.money/manifest.json ``` -------------------------------- ### PPB_Graphics2D API Methods and Web API Equivalents Source: https://developer.chrome.google.cn/docs/native-client/migration Documentation for PPB_Graphics2D methods, detailing their mapping to Emscripten and Web API functions, along with specific limitations or behavioral notes for each method. ```APIDOC PPB_Graphics2D Methods: Create: - Emscripten: SDL - Web API: Resource in Canvas.getContext('2d') - Limitations: None specified. Describe: - Emscripten: SDL - Web API: Canvas.clientWidth + Canvas.clientHeight - Limitations: None specified. PaintImageData: - Emscripten: SDL - Web API: CanvasRenderingContext2D.putImageData - Limitations: None specified. Scroll: - Emscripten: GAP - Web API: CanvasRenderingContext2D.scrollIntoView, CanvasRenderingContext2D.drawImage - Limitations: GAP (partial) - Can be achieved by drawing the canvas onto itself with an offset using drawImage, then filling the rest. ReplaceContents: - Emscripten: SDL - Web API: CanvasRenderingContext2D.drawImage - Limitations: None specified. Flush: - Emscripten: GAP - Web API: No direct equivalent - Limitations: GAP (partial) - There will always be an implicit flush at the end of drawing code; this is unlikely to change. However, OffscreenCanvas and ImageBitmapRenderingContext provide similar functionality. SetScale: - Emscripten: SDL - Web API: CanvasRenderingContext2D.scale - Limitations: None specified. GetScale: - Emscripten: SDL - Web API: CanvasRenderingContext2D.currentTransform - Limitations: None specified. SetLayerTransform: - Emscripten: SDL - Web API: CanvasRenderingContext2D.setTransform CanvasRenderingContext2D.scale CanvasRenderingContext2D.translate - Limitations: None specified. ``` -------------------------------- ### Example ID Assertion Endpoint Error Response JSON Source: https://developer.chrome.google.cn/docs/privacy-sandbox/fedcm-developer-guide An example JSON structure for an error response from the ID assertion endpoint, demonstrating the use of the 'code' and 'url' fields within the 'error' object. ```JSON { "error" : { "code": "access_denied", "url" : "https://idp.example/error?type=access_denied" } } ``` -------------------------------- ### messages.json Description Field Examples Source: https://developer.chrome.google.cn/docs/extensions/mv3/i18n-messages Shows examples of the optional 'description' field within `messages.json` entries. This field provides context or details to assist translators in providing the most accurate translation for a given message. ```JSON "description": "Ask for the user's name" ... "description": "Greet the user" ... "description": "Say goodbye to the user" ```