ContentIndex: getAll() 方法

可用性有限

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

實驗性: 這是一項實驗性技術
在生產中使用此技術之前,請仔細檢查瀏覽器相容性表格

注意:此功能在 Web Workers 中可用。

ContentIndex 介面的 getAll() 方法返回一個 Promise,該 Promise 解析為一個可迭代的內容索引條目列表。

語法

js
getAll()

引數

無。

返回值

返回一個 Promise,該 Promise 解析為一個 contentDescription 項的 Array

contentDescription

返回的每一項都是一個 Object,包含以下資料

id

一個唯一的 String 識別符號。

title

項的 String 標題。用於使用者可見的內容列表中。

description

項的 String 描述。用於使用者可見的內容列表中。

url

一個包含相應 HTML 文件 URL 的 String。需要位於當前 service worker 的作用域內。

category 可選

定義內容類別的 String。可以是

  • '' 一個空的 String,這是預設值。
  • homepage
  • article
  • video
  • audio
icons 可選

一個影像資源的 Array,定義為一個 Object,包含以下資料

src

源影像的 URL String

sizes 可選

影像尺寸的 String 表示。

type 可選

影像的 MIME 型別

label 可選

一個代表圖示可訪問名稱的字串。

異常

不會丟擲任何異常。如果內容索引中沒有條目,將返回一個空的 Array

示例

以下示例顯示了一個非同步函式,該函式檢索 內容索引中的條目,並遍歷每個條目,為介面構建一個列表。

js
async function createReadingList() {
  // access our service worker registration
  const registration = await navigator.serviceWorker.ready;

  // get our index entries
  const entries = await registration.index.getAll();

  // create a containing element
  const readingListElem = document.createElement("div");

  // test for entries
  if (entries.length === 0) {
    // if there are no entries, display a message
    const message = document.createElement("p");
    message.innerText =
      "You currently have no articles saved for offline reading.";

    readingListElem.append(message);
  } else {
    // if entries are present, display in a list of links to the content
    const listElem = document.createElement("ul");

    for (const entry of entries) {
      const listItem = document.createElement("li");

      const anchorElem = document.createElement("a");
      anchorElem.innerText = entry.title;
      anchorElem.setAttribute("href", entry.url);

      listElem.append(listItem);
    }

    readingListElem.append(listElem);
  }
}

規範

規範
Content Index
# content-index-getall

瀏覽器相容性

另見