### Basic PWA Setup with Manifest and Service Worker Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/learn/pwa/getting-started/index.md This snippet outlines the initial steps for creating an installable PWA. It involves setting up a basic manifest file for installability and a simple service worker to enable offline functionality by caching critical assets like CSS and JavaScript. ```html ``` ```javascript /* sw.js */ self.addEventListener('install', function(event) { event.waitUntil( caches.open('v1').then(function(cache) { return cache.addAll([ '/', '/styles.css', '/script.js' ]); }) ); }); self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request) .then(function(response) { if (response) { return response; } return fetch(event.request); }) ); }); ``` -------------------------------- ### Lighthouse CI Setup Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/pt/blog/lighthouse-whats-new-6.0/index.md Provides guidance on setting up Lighthouse CI in a project. It mentions support for various CI providers and the availability of Docker images for easier deployment. Users are directed to a getting started guide for detailed instructions. ```bash Follow our [getting started guide](https://github.com/GoogleChrome/lighthouse-ci/blob/master/docs/getting-started.md). ``` -------------------------------- ### PWA Installability Guide Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/es/progressive-web-apps/pwa-checklist/index.md Provides guidance on how to make a PWA installable, test for installability, and implement the installation process. This section links to a more detailed guide. ```html You can follow our [installation guide](/customize-install/) to learn how to make your PWA installable, how to test that it is installable, and try to do it yourself. ``` -------------------------------- ### Web.dev Components Guide Reference Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/handbook/quick-start/index.md This is a reference to the guide on web.dev that details the available UI components for making content more engaging. It links to the specific guide. ```html web.dev components ``` -------------------------------- ### Developer.chrome.com Components Guide Reference Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/handbook/quick-start/index.md This is a reference to the guide on developer.chrome.com that details the available UI components for making content more engaging. It links to the specific guide. ```html developer.chrome.com components ``` -------------------------------- ### Create a New Collection JSON File Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/handbook/quick-start/index.md Example of creating a new collection file for organizing content into learning paths. The file should be named `.json` and placed in the `site/_data/paths` directory. ```json { "title": "i18n.paths.newpathname.title", "description": "i18n.paths.newpathname.description", "overview": "i18n.paths.newpathname.overview", "topic_titles": [ "i18n.paths.newpathname.topic1", "i18n.paths.newpathname.topic2" ] } ``` -------------------------------- ### Web.dev Markup Section Reference Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/handbook/quick-start/index.md This is a reference to the section on web.dev that explains how to format markdown content correctly. It links to further guides on components. ```html web.dev markup section ``` -------------------------------- ### Desktop PWA Installation Example Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/learn/pwa/progressive-web-apps/index.md Illustrates the process of installing a PWA on a desktop computer via a browser, showcasing the standalone window experience. This is a descriptive reference to a video. ```html {% Video src="video/RK2djpBgopg9kzCyJbUSjhEGmnw1/d0cR0VyUhy30DkXEgGOt.mp4", alt="the user can install a PWA from the browser on a desktop computer, and then the user can access it like any other app with its standalone window", autoplay="true", loop="true", muted="true" %} ``` -------------------------------- ### PWA Store Submission Guides Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/learn/pwa/installation/index.md This section provides links to guides on submitting PWAs to specific stores like Google Play, Microsoft Store, and Apple App Store. ```markdown - [List your Progressive Web App in Google Play](https://chromeos.dev/en/publish/pwa-in-play) - [Submit your PWA to the Microsoft Store](https://docs.microsoft.com/en-us/windows/uwp/publish/pwa/overview) - [Publishing a PWA to App Store](https://firt.dev/pwa-stores/) - [WebKit: App-Bound Domains](https://webkit.org/blog/10882/app-bound-domains/) ``` -------------------------------- ### Writable Stream Example Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/streams/index.md A comprehensive example demonstrating the lifecycle of a writable stream, including start, write, close, and abort operations. It shows how to create a stream, get a writer, write chunks, and manage the stream's state. ```javascript const writableStream = new WritableStream({ start(controller) { console.log('[start]'); }, async write(chunk, controller) { console.log('[write]', chunk); // Wait for next write. await new Promise((resolve) => setTimeout(() => { document.body.textContent += chunk; resolve(); }, 1_000)); }, close(controller) { console.log('[close]'); }, abort(reason) { console.log('[abort]', reason); }, }); const writer = writableStream.getWriter(); const start = Date.now(); for (const char of 'abcdefghijklmnopqrstuvwxyz') { // Wait to add to the write queue. await writer.ready; console.log('[ready]', Date.now() - start, 'ms'); // The Promise is resolved after the write finishes. writer.write(char); } await writer.close(); ``` -------------------------------- ### JavaScript Example: Fetching Installed Related Apps Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/get-installed-related-apps/index.md This JavaScript snippet demonstrates how to use the Get Installed Related Apps API to retrieve a list of related installed applications and log them to the console. ```javascript async function getAndLogRelatedApps() { if ('getInstalledRelatedApps' in navigator) { try { const relatedApps = await navigator.getInstalledRelatedApps(); console.log('Found related apps:', relatedApps); relatedApps.forEach(app => { console.log(`- App ID: ${app.id}, Platform: ${app.platform}, URL: ${app.url}`); }); } catch (error) { console.error('Failed to get installed related apps:', error); } } else { console.log('getInstalledRelatedApps API not supported in this browser.'); } } getAndLogRelatedApps(); ``` -------------------------------- ### kbone CLI Project Initialization and Building Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/mini-apps/mini-app-open-source-projects/index.md Demonstrates how to initialize a new kbone project using the CLI, navigate into the project directory, and build the mini app, web app, and production web app. This is useful for setting up a new project or understanding the build process. ```bash npx kbone-cli init my-app cd my-app npm run mp npm run web npm run build ``` -------------------------------- ### WritableStream Full Code Example Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/ko/blog/streams/index.md A comprehensive example demonstrating the complete lifecycle of a WritableStream, including start, write, close, and abort methods, along with writer operations and logging. ```javascript const writableStream = new WritableStream({ start(controller) { console.log('[start]'); }, async write(chunk, controller) { console.log('[write]', chunk); // Wait for next write. await new Promise((resolve) => setTimeout(() => { document.body.textContent += chunk; resolve(); }, 1_000)); }, close(controller) { console.log('[close]'); }, abort(reason) { console.log('[abort]', reason); }, }); const writer = writableStream.getWriter(); const start = Date.now(); for (const char of 'abcdefghijklmnopqrstuvwxyz') { // Wait to add to the write queue. await writer.ready; console.log('[ready]', Date.now() - start, 'ms'); // The Promise is resolved after the write finishes. writer.write(char); } await writer.close(); ``` -------------------------------- ### TransformStream Constructor Example Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/streams/index.md Demonstrates the basic structure of creating a TransformStream with `start`, `transform`, and `flush` methods. ```javascript const transformStream = new TransformStream({ start(controller) { /* Initialize stream, enqueue prefix chunks */ }, transform(chunk, controller) { /* Transform incoming chunk and enqueue output */ }, flush(controller) { /* Enqueue suffix chunks before closing */ }, }); ``` -------------------------------- ### Run Thumbor with Debug Logging Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/install-thumbor/index.md Starts the Thumbor server with debug logging enabled, which can be useful for troubleshooting during setup. ```bash thumbor --log-level debug ``` -------------------------------- ### getUserMedia API Example Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/webrtc-basics/index.md Demonstrates how to capture audio and video streams using the getUserMedia API. This is a fundamental step for WebRTC applications. ```javascript navigator.mediaDevices.getUserMedia({ audio: true, video: true }).then(function(stream) { // Handle the stream (e.g., display in a video element) var videoElement = document.querySelector('video'); videoElement.srcObject = stream; }).catch(function(err) { console.error('Error accessing media devices.', err); }); ``` -------------------------------- ### Web.dev Content Template Reference Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/handbook/quick-start/index.md This is a placeholder reference to the content template used for drafting blog posts on web.dev. The actual template is a file that should be copied. ```html content template ``` -------------------------------- ### Lógica condicional para la experiencia del usuario Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/es/progressive-web-apps/define-install-strategy/index.md Ejemplo de cómo utilizar la información de la memoria del dispositivo para mostrar diferentes elementos de interfaz de usuario o banners de instalación. ```javascript if (isDeviceMidOrLowEnd()) { // Mostrar el banner de instalación para "Lite app" o el mensaje PWA A2HS } else { // Mostrar el banner de instalación la "app de insignia" } ``` -------------------------------- ### Video.js CDN Usage Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/media/media-frameworks/index.md Demonstrates the basic setup of Video.js using its free CDN version provided by Fastly. This is the easiest way to get started with the player. ```html ``` -------------------------------- ### Create RTCPeerConnection and Add Stream Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/webrtc-basics/index.md Demonstrates the initial setup of an RTCPeerConnection object and how to add a local media stream to it. This is a fundamental step in establishing a WebRTC connection. ```js pc1 = new RTCPeerConnection(servers); // ... localStream.getTracks().forEach((track) => { pc1.addTrack(track, localStream); }); ``` -------------------------------- ### Run React Application Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/react/get-started-optimize-react/index.md Shows the commands to navigate into the newly created React application directory and start the development server. This allows you to see your React app running in the browser. ```bash cd new-app npm start ``` -------------------------------- ### Get Installed Related Apps API Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/ru/progressive-web-apps/app-like-pwas/index.md Allows a web application to check if a related native application is installed on the user's device. This is useful for guiding users towards native app experiences or avoiding redundant prompts. ```javascript navigator.getInstalledRelatedApps().then(relatedApps => { if (relatedApps.length > 0) { console.log('Related apps are installed:', relatedApps); // Optionally, prompt user to use the native app } }).catch(error => { console.error('Error checking related apps:', error); }); // See: https://developer.chrome.com/docs/get-installed-related-apps/ ``` -------------------------------- ### Get Device Memory with JavaScript Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/progressive-web-apps/define-install-strategy/index.md Retrieves the device memory and categorizes it as 'lite' or 'full'. This is a basic example of using device information to tailor user experience. ```javascript const deviceCategory = req.get('Device-Memory') < 1 ? 'lite' : 'full'; ``` -------------------------------- ### Add Collection Content to i18n Directory Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/handbook/quick-start/index.md Example of adding translated content for a new collection to the `site/_data/i18n/paths` directory under the 'en' key. This allows for internationalization of collection details. ```json { "en": { "newpathname": { "title": "My New Collection Title", "description": "A description for my new collection.", "overview": "An overview of the learning path.", "topic1": "Topic One Title", "topic2": "Topic Two Title" } } } ``` -------------------------------- ### RTCPeerConnection API Example Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/webrtc-basics/index.md Illustrates the basic usage of the RTCPeerConnection API for establishing peer-to-peer connections. This involves creating an RTCPeerConnection object and handling ICE candidates and session descriptions. ```javascript var peerConnection = new RTCPeerConnection(); // Add stream tracks to the connection // peerConnection.addTrack(stream.getAudioTracks()[0], stream); // peerConnection.addTrack(stream.getVideoTracks()[0], stream); // Handle ICE candidates peerConnection.onicecandidate = function(event) { if (event.candidate) { // Send candidate to the other peer } }; // Handle remote stream peerConnection.ontrack = function(event) { var remoteVideo = document.querySelector('#remoteVideo'); remoteVideo.srcObject = event.streams[0]; }; ``` -------------------------------- ### Include Partial for Course Index Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/handbook/content-types/example-course/index.md Shows how to include a Nunjucks partial file to automatically generate the course index and sidebar navigation. ```njk {% include 'partials/course-index.njk' %} ``` -------------------------------- ### Create New Content Proposal (web.dev) Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/handbook/quick-start/index.md This is the URL to use when submitting a new content proposal for web.dev if you do not have access to a Googler. It pre-fills the issue template with relevant information. ```markdown https://github.com/GoogleChrome/web.dev/issues/new?template=propose-new-content.md ``` -------------------------------- ### Selecting Video Resolution with getUserMedia Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/webrtc-basics/index.md Demonstrates how to use constraints with getUserMedia to request a specific video resolution. This example highlights the process of setting resolution constraints and handling potential errors. ```javascript const constraints = { video: { width: { ideal: 1280 }, height: { ideal: 720 } } }; navigator.mediaDevices.getUserMedia(constraints) .then(function(stream) { // Use the stream }) .catch(function(err) { console.error('Error accessing media devices.', err); }); ``` -------------------------------- ### Obtener información del dispositivo con JavaScript Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/es/progressive-web-apps/define-install-strategy/index.md Utiliza las APIs de JavaScript navigator.hardwareConcurrency, navigator.deviceMemory y navigator.connection para obtener información sobre la CPU, la memoria y el estado de la red de un dispositivo. Esto permite categorizar los dispositivos y adaptar la experiencia del usuario. ```javascript const deviceCategory = req.get('Device-Memory') < 1 ? 'lite' : 'full'; ``` -------------------------------- ### Cross-fading Setup with GainNodes Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/webaudio-intro/index.md Demonstrates setting up an audio graph for cross-fading between two sounds. Each sound source is connected through its own AudioGainNode, allowing independent volume control for fading in and out. ```js function createSource(buffer) { var source = context.createBufferSource(); // Create a gain node. var gainNode = context.createGainNode(); source.buffer = buffer; // Turn on looping. source.loop = true; // Connect source to gain. source.connect(gainNode); // Connect gain to destination. gainNode.connect(context.destination); return { source: source, gainNode: gainNode }; } ``` -------------------------------- ### PWA Installation Criteria and Promotion Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/learn/pwa/installation/index.md This section lists resources related to PWA installation criteria, WebAPKs on Android, and patterns for promoting PWA installation. ```markdown - [What does it take to be installable](/install-criteria/) - [WebAPKs on Android](/webapks/) - [Patterns for promoting PWA installation](/promote-install/) - [Using a PWA in your Android app](/using-a-pwa-in-your-android-app/) ``` -------------------------------- ### Start webpkgserver Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/fast/signed-exchanges-webpackager/index.md Starts the webpkgserver executable. Successful startup is indicated by log messages showing the listening address, OCSP status, and cache directory. ```shell ./webpkgserver ``` -------------------------------- ### Get Installed Related Apps API Reference Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/get-installed-related-apps/index.md This section details the Get Installed Related Apps API, including its methods, parameters, and return values. It covers how to query for related installed applications and the data returned. ```APIDOC GetInstalledRelatedApps(): Promise Description: Returns a list of installed applications that are related to the current web application. Parameters: None Returns: Promise: A promise that resolves to an array of RelatedApp objects. RelatedApp: id: string - The unique identifier of the related application. platform: string - The platform of the related application (e.g., 'windows', 'android'). url: string - The URL to launch the related application. version?: string - The version of the related application (optional). degreeToLaunch?: number - The degree to which the app can be launched (optional). Example Usage: async function logRelatedApps() { try { const relatedApps = await navigator.getInstalledRelatedApps(); console.log('Related Apps:', relatedApps); } catch (error) { console.error('Error fetching related apps:', error); } } ``` -------------------------------- ### HTTP Request Example Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/user-preference-media-features-headers/index.md Demonstrates a basic HTTP GET request to a server. ```bash GET / HTTP/2 Host: example.com ``` -------------------------------- ### RTCDataChannel API Example Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/webrtc-basics/index.md Demonstrates the basic usage of the RTCDataChannel API for sending and receiving data between two peers. It shows how to create a data channel, send messages, and handle incoming messages. ```js const localConnection = new RTCPeerConnection(servers); const remoteConnection = new RTCPeerConnection(servers); const sendChannel = localConnection.createDataChannel('sendDataChannel'); // ... remoteConnection.ondatachannel = (event) => { receiveChannel = event.channel; receiveChannel.onmessage = onReceiveMessage; receiveChannel.onopen = onReceiveChannelStateChange; receiveChannel.onclose = onReceiveChannelStateChange; }; function onReceiveMessage(event) { document.querySelector("textarea#send").value = event.data; } document.querySelector("button#send").onclick = () => { var data = document.querySelector("textarea#send").value; sendChannel.send(data); }; ``` -------------------------------- ### Web Component Examples Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/web-components/index.md HowTo-Components are provided as a teaching aid to demonstrate Custom Element and Shadow DOM best practices, mapping suggestions to practical implementations. ```html

