YES, YOUR BROWSER CAN (probably) DO THAT___ A Look At Modern Web APIs You Might Not Know JULIAN BURR @ WEB DIRECTIONS CODE 2024
A presentation at Web Directions Code in June 2024 in Melbourne VIC, Australia by Julian Burr
YES, YOUR BROWSER CAN (probably) DO THAT___ A Look At Modern Web APIs You Might Not Know JULIAN BURR @ WEB DIRECTIONS CODE 2024
Progressive enhancement is a design philosophy that provides a baseline of essential content and functionality to as many users as possible while delivering the best possible experience only to users of the most modern browsers https://developer.mozilla.org/docs/Glossary/Progressive_Enhancement
stopme.io The ultimate SaaS (Stopwatch as a Service) product for everyone
Observe your APP …
01 Resize & Intersection Observer
01 Resize & Intersection Observer const callback = (entries) => { entries.forEach((entry) => { // *.contentBoxSize }); } const observer = new ResizeObserver(callback, options); const el = document.querySelector(“element”); observer.observe(el); https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver
01 Resize & Intersection Observer const callback = (entries) => { entries.forEach((entry) => { // *.isIntersecting // *.intersectionRect // *.intersectionRatio // … }); } const observer = new IntersectionObserver(callback, options); const el = document.querySelector(“element”); observer.observe(el); https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
… And the user’s Device
02 Network Information API
02 Network Information API // Online status let isOnline = navigator.onLine const callback = () => { isOnline = navigator.onLine; } window.addEventlistener(“online”, callback); window.addEventlistener(“offline”, callback); https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine
02 Network Information API let userConnection = navigator.connection; // *.type (e.g. wifi, …) // *.effectiveType (e.g. 2g, 3g, …) // *.downlink // *.downlinkMax // *.rtt // *.saveData const callback = () => { userC onnection = navigator.connection; } navigator.connection .addEventListener(“change”, callb ack); https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API
02 Network Information API
03 Page Visibility API
03 Page Visibility API let isHidden = document.hidden; const callback = () => { isHidden = document.hidden; } document.addEventListener( “visibilitychange”, callback ); https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
03 Page Visibility API
04 Battery Status API
04 Battery Status API const info = await navigator.getBattery(); // *.level // *.charging // *.chargingTime // *.dischargingTime info.addEventListener(“levelchange”, …); info.addEventListener(“chargingchange”, …); // … https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API
04 Battery Status API
Enhance your components
05 Vibration API
05 Vibration API navigator.vibrate(duration); // Patterns // e.g. vibrate for 100ms with 50ms pauses navigator.vibrate([100, 50, 100, 50, 100]); // Stop long vibration or pattern navigate.vibrate(0); https://developer.mozilla.org/en-US/docs/Web/API/Vibration_API
05 Vibration API // SOS in Morse navigator.vibrate([ 100, 30, 100, 30, 100, 30, 200, 30, 200, 30, 200, 30, 100, 30, 100, 30, 100 ]); // Super Mario navigator.vibrate([ 125, 75, 125, 275, 200, 275, 125, 75, 125, 275, 200, 600, 200, 600 ]); // Star Wars navigator.vibrate([ 500, 110, 500, 110, 450, 110, 200, 110, 170, 40, 450, 110, 200, 110, 170, 40, 500 ]); https://gearside.com/custom-vibration-patterns-mobile-devices/
05 Vibration API , s e t a r b i v ! It r a e w Is
06 EyeDropper API
06 EyeDropper API const eyeDropper = new EyeDropper(); document.getElementById(“btn”) .addEventListener(“click”, () => { // Needs to be triggered by user action eyeDr opper.open() .then((result) => { // Returns the selected color // *.sRGBHex }) .catch((e) => { // Catches any errors, including // when the user cancels selection }); }); https://developer.mozilla.org/en-US/docs/Web/API/EyeDropper_API
06 EyeDropper API
Alomost as good as native
07 Web Share API
07 Web Share API const shareData = { title: “../NEW”, text: “Celebrate all things technology”, url: “https://slashnew.tech” files: [imageFile, videoFile] }; document.getElementById(“btn”) .addEventListener(“click”, () => { navigator.share(shareData) .catch((e) => { // Handle any errors }); }); https://developer.mozilla.org/en-US/docs/Web/API/Web_Share_API
07 Web Share API
08 Contact Picker API
08 Contact Picker API const props = [“name”, “email”, “tel”, “icon”]; const opts = { multiple: true }; const contacts = await navigator.contacts .select(props, opts); .catch((e) => { // Handle any errors }); https://developer.mozilla.org/en-US/docs/Web/API/Contact_Picker_API
08 Contact Picker API
09 Web OTP API
09 Web OTP API navigator.credentials .get({ otp: { transport: [“sms”] }, signal: ac.signal, }) .then((otp) => { // *.code }) .catch((e) => { // Handle any errors }); // Format of the SMS so it can be processed // Your verification code is 123456.\n\n // @app.stopme.io #123456 https://developer.mozilla.org/en-US/docs/Web/API/WebOTP_API
09 Web OTP API
09 Web OTP API
Honourable Mentions
Debugging Console Performance Memory
Debugging Console Performance Memory console.log(…); console.assert(…); console.count(…); console.countReset(…); console.dir(…); console.table(…); console.group(…); console.groupCollapsed(…); console.groupEnd(…); console.time(…); console.timeEnd(…); console.trace(…); console.clear(); https://developer.mozilla.org/en-US/docs/Web/API/Console_API
Debugging const time = performance.now(); performance.mark(“start”); performance.mark(“end”, { detail: { … } }); performance.measure(“login”, “start”, “end”); Console Performance Memory const observer = new PerformanceObserver((list, obj) => { list.getEntries().forEach((entry) => { // *.name // *.startTime // *.duration // *.detail }); }); observ er.observe({ type: “res ource” }); https://developer.mozilla.org/en-US/docs/Web/API/Performance
Debugging Console const memory = navigator.deviceMemory; // Device has at least ${memory}GiB of RAM const memorySample = await performance .measureUserAgentSpecificMemory(); // *.bytes // *.breakdown[].bytes // *.breakdown[].attribution // *.breakdown[].types Performance Memory https://developer.mozilla.org/en-US/docs/Web/API/Device_Memory_API
Auth but better Credentials API AUthn API
Auth but better const cred = new PasswordCredential({ id, password, name }); // Store credentials await navigator.credentials.store(cred); Credentials API AUthn API // Get stored credentials const user = await navigator.credentials.get(); // Prevent automatic login when user signs out await navigator .credentials .preventSilentAccess(); https://developer.mozilla.org/en-US/docs/Web/API/Credential_Management_API
Auth but better Credentials API AUthn API // Create credentials object on the client // using challenge generated on the server const registerCredential = await navigator.credentials.create({ publicKey }); // Credentials are stored with the user // identity are sent back and stored on the // server // Authenticate again using server challenge const authCredential = await navigator.credentials.get({ publicKey }); // Use stored public key to verify validity // of auth crendentials https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API
https://webauthn.io/ Auth but better Credentials API AUthn API
The Next GENeration INTL API Temporal* Navigation API
The Next generation INTL API Temporal* Navigation API const o ptions = { dateStyle: “full”, timeSt yle: “long”, timeZone: “ Australia/Sydney” }); new Intl.D ateTimeFormat(“en-US”, options) .format(date); // Friday, December 2, 2022 at 12:21:40 PM // GMT+11 // Relative time const fmt = new Intl.Rela tiveTimeFormat( “en “, { st yle: “narrow” } ); fmt.format(3, “day”); // in 3 days fmt.for mat(-2, “year”); // 2 years ago https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl
The Next generation INTL API Temporal* const au = new Intl.NumberFormat(“en-AU”); au.format(123_456.79); // 123,456.79 const de = new Intl.NumberFormat(“de-DE”); de.format(123_456.79); // 123.456,79 const fmt = new Int l.NumberFormat( “de- DE”, { style: “currency”, currency: “EUR” } ); fmt.f ormat(123_456.79) // 123.456,79 € Navigation API https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl
The Next generation INTL API Temporal* Navigation API // Get exact current system time Temporal.Now.instant(); // Get time zone Temporal.Now.timeZoneId(); // Useful utilities const date = Temporal.PlainDate.from(dateStr); // *.year // *.inLeapYear // *.toString() // … // Manipulate time date.add({ hours: 1 }); https://tc39.es/proposal-temporal/docs/
The Next generation INTL API Temporal* Navigation API // Promises for the win (finally!) await navigation.reload({ info, state }); // Navigate around await navigation.navigate(url, options); await navigation.back(options); await navigation.forward(options); await navigation.traverseTo(key, options); // Events navigation .addEventListener(“currententrychange”); .addEventListener(“navigate”); .addEventListener(“navigatesuccess”); .addEventListener(“navigateerror”); https://developer.mozilla.org/en-US/docs/Web/API/Navigation_API
The Next generation URL Patterns Popover const p = new URLPattern({ pathname: “/foo” }); p.test(“https://example.com/books”)); // true const p = new URLPattern({ pathname: “/books/:id” }); const match = p.exec(“https://example.com/books/123”); // *.pathname.groups.id = 123 const p = new URLPattern( “/books/:id(\d+)”, “https://example.com” ); View Transition https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API
The Next generation URL Patterns Popover <button popovertarget=”mypopover”> Toggle the popover </button> <div id=”mypopover” popover> Popover content </div> document.addEventListener(“keydown”, (e) => { if (e.key === “h”) { mypopover.togglePopover(); } }); View Transition https://developer.mozilla.org/en-US/docs/Web/API/Popover_API
The Next generation function updateView(e) { e.preventDefault(); const details = e.target.closest(“details”); if (!document.startViewTransition) { // Fallback for older browsers details.toggleAttribute(“open”) } URL Patterns Popover document.startViewTransition(() => details.toggleAttribute(“open”) ); } View Transition https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API
Thanks! @jburr90 / julian burr https://www.julianburr.de/ web-directions-code-2024slides.pdf