Window:pageswap 事件

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

當你在文件之間導航且上一個文件即將解除安裝時,會觸發 pageswap 事件。

這對於跨文件(MPA)檢視過渡很有用,可以從導航的出站頁面操作活動的過渡。例如,你可能希望跳過過渡,或者透過 JavaScript 自定義出站過渡動畫。

它還提供了對導航型別以及當前和目標文件歷史條目的訪問。

語法

在諸如 addEventListener() 之類的方法中使用事件名稱,或設定事件處理程式屬性。

js
addEventListener("pageswap", (event) => { })

onpageswap = (event) => { }

事件型別

一個 PageSwapEvent。繼承自 Event

Event PageSwapEvent

事件屬性

PageSwapEvent.activation 只讀

返回一個 NavigationActivation 物件,其中包含同源導航的導航型別以及當前和目標文件歷史條目。如果導航在重定向鏈中的任何位置包含跨域 URL,則返回 null

PageSwapEvent.viewTransition 只讀

如果事件觸發時有活動的入站跨文件檢視過渡,則返回表示該過渡的 ViewTransition 物件。如果不是這種情況,則返回 null

示例

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
# 事件 - pageswap

瀏覽器相容性

另見