Examples

HowTo-Components are a set of elements which demonstrate Custom Element and Shadow DOM best practices. These elements are not intended to be used in production, but are instead presented as a teaching aide to help map best practice suggestions to actual implementations.

Learn more ``` -------------------------------- ### BufferLoader Example Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/webaudio-intro/index.md Demonstrates how to use a BufferLoader class to load multiple audio files asynchronously and play them back simultaneously once loaded. This is useful for pre-loading sound assets in applications. ```js window.onload = init; var context; var bufferLoader; function init() { context = new AudioContext(); bufferLoader = new BufferLoader( context, [ '../sounds/hyper-reality/br-jam-loop.wav', '../sounds/hyper-reality/laughter.wav', ], finishedLoading ); bufferLoader.load(); } function finishedLoading(bufferList) { // Create two sources and play them both together. var source1 = context.createBufferSource(); var source2 = context.createBufferSource(); source1.buffer = bufferList[0]; source2.buffer = bufferList[1]; source1.connect(context.destination); source2.connect(context.destination); source1.noteOn(0); source2.noteOn(0); } ``` -------------------------------- ### Obtendo informações do dispositivo com JavaScript Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/pt/progressive-web-apps/define-install-strategy/index.md Este snippet demonstra como usar APIs JavaScript como navigator.hardwareConcurrency, navigator.deviceMemory e navigator.connection para obter informações sobre a CPU, memória e status da rede de um dispositivo. Essas informações podem ser usadas para categorizar dispositivos e adaptar a experiência do usuário. ```javascript const deviceCategory = req.get('Device-Memory') < 1 ? 'lite' : 'full'; ``` -------------------------------- ### Chrome DevTools Network Panel Usage Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/performance-audit-tools/index.md Instructions on using the Chrome DevTools network panel for performance auditing, including getting started guides and saving profile data. ```html Get Started Guide save profile data disable the browser cache clear Cache API storage ``` -------------------------------- ### Handling PWA Installation Prompt Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/learn/pwa/installation-prompt/index.md This JavaScript code snippet demonstrates how to capture the `beforeinstallprompt` event, display a custom install UI, and handle the user's choice (accepted or dismissed). It also shows how to reset the deferred prompt after use. ```js installButton.addEventListener('click', async () => { // deferredPrompt is a global variable we've been using in the sample to capture the `beforeinstallevent` deferredPrompt.prompt(); // Find out whether the user confirmed the installation or not const { outcome } = await deferredPrompt.userChoice; // The deferredPrompt can only be used once. deferredPrompt = null; // Act on the user's choice if (outcome === 'accepted') { console.log('User accepted the install prompt.'); } else if (outcome === 'dismissed') { console.log('User dismissed the install prompt'); } }); ``` -------------------------------- ### Usability Review Examples Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/handbook/reviews/index.md Examples of content that should undergo usability reviews, including codelabs, tooling guides, and API guides. These examples illustrate the practical application of the review process. ```html

Codelabs like [Configure HTTP caching behavior](/codelab-http-cache/)

Tooling guides like [Replace animated GIFs with video](/replace-gifs-with-videos/)

API guides like [Getting started with Trust Tokens](/trust-tokens/)

``` -------------------------------- ### webpkgserver Successful Startup Logs Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/fast/signed-exchanges-webpackager/index.md Example log messages indicating a successful startup of the webpkgserver, including the listening address, OCSP retrieval status, and cache directory. ```shell Listening at 127.0.0.1:8080 Successfully retrieved valid OCSP. Writing to cache in /private/tmp/webpkg ``` -------------------------------- ### Start Local Development Server Source: https://github.com/googlechrome/web.dev/blob/main/README.md Starts a local development server to preview the website. Changes to assets will trigger automatic rebuilds. Access the site at http://localhost:8080/. ```bash npm run dev ``` -------------------------------- ### CSS circle() shape with positioned center Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/shapes-getting-started/index.md This example shows how to position the center of the `circle()` shape using coordinates. Here, the center is set to the origin (0 0) of the element's coordinate system. ```css .element{ shape-outside: circle(50% at 0 0); } ``` -------------------------------- ### JavaScript Setup for Convolution Kernel Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/webgl-fundamentals/index.md This JavaScript code demonstrates how to get the uniform location for the kernel array in GLSL and how to set its values. It shows an example of an edge detection kernel and passing it to the shader using `gl.uniform1fv`. ```javascript var kernelLocation = gl.getUniformLocation(program, "u_kernel[0]"); var edgeDetectKernel = [ -1, -1, -1, -1, 8, -1, -1, -1, -1 ]; gl.uniform1fv(kernelLocation, edgeDetectKernel); ``` -------------------------------- ### インストールボタンのクリックを処理する Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/ja/progressive-web-apps/codelab-make-installable/index.md このコードは、インストールボタンのクリックイベントを処理し、保存された `beforeinstallprompt` イベントで `prompt()` を呼び出してインストールプロンプトを表示します。また、プロンプトの結果をログに記録し、インストールボタンを非表示にします。 ```js butInstall.addEventListener('click', async () => { console.log('👍', 'butInstall-clicked'); const promptEvent = window.deferredPrompt; if (!promptEvent) { // デファーされたプロンプトは使用できません。 return; } // インストールプロンプトを表示する。 promptEvent.prompt(); // 結果をログに記録する const result = await promptEvent.userChoice; console.log('👍', 'userChoice', result); // デファーされたプロンプトの変数をリセット。 // prompt() は1回しか呼び出せません。 window.deferredPrompt = null; // インストールボタンを非表示にする。 divInstall.classList.toggle('hidden', true); }); ``` -------------------------------- ### Triggering PWA Installation Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/progressive-web-apps/promote-install/index.md This snippet demonstrates how to trigger the PWA installation flow. It involves listening for the `beforeinstallprompt` event and then showing a UI element (like a button) that, when clicked, displays the install prompt. This is a core mechanism for custom PWA installation experiences. ```javascript let deferredPrompt; window.addEventListener('beforeinstallprompt', (e) => { // Prevent Chrome 67 and earlier from automatically showing the prompt e.preventDefault(); // Stash the event so it can be triggered later. deferredPrompt = e; // Update UI to notify the user they can add to home screen // For example, add a "Install" button to your web app's UI. showInstallButton(); }); async function installPWA() { // Show the prompt deferredPrompt.prompt(); // Wait for the user to respond to the prompt const { outcome } = await deferredPrompt.userChoice; // Optionally, send the result to analytics console.log(`User response to the install prompt: ${outcome}`); // We've used the prompt, and may not need it again. If the user has // dismissed the prompt, then deferredPrompt will be null. deferredPrompt = null; } function showInstallButton() { // Logic to display an install button or other UI element // For example: const installButton = document.getElementById('install-button'); if (installButton) { installButton.style.display = 'block'; installButton.addEventListener('click', installPWA); } } ``` -------------------------------- ### Three.js Scene Setup Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/three-intro/index.md Initializes a WebGL renderer, a perspective camera, and a scene using the Three.js library. It sets up basic scene dimensions, camera attributes, and attaches the renderer's output to a DOM element. ```js var WIDTH = 400, HEIGHT = 300; var VIEW_ANGLE = 45, ASPECT = WIDTH / HEIGHT, NEAR = 0.1, FAR = 10000; var $container = $('#container'); var renderer = new THREE.WebGLRenderer(); var camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR ); var scene = new THREE.Scene(); camera.position.z = 300; renderer.setSize(WIDTH, HEIGHT); $container.append(renderer.domElement); ``` -------------------------------- ### Animating Polygon Shape Outside Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/shapes-getting-started/index.md Illustrates animating a `polygon()` shape with CSS transitions. This example transitions a rectangle shape to a triangle shape by adjusting the vertices, ensuring the same number of vertices are used in both states. ```css .element{ /* four vertices (looks like rectangle) */ shape-outside: polygon(0 0, 100% 0, 100% 100%, 0 100%); transition: shape-outside 1s; } .element:hover{ /* four vertices, but second and third overlap (looks like triangle) */ shape-outside: polygon(0 0, 100% 50%, 100% 50%, 0 100%); } ``` -------------------------------- ### App Shortcuts Example Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/learn/pwa/installation/index.md Shows how to define contextual menus for PWA icons using the App Shortcuts feature in the Web App Manifest. This allows users to quickly access common actions within the PWA directly from the icon. ```json { "name": "My PWA", "icons": [ { "src": "/icons/icon-192x192.png", "sizes": "192x192", "type": "image/png" } ], "shortcuts": [ { "name": "New Note", "short_name": "New Note", "url": "/new-note", "icons": [ { "src": "/icons/new-note-icon.png", "sizes": "192x192", "type": "image/png" } ] } ] } ``` -------------------------------- ### Lighthouse CI Docker Setup Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/lighthouse-evolution-cds-2019/index.md This snippet provides information on setting up the Lighthouse CI server using a Docker image for instant deployment. It links to a recipe for a Docker server setup, indicating a streamlined approach to getting Lighthouse CI running. ```html You can install the Lighthouse CI server on-premise or use a [docker image for instant setup](https://github.com/GoogleChrome/lighthouse-ci/blob/master/docs/recipes/docker-server/README.md). ``` -------------------------------- ### CSS Shape Margin Example Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/shapes-getting-started/index.md Demonstrates the use of `shape-outside` with a circle and `shape-margin` to create spacing around the shape. The `shape-margin` property adds space around the defined shape, influencing how content flows. ```css .element{ shape-outside: circle(40%); shape-margin: 1em; float: left; } ``` -------------------------------- ### Animating Circle Shape Outside Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/shapes-getting-started/index.md Shows how to animate the `shape-outside` property for a circle using CSS transitions. This example transitions the circle's radius from 30% to 50% on hover, creating a visual animation. ```css .element{ shape-outside: circle(30%); transition: shape-outside 1s; float: left; } .element:hover{ shape-outside: circle(50%); } ``` -------------------------------- ### Escuchar el evento beforeinstallprompt Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/es/progressive-web-apps/codelab-make-installable/index.md Este código agrega un manejador de eventos al objeto `window` para el evento `beforeinstallprompt`. Cuando se activa, evita la barra de información mini, almacena el evento para su uso posterior y muestra un botón de instalación al usuario. ```js window.addEventListener('beforeinstallprompt', (event) => { // Prevent the mini-infobar from appearing on mobile. event.preventDefault(); console.log('👍', 'beforeinstallprompt', event); // Stash the event so it can be triggered later. window.deferredPrompt = event; // Remove the 'hidden' class from the install button container. divInstall.classList.toggle('hidden', false); }); ``` -------------------------------- ### 인앱 설치 흐름 시작 Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/ko/progressive-web-apps/customize-install/index.md 사용자가 앱을 설치하기 위해 클릭할 수 있는 버튼 또는 기타 인터페이스 요소를 제공합니다. 요소를 클릭하면 저장된 `beforeinstallprompt` 이벤트(`deferredPrompt` 변수에 저장됨)에서 `prompt()`를 호출하여 사용자에게 PWA를 설치할지 확인하는 모달 설치 대화 상자를 표시합니다. ```js buttonInstall.addEventListener('click', async () => { // Hide the app provided install promotion hideInstallPromotion(); // Show the install prompt deferredPrompt.prompt(); // Wait for the user to respond to the prompt const { outcome } = await deferredPrompt.userChoice; // Optionally, send analytics event with outcome of user choice console.log(`User response to the install prompt: ${outcome}`); // We've used the prompt, and can't use it again, throw it away deferredPrompt = null; }); ``` -------------------------------- ### Basic CSS circle() shape Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/shapes-getting-started/index.md This example demonstrates how to use the `circle()` function with `shape-outside` to create a circular path for content wrapping. The radius is set to 50%, making it responsive to the element's dimensions. ```css .element{ shape-outside: circle(50%); width: 300px; height: 300px; float: left; } ``` -------------------------------- ### Dynamic Server-Side Hints - Blog Route Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/migrate-to-ua-ch/index.md Example of response headers for a '/blog' route, specifying a set of Client Hints. ```text Accept-CH: Sec-CH-UA-Mobile, Sec-CH-UA-Platform, Sec-CH-UA ``` -------------------------------- ### Create and Configure Low-Pass Filter Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/webaudio-intro/index.md This snippet demonstrates how to create a BiquadFilterNode, connect it within an audio graph, set its type to low-pass, and define the cutoff frequency. It's a fundamental example of applying a filter effect. ```js var context = new AudioContext(); var source = context.createBufferSource(); // Assume source is already created and has audio data // Create the filter var filter = context.createBiquadFilter(); // Create the audio graph. source.connect(filter); filter.connect(context.destination); // Create and specify parameters for the low-pass filter. filter.type = 0; // Low-pass filter. See BiquadFilterNode docs filter.frequency.value = 440; // Set cutoff to 440 HZ // Playback the sound. source.start(0); ``` -------------------------------- ### Copy webpkgserver.example.toml Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/fast/signed-exchanges-webpackager/index.md Copies the example webpkgserver.toml file to a new file named webpkgserver.toml, which will be used for configuration. ```shell cp ./webpkgserver.example.toml ./webpkgserver.toml ``` -------------------------------- ### Manejar el evento beforeinstallprompt para la instalación en la aplicación Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/es/progressive-web-apps/customize-install/index.md Este snippet muestra cómo manejar el evento `beforeinstallprompt` para permitir a los usuarios instalar la PWA. Captura la elección del usuario después de que se muestra el prompt de instalación y limpia la variable `deferredPrompt`. ```js buttonInstall.addEventListener('click', async () => { // Esconde la información promotora de la instalación hideInstallPromotion(); // Muestre el mensaje de instalación deferredPrompt.prompt(); // Espera a que el usuario responda al mensaje const { outcome } = await deferredPrompt.userChoice; // De manera opcional, envía analíticos del resultado que eligió el usuario console.log(`User response to the install prompt: ${outcome}`); // Como ya usamos el mensaje, no lo podemos usar de nuevo, este es descartado deferredPrompt = null; }); ```