Chrome 68 的新功能

以及更多功能

我是 Pete LePage。我们来深入了解一下,看看 Chrome 68 为开发者提供了哪些新功能!

想要查看更改的完整列表?查看 Chromium 源代码库变更列表

“添加到主屏幕”更改

如果您的网站符合“添加到主屏幕”条件,Chrome 将不再显示“添加到主屏幕”横幅。完全由您掌控何时以及如何提示用户。

如需提示用户,请监听 beforeinstallprompt 事件,然后保存事件并向应用添加按钮或其他界面元素,以表明该应用可以安装。

let installPromptEvent;

window.addEventListener('beforeinstallprompt', (event) => {
  // Prevent Chrome <= 67 from automatically showing the prompt
  event.preventDefault();
  // Stash the event so it can be triggered later.
  installPromptEvent = event;
  // Update the install UI to notify the user app can be installed
  document.querySelector('#install-button').disabled = false;
});

当用户点击“安装”按钮时,对已保存的 beforeinstallprompt 事件调用 prompt(),然后 Chrome 会显示“添加到主屏幕”对话框。


btnInstall.addEventListener('click', () => {
  // Update the install UI to remove the install button
  document.querySelector('#install-button').disabled = true;
  // Show the modal add to home screen dialog
  installPromptEvent.prompt();
  // Wait for the user to respond to the prompt
  installPromptEvent.userChoice.then(handleInstall);
});

为了让您有时间更新网站,当用户首次访问符合“添加到主屏幕”条件的网站时,Chrome 将显示一个迷你信息栏。关闭后,迷你信息栏在一段时间内将不再显示。

“添加到主屏幕”行为的更改具有完整详细信息,包括您可以使用的代码示例等。

页面生命周期 API

当用户运行大量标签页时,内存、CPU、电池和网络等关键资源可能会超额订阅,从而导致用户体验不佳。

如果您的网站在后台运行,系统可能会暂停运行以节省资源。借助新的 Page Lifecycle API,您现在可以监听和响应这些事件。

例如,如果用户将某个标签页置于后台,浏览器可能会选择在该页面上暂停脚本执行以节省资源。在此之前,它会触发 freeze 事件,以便您关闭打开的 IndexedDB 或网络连接,或保存任何未保存的视图状态。然后,当用户重新聚焦该标签页时,会触发 resume 事件,您可以重新初始化任何已拆除的内容。

const prepareForFreeze = () => {
  // Close any open IndexedDB connections.
  // Release any web locks.
  // Stop timers or polling.
};
const reInitializeApp = () => {
  // Restore IndexedDB connections.
  // Re-acquire any needed web locks.
  // Restart timers or polling.
};
document.addEventListener('freeze', prepareForFreeze);
document.addEventListener('resume', reInitializeApp);

请参阅 Phil 的 Page Lifecycle API 帖子,详细了解更多方面,包括代码示例、提示等。 您可以在 GitHub 上找到相关spec说明文档

Payment Handler API

Payment Request API 是一种基于标准的开放式付款接受方式。Payment Handler API 支持基于网络的付款应用,以直接在付款请求体验中支持付款,从而扩大付款请求的范围。

作为卖家,添加现有的网页版付款应用就像在 supportedMethods 属性中添加一个条目一样简单。

const request = new PaymentRequest([{
  // Your custom payment method identifier comes here
  supportedMethods: 'https://bobpay.xyz/pay'
}], {
  total: {
    label: 'total',
    amount: { value: '10', currency: 'USD' }
  }
});

如果安装了可以处理指定付款方式的 Service Worker,它会显示在付款请求界面中,并且用户可以使用它付款。

Eiji 发布了一篇很棒的博文,其中展示了如何为商家网站和付款处理程序实现此功能。

还有更多其他奖励!

以上只是我们针对开发者在 Chrome 68 中所做的更改的一部分,当然还有许多其他变化。

开发者工具中的新功能

请务必查看 Chrome 开发者工具中的新功能,了解 Chrome 68 中开发者工具的新变化。

订阅

然后,点击 YouTube 频道上的订阅按钮,每当我们发布新视频时,您都会收到电子邮件通知。

我叫 Pete LePage