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

浏览器兼容性

另见