2019年谷歌开发者大会之Web的新功能

写在前面

2019年谷歌开发者大会 —— 实现适用于Web新功能 的半小时演讲中,Thomas Steiner介绍了一些Chrome已经发布和即将支持的新API。这些新增的API使得web app可以实现一些native app的功能,并同时坚持保护用户的安全性、隐私、信任及其余 web 核心原则。前端

Through our capabilities project, we want to make it possible for web apps to do anything native apps can, by exposing the capabilities of native platforms to the web platform, while maintaining user security, privacy, trust, and other core tenets of the web. (developers.google.com/web/updates…)git

注:这些 API 有三种状态:github

  • 已发布
  • Available as an origin trial:试验阶段,能够经过申请对应 API 的token,选择性得应用于本身的 web 中 (Origin Trials Guide)
  • Behind a flag:须要手动开启 Chrome 中对应 API 的 flag (Chrome Flag)

Async Clipboard API (images)

状态:Chrome 76 发布web

做用:支持对于图片的复制粘贴json

  • 复制

首先得到 Blob 对象格式的图片,而后将 ClipboardItem 这个对象做为数组项传入新的异步方法 navigator.clipboard.write() 中。目前只支持一次传递一张图片,将来会支持多张图片。api

try {
  const imgURL = 'https://developers.google.com/web/updates/images/generic/file.png';
  const data = await fetch(imgURL);
  const blob = await data.blob();
  await navigator.clipboard.write([
    new ClipboardItem(Object.defineProperty({}, blob.type, {
      value: blob,
      enumerable: true
    }))
  ]);
  console.log('Image copied.');
} catch(e) {
  console.error(e, e.message);
}
复制代码
  • 粘贴

经过 navigator.clipboard.read() 方法可得到一个由 clipboardItem 组成的数组。因为这些方法都是异步的,此处建议建议用 for ... of 循环 image 数组。数组

async function getClipboardContents() {
  try {
    const clipboardItems = await navigator.clipboard.read();
    for (const clipboardItem of clipboardItems) {
      try {
        for (const type of clipboardItem.types) {
          const blob = await clipboardItem.getType(type);
          console.log(URL.createObjectURL(blob));
        }
      } catch (e) {
        console.error(e, e.message);
      }
    }
  } catch (e) {
    console.error(e, e.message);
  }
}
复制代码
  • 自定义粘贴和复制动做

能够经过监听 paste 事件自定义粘贴动做。注意要先preventDefault()浏览器

document.addEventListener('paste', async (e) => {
  e.preventDefault();
  getClipboardContents();
});
复制代码

一样的,经过监听 copy 事件能够自定义粘贴动做,此事件包含一个 clipboardData 的属性,能够从中获取剪贴板中的数据。安全

document.addEventListener('copy', async (e) => {
  e.preventDefault();
  try {
    for (const item of e.clipboardData.items) {
      await navigator.clipboard.write([
        new ClipboardItem(Object.defineProperty({}, item.type, {
          value: item,
          enumerable: true
        }))
      ]);
    }
    console.log('Image copied.');
  } catch(e) {
    console.error(e, e.message);
  }
});
复制代码

Contact Picker API

状态:Available as an origin trial for Androidapp

做用:使用户能够在 web app 中打开通信录,分享指定的内容给选中的联系人

一个使 web app 更接近于 native app 的 API。经过 navigator.contacts.select() 这个异步方法打开通信录列表,此方法包含两个参数:props,提早设定好的想要返回的属性数组;option,是否能够选择多个联系人的对象。

const props = ['name', 'email', 'tel'];
const opts = {multiple: true};

try {
  const contacts = await navigator.contacts.select(props, opts);
  handleResults(contacts);
} catch (ex) {
  // Handle any errors here.
}
复制代码

此 API 的返回值为一个由联系人属性对象组成的数组。

[{
  "email": [],
  "name": ["Queen O'Hearts"],
  "tel": ["+1-206-555-1000", "+1-206-555-1111"]
}]
复制代码

Badging for App Icons

状态:Available as an origin trial

做用:在 web app 的图标上显示消息提醒

示例图片

相比于发送推送通知,在 PWA 的图标上静默显示通知是更接近于原生应用的体验。尽管如此,Chrome 仍然建议不要根据 web app 的安装状态调用此 API,由于Badgin API 能够应用于任何浏览器但愿显示标记的地方,因此不须要预设此 API 的做用条件。若是环境不支持,标记就不会显示。

