ContentIndex
Ограниченная доступность
Эта функция не относится к Baseline, так как она не работает в некоторых из самых распространённых браузеров.
Экспериментально: Это экспериментальная технология
Перед использованием в производстве внимательно ознакомьтесь со таблицей совместимости браузеров.
Примечание: Эта функция доступна в Web Workers.
Интерфейс ContentIndex API «Индекс содержимого» позволяет разработчикам регистрировать свой автономный контент в браузере.
Свойства экземпляра
Свойства для этого интерфейса отсутствуют.
Методы экземпляра
-
ContentIndex.add()Экспериментально -
Регистрирует элемент в индексе содержимого.
-
ContentIndex.delete()Экспериментально -
Удаляет элемент из текущего индексируемого содержимого.
-
ContentIndex.getAll()Экспериментально -
Возвращает
Promise, который разрешается с итерируемым списком записей индекса содержимого.
Примеры
Обнаружение функции и доступ к интерфейсу
Здесь мы получаем ссылку на ServiceWorkerRegistration, а затем проверяем свойство index, которое дает нам доступ к интерфейсу индекса содержимого.
// reference registration
const registration = await navigator.serviceWorker.ready;
// feature detection
if ("index" in registration) {
// Content Index API functionality
const contentIndex = registration.index;
}
Добавление в индекс содержимого
Здесь мы объявляем элемент в правильном формате и создаём асинхронную функцию, которая использует метод add() для его регистрации в индексе содержимого.
// 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);
}
}
Получение элементов в текущем индексе
В примере ниже показана асинхронная функция, которая получает элементы в индексе содержимого и итерируется по каждой записи, создавая список для интерфейса.
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);
}
}
Удаление индексируемого содержимого
Ниже приведена асинхронная функция, которая удаляет элемент из индекса содержимого.
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);
}
Все вышеперечисленные методы доступны в рамках области действия работника службы. Они доступны через свойство WorkerGlobalScope.self:
// service worker script self.registration.index.add(item); self.registration.index.delete(item.id); const contentIndexItems = self.registration.index.getAll();
Спецификации
| Спецификация |
|---|
| Индекс содержимого # content-index |
Совместимость браузеров
| Рабочие столы | Мобильные устройства | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari на iOS | Samsung Internet | WebView Android | |
ContentIndex |
Нет | Нет | Нет | Нет | Нет | 84 | Нет | 60 | Нет | 14.0 | 84 |
add |
Нет | Нет | Нет | Нет | Нет | 84 | Нет | 60 | Нет | 14.0 | 84 |
delete |
Нет | Нет | Нет | Нет | Нет | 84 | Нет | 60 | Нет | 14.0 | 84 |
getAll |
Нет | Нет | Нет | Нет | Нет | 84 | Нет | 60 | Нет | 14.0 | 84 |
См. также
© 2005–2024 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/ContentIndex