samples
A repo containing samples tied to new functionality in each release of Google Chrome.
Top Related Projects
Code examples that accompany various MDN DOM and Web API documentation pages
A series of web components examples, related to the MDN web components documentation at https://developer.mozilla.org/en-US/docs/Web/Web_Components.
Test suites for Web platform specs — including WHATWG, W3C, and others
HTML Standard
Web Components specifications
A suite of polyfills supporting the HTML Web Components specs
Quick Overview
GoogleChrome/samples is a GitHub repository containing a collection of small, focused samples demonstrating various features and APIs available in Google Chrome. These samples serve as practical examples and reference implementations for web developers looking to leverage Chrome's capabilities in their projects.
Pros
- Wide range of topics covered, including Web APIs, Chrome Extensions, and Progressive Web Apps
- Regularly updated to reflect the latest Chrome features and best practices
- Well-organized structure with clear documentation for each sample
- Provides a valuable learning resource for both beginners and experienced developers
Cons
- Some samples may become outdated as Chrome evolves rapidly
- Not all samples are equally maintained or documented
- May not cover every possible use case or edge case for each feature
- Focused primarily on Chrome, which may limit applicability to other browsers
Code Examples
Here are a few short code examples from different samples in the repository:
- Using the Web Bluetooth API to connect to a device:
navigator.bluetooth.requestDevice({ filters: [{ services: ['battery_service'] }] })
.then(device => device.gatt.connect())
.then(server => server.getPrimaryService('battery_service'))
.then(service => service.getCharacteristic('battery_level'))
.then(characteristic => characteristic.readValue())
.then(value => {
console.log(`Battery percentage is ${value.getUint8(0)}`);
})
.catch(error => { console.error(error); });
- Implementing a basic service worker for offline functionality:
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open('v1').then((cache) => {
return cache.addAll([
'/',
'/styles/main.css',
'/script/main.js'
]);
})
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
})
);
});
- Using the Intersection Observer API for lazy loading images:
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const image = entry.target;
image.src = image.dataset.src;
observer.unobserve(image);
}
});
});
document.querySelectorAll('img[data-src]').forEach((img) => {
observer.observe(img);
});
Getting Started
To get started with GoogleChrome/samples:
-
Clone the repository:
git clone https://github.com/GoogleChrome/samples.git
-
Navigate to the desired sample directory:
cd samples/[feature-name]
-
Open the
index.html
file in Google Chrome to see the sample in action. -
Explore the source code to understand how the feature is implemented.
Competitor Comparisons
Code examples that accompany various MDN DOM and Web API documentation pages
Pros of dom-examples
- More comprehensive coverage of DOM APIs and features
- Better organized with clear categorization of examples
- Regularly updated with new web platform features
Cons of dom-examples
- Less focus on cutting-edge Chrome-specific features
- Fewer examples related to Progressive Web Apps (PWAs)
Code Comparison
dom-examples (IndexedDB example):
const dbName = "MyTestDatabase";
const request = indexedDB.open(dbName, 2);
request.onerror = (event) => {
console.error("Database error: " + event.target.error);
};
samples (Service Worker example):
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
console.log('Service Worker registered with scope:', registration.scope);
}).catch(function(error) {
console.log('Service Worker registration failed:', error);
});
}
Summary
dom-examples provides a wider range of DOM-related examples and is well-organized, making it an excellent resource for learning web APIs. samples focuses more on Chrome-specific features and emerging web technologies. Both repositories offer valuable examples for web developers, with dom-examples being more suitable for general DOM manipulation and samples being better for exploring cutting-edge Chrome features and PWAs.
A series of web components examples, related to the MDN web components documentation at https://developer.mozilla.org/en-US/docs/Web/Web_Components.
Pros of web-components-examples
- Focused specifically on Web Components, providing a comprehensive set of examples
- Well-documented with detailed explanations for each example
- Maintained by MDN, ensuring high-quality and up-to-date content
Cons of web-components-examples
- Limited scope compared to samples, which covers a broader range of web technologies
- Fewer examples overall, as it's focused solely on Web Components
- May not include cutting-edge or experimental features as quickly as samples
Code Comparison
web-components-examples:
<template id="element-details-template">
<details>
<summary>
<span>
<code class="name"><<slot name="element-name">NEED NAME</slot>></code>
<i class="desc"><slot name="description">NEED DESCRIPTION</slot></i>
</span>
</summary>
<div class="attributes">
<h4>Attributes</h4>
<slot name="attributes"><p>None</p></slot>
</div>
</details>
</template>
samples:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then(function(registration) {
console.log('Service Worker registered with scope:', registration.scope);
}).catch(function(error) {
console.log('Service Worker registration failed:', error);
});
}
Test suites for Web platform specs — including WHATWG, W3C, and others
Pros of wpt
- Comprehensive test suite covering a wide range of web platform features
- Collaborative effort with contributions from multiple browser vendors and web developers
- Regularly updated to reflect the latest web standards and specifications
Cons of wpt
- More complex setup and execution process compared to simpler sample repositories
- Requires more technical knowledge to understand and contribute to the test suite
- May be overwhelming for developers looking for quick, specific examples
Code Comparison
samples:
function showNotification() {
Notification.requestPermission().then((result) => {
if (result === 'granted') {
new Notification('Hello World!');
}
});
}
wpt:
test(() => {
assert_true('Notification' in self, 'Notification API supported');
assert_equals(typeof Notification.requestPermission, 'function', 'requestPermission is a function');
assert_equals(typeof Notification.permission, 'string', 'permission is a string');
}, 'Notification API basic functionality');
The samples repository provides practical, ready-to-use code examples, while wpt focuses on comprehensive testing of web platform features. samples is more suitable for developers looking for quick implementation references, whereas wpt is essential for ensuring cross-browser compatibility and adherence to web standards.
HTML Standard
Pros of html
- Comprehensive documentation of HTML standard
- Collaborative effort with contributions from multiple organizations
- Regularly updated to reflect the latest HTML specifications
Cons of html
- Focuses solely on HTML specification, lacking practical examples
- May be overwhelming for beginners due to its technical nature
- Less frequent updates compared to samples
Code Comparison
html:
<section>
<h1>Example Heading</h1>
<p>This is a paragraph in the HTML specification.</p>
</section>
samples:
<div class="example">
<h2>Chrome API Demo</h2>
<button id="startDemo">Start Demo</button>
<script src="demo.js"></script>
</div>
Summary
The html repository serves as the official source for HTML specifications, offering comprehensive documentation for web developers and browser implementers. It provides a collaborative platform for discussing and evolving the HTML standard.
In contrast, the samples repository focuses on practical examples and demonstrations of various web technologies, particularly those related to Chrome and its APIs. It offers a more hands-on approach for developers looking to implement specific features or learn through code examples.
While html is essential for understanding the core HTML language, samples is more suitable for developers seeking practical implementations and real-world usage of web technologies in Chrome.
Web Components specifications
Pros of webcomponents
- Focuses specifically on Web Components, providing a comprehensive resource for this technology
- Includes polyfills and libraries to support broader browser compatibility
- Offers more in-depth documentation and examples for Web Components implementation
Cons of webcomponents
- Limited scope compared to samples, which covers a wider range of web technologies
- May not be as frequently updated as samples, which is maintained by the Chrome team
- Less diverse set of examples and use cases for general web development
Code Comparison
samples:
navigator.serviceWorker.register('service-worker.js')
.then(function(registration) {
console.log('Service Worker registered successfully.');
}).catch(function(error) {
console.log('Service Worker registration failed:', error);
});
webcomponents:
class MyElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `<p>Hello, Web Components!</p>`;
}
}
customElements.define('my-element', MyElement);
A suite of polyfills supporting the HTML Web Components specs
Pros of webcomponentsjs
- Focused specifically on Web Components polyfills and utilities
- More comprehensive support for Web Components across browsers
- Actively maintained with regular updates
Cons of webcomponentsjs
- Limited to Web Components technology
- Less diverse range of examples and use cases
- Steeper learning curve for beginners
Code Comparison
webcomponentsjs:
import '@webcomponents/webcomponentsjs/webcomponents-loader.js';
class MyElement extends HTMLElement {
connectedCallback() {
this.innerHTML = '<p>Hello, Web Components!</p>';
}
}
customElements.define('my-element', MyElement);
samples:
// No equivalent code sample as samples covers a wide range of Chrome features
// and doesn't focus specifically on Web Components
Summary
webcomponentsjs is a specialized library for Web Components support, offering comprehensive polyfills and utilities. It's ideal for projects heavily focused on Web Components but may have a steeper learning curve.
samples provides a broader range of examples for various Chrome features, making it more suitable for developers exploring different Chrome capabilities. However, it lacks the depth of Web Components support found in webcomponentsjs.
Choose webcomponentsjs for dedicated Web Components projects, and samples for exploring diverse Chrome features and APIs.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Google Chrome Samples
Samples tied to new functionality in Google Chrome.
Each sample corresponds to an entry in https://www.chromestatus.com/features, and using that interface is currently the best way to browse.
Contributing Samples
Please use SAMPLE_STARTING_POINT
as a starting point.
While it's possible to simply create a standard set of HTML/JS/CSS files within the new directory, you can take advantage of the Jekyll-based templating system to handle most of the boilerplate. Any files that start with a front matter block will be templated, and any other files will be served verbatim.
If you're still unsure, two canonical samples that use templates are:
Follow the Using Jekyll with Pages guide to mimic the production Jekyll environment during local development.
Once complete, please file a pull request against the gh-pages
branch with your sample.
It's ideal when filing a pull request @-mention the relevant engineer who worked on adding the
feature into Chrome, to solicit their feedback and ensure that the sample properly describes
the functionality. The email address of the engineer who worked on a given feature can be found in
the corresponding https://www.chromestatus.com/features entry. If you're unsure of the GitHub
username corresponding to the engineer, an alternative is to email them a link to the pull request
and ask for feedback directly.
Style / Linting / CI
The samples ideally should follow the Google JavaScript Style Guide,
and that's enforced via ESLint, using the eslint-config-google
base configuration, with a few overrides as needed.
Linting can be performed via npm run lint
(make sure to npm install
first).
Various IDEs offer real-time ESLint integration, and using those integrations that can help avoid errors before anything gets checked in.
Travis CI is currently being used to verify that the Jekyll build completes successfully and that linting passes without errors.
Top Related Projects
Code examples that accompany various MDN DOM and Web API documentation pages
A series of web components examples, related to the MDN web components documentation at https://developer.mozilla.org/en-US/docs/Web/Web_Components.
Test suites for Web platform specs — including WHATWG, W3C, and others
HTML Standard
Web Components specifications
A suite of polyfills supporting the HTML Web Components specs
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot