PageSwapEvent

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

PageSwapEvent 事件对象可在 pageswap 事件的处理函数中使用。

当您导航到其他文档时,在前一个文档即将卸载时会触发 pageswap 事件。在跨文档导航期间,PageSwapEvent 事件对象允许您从正在导航离开的文档中操纵相关的 视图过渡(通过访问相关的 ViewTransition 对象),前提是导航触发了视图过渡。它还提供导航类型以及当前和目标文档的信息。

构造函数

PageSwapEvent()

创建一个新的 PageSwapEvent 对象实例。

实例属性

activation 只读

包含一个 NavigationActivation 对象,其中包含同源导航的导航类型以及当前和目标文档的历史条目。如果导航的重定向链中任何位置存在跨源 URL,则返回 null

viewTransition 只读

包含一个 ViewTransition 对象,代表跨文档导航的活动视图过渡。

示例

js
window.addEventListener("pageswap", async (e) => {
  // Only run this if an active view transition exists
  if (e.viewTransition) {
    const currentUrl = e.activation.from?.url
      ? new URL(e.activation.from.url)
      : null;
    const targetUrl = new URL(e.activation.entry.url);

    // Going from profile page to homepage
    // ~> The big img and title are the ones!
    if (isProfilePage(currentUrl) && isHomePage(targetUrl)) {
      // Set view-transition-name values on the elements to animate
      document.querySelector(`#detail main h1`).style.viewTransitionName =
        "name";
      document.querySelector(`#detail main img`).style.viewTransitionName =
        "avatar";

      // Remove view-transition-names after snapshots have been taken
      // Stops naming conflicts resulting from the page state persisting in BFCache
      await e.viewTransition.finished;
      document.querySelector(`#detail main h1`).style.viewTransitionName =
        "none";
      document.querySelector(`#detail main img`).style.viewTransitionName =
        "none";
    }

    // Going to profile page
    // ~> The clicked items are the ones!
    if (isProfilePage(targetUrl)) {
      const profile = extractProfileNameFromUrl(targetUrl);

      // Set view-transition-name values on the elements to animate
      document.querySelector(`#${profile} span`).style.viewTransitionName =
        "name";
      document.querySelector(`#${profile} img`).style.viewTransitionName =
        "avatar";

      // Remove view-transition-names after snapshots have been taken
      // Stops naming conflicts resulting from the page state persisting in BFCache
      await e.viewTransition.finished;
      document.querySelector(`#${profile} span`).style.viewTransitionName =
        "none";
      document.querySelector(`#${profile} img`).style.viewTransitionName =
        "none";
    }
  }
});

注意:请参阅Chrome DevRel 团队成员列表以获取此代码所引用的实时演示。

规范

规范
HTML
# the-pageswapevent-interface

浏览器兼容性

另见