设置/清除标记能够经过 window.ExperimentalBadge 对象,它有两个方法 set([number])clear() 分别用于设置指定数目的标记,和清除标记。

// In a web page
const unreadCount = 24;
window.ExperimentalBadge.set(unreadCount);
复制代码

Web Share and Web Share Target API

状态:Launched

做用:使 web app 能够向其余 app 分享文件

分享文件

仍然是一个改善 PWA 用户体验使其更接近于原生应用的 API。经过 navigator.canShare() 方法判断分享的文件是否能够分享以及获取分享数据。

目前支持分享的文件为 Image, video, audio 以及文本文件,将来会提供更多类型文件的支持。

if (navigator.canShare && navigator.canShare( { files: filesArray } )) {
  navigator.share({
    files: filesArray,
    title: 'Vacation Pictures',
    text: 'Barb\nHere are the pictures from our vacation.\n\nJoe',
  })
  .then(() => console.log('Share was successful.'))
  .catch((error) => console.log('Sharing failed', error));
} else {
  console.log('Your system doesn\'t support sharing files.');
}
复制代码

此外能够经过 Web Share Target API 将你的 PWA 注册为能够被分享的目标,之前只有原生应用才能够被分享。注册方式为在你的 manifest.json 中添加一个 share_traget 对象,

"share_target": {
  "action": "/share-target/",
  "method": "GET",
  "enctype": "application/x-www-form-urlencoded",
  "params": {
    "title": "title",
    "text": "text",
    "url": "url"
  }
}
复制代码

其中的 params 能够自定义为你已有的 share URL scheme,method 默认为 GET,也可将它设为 POST

当你的 web app 被指定分享某个文件而且 methodGET 时,浏览器会在 action 指定的 URL 中打开一个新窗口,并带上 params 中指定的一系列参数。

window.addEventListener('DOMContentLoaded', () => {
  const parsedUrl = new URL(window.location);
  // searchParams.get() will properly handle decoding the values.
  console.log('Title shared: ' + parsedUrl.searchParams.get('title'));
  console.log('Text shared: ' + parsedUrl.searchParams.get('text'));
  console.log('URL shared: ' + parsedUrl.searchParams.get('url'));
});
复制代码

Native File System API

状态:Behind a flag

做用:PWA 能够读写本地文件系统了!

仍然是一个使 PWA 更像原生应用的 API。用户授予权限后,web app 经过此 API 能够即时读写用户设备上的本地文件,方法为 window.chooseFileSystemEntries()。默认只可选取一个文件,能够经过设置参数使其选取多个文件。

let fileHandle;
butOpenFile.addEventListener('click', async (e) => {
  fileHandle = await window.chooseFileSystemEntries();
  // Do something with the file handle
});
复制代码

fileHandle 为调用此 API 的回调,它包含各类和文件互动的属性和方法。好比读取文件。

const file = await fileHandle.getFile();
const contents = await file.text();
复制代码

须要建立文件时,向 window.chooseFileSystemEntries() 中传入一个配置参数便可。

function getNewFileHandle() {
  const opts = {
    type: 'saveFile',
    accepts: [{
      description: 'Text file',
      extensions: ['txt'],
      mimeTypes: ['text/plain'],
    }],
  };
  const handle = window.chooseFileSystemEntries(opts);
  return handle;
}
复制代码

打开文件目录枚举文件的写法为,在此 API 中传入一个 openDirectory 参数。

const butDir = document.getElementById('butDirectory');
butDir.addEventListener('click', async (e) => {
  const opts = {type: 'openDirectory'};
  const handle = await window.chooseFileSystemEntries(opts);
  const entries = await handle.getEntries();
  for await (const entry of entries) {
    const kind = entry.isFile ? 'File' : 'Directory';
    console.log(kind, entry.name);
  }
});
复制代码

写在后面

Google 团队在致力于弥合 PWA 和原生应用之间的间隙,力图拓展 web app 的边界使其尽量地提供原生应用的用户体验,例如他们还新提出了 Barcode Detection API(识别二维码),短信/本地通知 push 等试验性功能。由此,在移动端开发各个框架的 PK 及大前端浩荡的潮流中, PWA 能够利用其支持全部平台,日益完善的 web api 以及较少开发成本等优点在轻量应用的开发中占据更重要的位置。

P.S 上述 API 主要参考自 Goole developer 官网 ,若是有理解错误的地方麻烦评论告诉我啊

P.P.S 此次大会听过以后以为 Flutter 很好用的样子!

相关文章
相关标签/搜索