ContentIndex
注意:此功能在 Web Workers 中可用。
ContentIndex 介面是 Content Index API 的一部分,它允許開發者向瀏覽器註冊支援離線使用的內容。
例項屬性
此介面沒有屬性。
例項方法
ContentIndex.add()實驗性-
向 內容索引 註冊一個條目。
ContentIndex.delete()實驗性-
從當前索引的內容中登出一個條目。
ContentIndex.getAll()實驗性-
返回一個
Promise,該 Promise 解析為一個可迭代的內容索引條目列表。
示例
功能檢測和介面訪問
在這裡,我們獲取對 ServiceWorkerRegistration 的引用,然後檢查 index 屬性,該屬性允許我們訪問內容索引介面。
js
// reference registration
const registration = await navigator.serviceWorker.ready;
// feature detection
if ("index" in registration) {
// Content Index API functionality
const contentIndex = registration.index;
}
新增到內容索引
在這裡,我們宣告一個格式正確的條目,並建立一個非同步函式,該函式使用 add() 方法將其註冊到 內容索引。
js
// our content
const item = {
id: "post-1",
url: "/posts/amet.html",
title: "Amet consectetur adipisicing",
description:
"Repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.",
icons: [
{
src: "/media/dark.png",
sizes: "128x128",
type: "image/png",
},
],
category: "article",
};
// our asynchronous function to add indexed content
async function registerContent(data) {
const registration = await navigator.serviceWorker.ready;
// feature detect Content Index
if (!registration.index) {
return;
}
// register content
try {
await registration.index.add(data);
} catch (e) {
console.log("Failed to register content: ", e.message);
}
}
檢索當前索引中的條目
下面的示例展示了一個非同步函式,該函式檢索 內容索引 中的條目,並迭代每個條目,為介面構建一個列表。
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);
}
}
登出已索引的內容
下面是一個非同步函式,它從 內容索引 中刪除一個條目。
js
async function unregisterContent(article) {
// reference registration
const registration = await navigator.serviceWorker.ready;
// feature detect Content Index
if (!registration.index) return;
// unregister content from index
await registration.index.delete(article.id);
}
以上所有方法都在 service worker 的作用域內可用。它們可以透過 WorkerGlobalScope.self 屬性訪問。
js
// service worker script
self.registration.index.add(item);
self.registration.index.delete(item.id);
const contentIndexItems = self.registration.index.getAll();
規範
| 規範 |
|---|
| Content Index # content-index |
瀏覽器相容性
載入中…