Portals 实操:在 Web 上实现无缝导航

了解拟议的 Portals API 如何改善您的导航用户体验。

Yusuke Utsunomiya
Yusuke Utsunomiya

确保网页快速加载是提供良好用户体验的关键。 但我们经常忽略的一个方面是页面过渡,即用户在页面之间切换时看到的内容。

一项名为 Portals 的新 Web 平台 API 提案旨在通过简化用户在网站中浏览时的体验来帮助解决此问题。

查看 Portals 的实际应用:

使用 Portals 实现无缝嵌入和导航。由 Adam Argyle 创建。

门户可实现的功能

单页应用 (SPA) 可提供良好的过渡效果,但构建起来较为复杂。 多页应用 (MPA) 的构建要简单得多,但页面之间会出现空白屏幕。

Portals 兼具两者的优势:MPA 的低复杂性以及 SPA 的无缝过渡。它们类似于 <iframe>,因为它们允许嵌入,但与 <iframe> 不同的是,它们还具有导航到其内容的功能。

眼见为实:请先看看我们在 2018 年 Chrome 开发者峰会上展示的内容:

在传统导航中,用户必须在空白屏幕前等待,直到浏览器完成目标页面的渲染。 借助 Portals,用户可以体验动画,而 <portal> 会预渲染内容并打造顺畅的导航体验。

在 Portals 出现之前,我们可以使用 <iframe> 呈现另一个网页。我们还可以添加动画,让框架在页面上移动。但 <iframe> 不允许您浏览其内容。Portals 弥补了这一差距,从而实现了有趣的使用场景。

试用门户

通过 about://flags 启用

通过切换实验性标志,在 Chrome 85 及更高版本中试用 Portals:

  • 为同源导航启用 about://flags/#enable-portals 标志。
  • 如需测试跨域导航,请额外启用 about://flags/#enable-portals-cross-origin 标志。

在 Portals 实验的早期阶段,我们还建议您通过设置 --user-data-dir 命令行 flag,为测试使用完全独立的用户数据目录。启用 Portals 后,请在开发者工具中确认您已拥有全新的 HTMLPortalElement。

显示 HTMLPortalElement 的 DevTools 控制台的屏幕截图

实现门户

我们来看一个基本实现示例。

// Create a portal with the wikipedia page, and embed it
// (like an iframe). You can also use the <portal> tag instead.
portal = document.createElement('portal');
portal.src = 'https://en.wikipedia.org/wiki/World_Wide_Web';
portal.style = '...';
document.body.appendChild(portal);

// When the user touches the preview (embedded portal):
// do fancy animation, e.g. expand …
// and finish by doing the actual transition.
// For the sake of simplicity, this snippet will navigate
// on the `onload` event of the Portals element.
portal.addEventListener('load', (evt) => {
   portal.activate();
});

就是这么简单。在开发者工具控制台中试用此代码,维基百科页面应该会打开。

预览门户网站样式演示的 GIF

如果您想构建我们在 Chrome 开发者峰会上展示的内容(其工作方式与上述演示类似),则以下代码段会很有用。

// Adding some styles with transitions
const style = document.createElement('style');
style.innerHTML = `
  portal {
    position:fixed;
    width: 100%;
    height: 100%;
    opacity: 0;
    box-shadow: 0 0 20px 10px #999;
    transform: scale(0.4);
    transform-origin: bottom left;
    bottom: 20px;
    left: 20px;
    animation-name: fade-in;
    animation-duration: 1s;
    animation-delay: 2s;
    animation-fill-mode: forwards;
  }
  .portal-transition {
    transition: transform 0.4s;
  }
  @media (prefers-reduced-motion: reduce) {
    .portal-transition {
      transition: transform 0.001s;
    }
  }
  .portal-reveal {
    transform: scale(1.0) translateX(-20px) translateY(20px);
  }
  @keyframes fade-in {
    0%   { opacity: 0; }
    100% { opacity: 1; }
  }
`;
const portal = document.createElement('portal');
// Let's navigate into the WICG Portals spec page
portal.src = 'https://wicg.github.io/portals/';
// Add a class that defines the transition. Consider using
// `prefers-reduced-motion` media query to control the animation.
// https://developers.google.com/web/updates/2019/03/prefers-reduced-motion
portal.classList.add('portal-transition');
portal.addEventListener('click', (evt) => {
  // Animate the portal once user interacts
  portal.classList.add('portal-reveal');
});
portal.addEventListener('transitionend', (evt) => {
  if (evt.propertyName == 'transform') {
    // Activate the portal once the transition has completed
    portal.activate();
  }
});
document.body.append(style, portal);

此外,您还可以轻松进行功能检测,以便使用 Portals 渐进增强网站。

if ('HTMLPortalElement' in window) {
  // If this is a platform that have Portals...
  const portal = document.createElement('portal');
  ...
}

以下演示展示了 Portals 的效果:

  1. 输入您要预览的网址。
  2. 然后,该页面将作为 <portal> 元素嵌入。
  3. 点击“预览”。
  4. 预览将在动画播放后激活。

GIF:使用 Portals 演示

查看规范

我们正在 Web Incubation Community Group (WICG) 中积极讨论门户规范。如需快速上手,请查看一些关键场景。以下是您需要熟悉的三项重要功能:

  • <portal> 元素:HTML 元素本身。该 API 非常简单。它由 src 属性、activate 函数和消息传递接口 (postMessage) 组成。activate 接受一个可选参数,用于在激活时将数据传递给 <portal>。
  • portalHost 接口:将 portalHost 对象添加到 window 对象。这样,您就可以检查该网页是否作为 <portal> 元素嵌入。它还提供了一个接口,用于向主机发送消息 (postMessage)。
  • PortalActivateEvent 接口:在 <portal> 激活时触发的事件。有一个名为 adoptPredecessor 的实用函数,可用于将上一页检索为 <portal> 元素。这样,您就可以在两个页面之间创建顺畅的导航和组合体验。

我们来看看基本使用模式之外的情况。以下列出了您可以使用 Portals 实现的功能(并非详尽无遗),并附有示例代码。

自定义作为 <portal> 元素嵌入时的样式

// Detect whether this page is hosted in a portal
if (window.portalHost) {
  // Customize the UI when being embedded as a portal
}

<portal> 元素与 portalHost 之间的消息传递

// Send message to the portal element
const portal = document.querySelector('portal');
portal.postMessage({someKey: someValue}, ORIGIN);

// Receive message via window.portalHost
window.portalHost.addEventListener('message', (evt) => {
  const data = evt.data.someKey;
  // handle the event
});

激活 <portal> 元素并接收 portalactivate 事件

// You can optionally add data to the argument of the activate function
portal.activate({data: {somekey: 'somevalue'}});

// The portal content will receive the portalactivate event
// when the activate happens
window.addEventListener('portalactivate', (evt) => {
  // Data available as evt.data
  const data = evt.data;
});

正在检索前置任务

// Listen to the portalactivate event
window.addEventListener('portalactivate', (evt) => {
  // ... and creatively use the predecessor
  const portal = evt.adoptPredecessor();
  document.querySelector('someElm').appendChild(portal);
});

了解您的页面被用作前置页面的情况

// The activate function returns a Promise.
// When the promise resolves, it means that the portal has been activated.
// If this document was adopted by it, then window.portalHost will exist.
portal.activate().then(() => {
  // Check if this document was adopted into a portal element.
  if (window.portalHost) {
    // You can start communicating with the portal element
    // i.e. listen to messages
    window.portalHost.addEventListener('message', (evt) => {
      // handle the event
    });
  }
});

通过结合使用 Portals 支持的所有功能,您可以打造真正出色的用户体验。 例如,下面的演示展示了 Portals 如何在网站和第三方嵌入内容之间实现无缝的用户体验。

用例和方案

希望您喜欢这次简短的 Portals 之旅!我们迫不及待地想看到您的创意。例如,您可能希望开始使用 Portals 进行非普通导航,例如:从商品类别列表页面预渲染畅销商品的页面。

另一个需要了解的重要事项是,Portal 可用于跨域导航,就像 <iframe> 一样。因此,如果您有多个相互交叉引用的网站,也可以使用 Portals 在两个不同的网站之间创建无缝导航。这种跨域用例是 Portals 独有的,甚至可以改善 SPA 的用户体验。

欢迎提供反馈

Chrome 85 及更高版本已支持实验性使用 Portals。社区反馈对于新 API 的设计至关重要,因此请试用并告诉我们您的想法!如果您有任何功能请求或反馈,请前往 WICG GitHub 代码库。