📘
Dev & Ops
Programming
Programming
  • Programming Book
  • Technologies
    • API
      • Известные API
        • Facebook API
      • Проектирование API
        • Программы для проектирования
          • Конвертация между форматами
          • Postman
          • Swagger
        • Webhooks
        • GraphQL
          • Введение
          • Introspection
        • RPC
          • Описание
          • gRPC
          • XML-RPC
          • SOAP
            • About
            • wsdl
          • JSON RPC
        • REST API
        • SAML
      • Program's API
        • Общие понятия
        • DOM API & элементы веб-браузера
        • Известные API
          • Google API
          • Telegram Bot API
      • Получение данных с сервера / AJAX
      • Хранение данных на стороне клиента
        • Подходы
        • Подробнее
          • Web Storage API
          • IndexedDB
          • Service Worker API
          • Cache API
    • WEB
      • Modern Web Application Architecture
      • PWA
      • Стеки технологий
        • JAMstack
        • LAMP
        • MEAN
        • MERN
      • The World Wide Web Consortium (W3C)
    • Архитектура сервисов
      • No-code / Low-code
        • Databases
        • Платформы для запуска и исполнения произвольных процессов и вычислений
        • Генераторы сайтов
      • Архитектурные паттерны
        • Papers
        • Инструменты визуализации и моделирования архитектуры
        • Архитектура проекта
          • Альтернативы
          • Feature-Sliced Design
          • MVC
          • DDD | Domain-Driven Design
          • Clean Architecture
          • Hexagonal
        • Архитектура кода
          • Papers
          • Singleton
          • Retry
          • Circuit Breaker
          • Общение между компонентами
            • Intro
            • Observer
            • PubSub
          • ООП
        • Архитектура систем
          • Monolith
          • API Gateway
          • CQRS
          • Microservices
          • Service Mesh
            • Для чего
            • Kuma
            • Istio
            • Hashicorp Consul
      • Telemetry
        • OpenTelemetry Concepts
        • Metrics
        • Tracing
        • Logs collect
      • Testing
      • Построение админок
      • Cases
      • Брокеры сообщений
        • Why?
        • RabbitMQ
        • RedisMQ
        • AWS SQS
        • Apache Kafka
        • ZeroMQ
        • Apache ActiveMQ
        • IronMQ
      • Автоматизация сборок
        • Makefile
      • Subscriptions
      • Zero Trust
    • Визуализация информации
      • Design/Совместная разработка интерфейсов
      • Работа с данными
      • Схемы, графы, рисунки..
        • Работа с графами
        • Рисуем структуру базы
        • Miro App
        • Рисование детских диаграмм
        • draw.io
        • Xmind
      • Куда заливать видео
      • yEd
      • LaTeX + PGF/TikZ
    • Version Control Systems
      • Git
      • Github
    • Programs
      • Adobe Alternatives
      • Atlassian
        • Jira
        • Confluence
      • Базы данных
        • LevelDB
      • Google Products for Developers
      • Open source
      • Фреймворки
      • vscode
      • Сборка проектов
      • Regular expressions
      • Browsers
    • Библиотеки
      • Полнотекстовой поиск
      • Парсинг грамматик
      • Регулярные выражения
      • Решение практических проблем ML
      • Chrome Cast
    • AI
      • Учимся использовать AI
      • Core Tech
      • Практическое использование
        • Assistants
        • Code assistants
        • Security
        • Web & Design
    • Dev portals
    • Разработка игр
  • Management
    • (draft) Product Management
      • Проработка идеи нового сервиса
      • Построение гипотез
    • Goals management
      • Определения и тезисы
      • OKR
      • KPI
      • OKR vs KPI
  • Programming Languages
    • Learn materials
    • Code Quality
    • Security Coding Styles
    • Testing
      • Integration testing
    • Other non programming languages
      • YAML
      • Proto
      • SQL
        • Create table
        • WITH operator
        • Time sleep
    • Bash
      • Простые операции
        • Работа с файлами
        • Untitled
        • trim
      • Процессы
    • PowerShell
      • IDE
      • Запуск скриптов
      • Удаленный запуск скриптов (with privesc)
      • Копирование файлов и директорий
      • Основы/Описание команд некоторых
      • Papers & Books
      • Примеры
        • Get-Help
        • Скачать файл
        • Импорт модулей и скриптов
        • Создание объекта Credential
        • Пользователи
        • Simple HTTP Server
    • Swift
    • ActionScript
    • Backend
      • Build & Distribution
        • cookiecutter
        • meson
        • Fastlane
        • Maven
        • Gradle
        • Apache Ant
      • JVM
        • Java Env Manager
        • Java
          • Build and Run Simple Script
          • jshell & jrunscript
          • Basic Serialization and Deserialization Java Object
          • Libraries
        • Scala
        • Kotlin
          • Intro
          • Basics
          • Async Programming
          • Логирование
          • Frameworks
            • Kotlin stdlib
            • HTTP
            • Documentation
        • Frameworks
          • Jersey Rest API
          • Spring Framework
            • About
            • Spring Boot AutoConfiguration
            • Spring IoC
            • Spring MVC
            • Spring Boot
            • Other Spring Annotations
          • Struts 2
        • Security
      • JS/TS
        • Lerna
        • Gulp
        • Frameworks
          • Templating libraries
          • Nest.js
          • Fastify
          • Express.js
          • Koa.js
      • Go
        • Get Started
          • Basic
          • Golang документация
          • Golang VSCode IDE
          • GOPATH and GOROOT
          • Сценарии на Go
        • Общее
          • Операторы и встроенные функции
          • Указатели и ссылки
          • Типизация
            • Простые типы
            • Составные типы
            • Пользовательские типы
            • Сокращенное и полное объявление переменной или константы
            • Строки
            • Срезы
            • Работа с типами
          • Коллекции
            • Перечисления
            • Массивы и срезы
            • Отображения
          • Процедурное программирование
            • Ветвления
              • if
              • select
              • switch
            • Циклы
            • Функции и методы
          • ООП
            • Ключевые понятия
            • Интерфейсы
            • Нюансы и ограничения
          • Generics in Go
          • Параллельное программирование
            • go-подпрограммы
            • Каналы обмена данными
            • Проблемы в параллельном программировании и пути их решения
        • Packages
          • Установка пакетов
          • Импортирование локальных пакетов
          • Базовые
            • Списком
            • context
          • Сторонние
            • Общепризнанные
            • Абстракции
            • Микросервисы
              • go-micro
              • gRPC Ecosystem
              • Go kit
                • About
                • Пример
                • Middlewares
                • Общение с другими микросервисами
            • GUI Decktop
            • web
            • Protocols
            • Network
            • FileSystem
            • Files & Databases
            • Testing, Profiling
            • Others
        • Debugging
        • Testing
        • Diagnostics
        • Godoc
        • Books
        • Примеры
          • Hello world
          • Узнать ОС
          • Типы
          • Файлы
          • HTTP-сервер
          • Test HTTP Request
          • RabbitMQ with Go
        • Проблемы
          • _cgo_export.c:3:10: fatal error: 'stdlib.h' file not found
        • Tools Powered on Go
        • Go Security
      • Ruby
        • Use Ruby Env and Deps
        • VSCode Ruby extensions
        • Ruby Language Guide
          • Comments
          • Variables
          • Strings
          • Ranges
          • Arrays
          • Methods
          • Flow Control
          • Classes
          • Dependencies
        • Cases
          • WebSocket Server
        • Frameworks
          • Web: Sinatra
          • Web: Padrino
          • Web: Ruby on Rails
            • Getting Started
            • Routes
            • Controllers
            • Modules
            • Rails Security
              • Common Security Issues
                • Common
                • Deserialisation
                • SQLi
              • Ruby CVEs
              • Security Tools
              • Papers
          • Middleware: Rack
          • Test: RSpec
      • Python
        • Basic
          • Install
          • Enum
          • Collections
          • Operators
          • Reflection
          • Tips
        • Advanced
          • Venv
          • Include Other Languages Libs
          • Время выполнения операции
          • Работа с контекстом
          • Работа с текстом, числами и объектами
          • Работа с файлами и IO
          • Запуск других программ
          • Работа с функциями
          • Работа с классами
          • Работа с итераторами
          • Работа с генераторами
          • Работа с многопоточностью
          • Создание CLI
          • tqdm
          • pydantic
        • Packaging
          • Intro
          • Install packages / Build Frontends
            • pip
            • pipx
            • hatch
            • poetry
          • Организация кода
            • src-layout vs flat-layout
            • namespaces
            • Plugins
          • Конфигурация
            • Papers
            • pyproject.toml
            • setup.py
            • setup.cfg
        • Packages
          • Public Lists of Python Packages
          • Linters
          • True Python
          • Network
          • Web
            • Simple HTTP Server
            • ASGI Python Web Servers
            • Http Client
              • aiohttp
              • requests
              • Packages
            • selenium
            • zeep [SOAP]
          • Web Frameworks
            • Bootle
            • FastAPI
            • Flask
            • Django
              • Intro
              • Django Admin
              • Django Signals
              • Security
            • Tornado
          • Databases
            • boto3
            • Mongo
            • Postgres
            • SQLAlchemy
          • Асинхронная обработка сообщений / работа с очередями
            • Celery
            • Others
          • Обработка информации
            • Работа с графами
            • plist
            • HAR
            • Лингвистика
            • Обработка изображений
            • Parsing HTML
            • Parsing JS
            • Beatifiers
            • XML -> Dictionary
            • Извлечение текста из pdf
            • Санитайзеры
            • Document converter
            • Генерация PDF документов
            • Parse and generate CSS
            • PDF Parser
          • Qt/QML
          • Python script -> binary file
          • Разное
          • Math & Crypto
          • Работа с другими сервисами
          • pwn & re
        • Patterns
          • Singleton
          • Factory
        • Testing
          • Intro
          • Pytest CLI
          • Markers
          • Fixtures
          • Mocking
          • Plugins
          • Configuration
          • Unit tests
        • Errors
        • Papers & Books
        • Python Security
      • .Net
        • dotnet
        • NuGet
        • Интроспекция .Net решения
      • ASP.NET
        • Поднимаем тестовое приложение
        • Структура папок ASP.Net проекта
          • ASP.NET Core
          • ASP.NET MVC
          • Classic ASP.NET WebApp
        • ASPX
          • examples
            • Hello world
        • Security
      • Perl
        • cpan
      • PHP
        • Getting Started
        • Basic
        • Magic Methods
        • Examples
          • Phar
          • Работа с файлами
          • Usefull small examples
          • Поднять инфру для разработки
          • Simple page with GET param
        • Packages
        • Frameworks
          • Yii
          • Laravel
            • Intro
            • Getting Started
            • Docker
            • Pentest
          • Zend
          • Symfony
          • CodeIgniter
          • Moodle
        • Libraries
        • Security
      • C/C++
        • Security
        • IDE
        • Build
          • Compilers
            • GCC
            • MinGW
            • Clang
            • MSVC
          • cmake
        • Cases
          • Как подключить .Lib/.h статическую библиотеку в свой проект VS/C/C++
          • Disable stdafx and other features in VS
          • Если не компилируются стандартные библиотеки в Visual Studio 2015
    • Frontend
      • Инструменты
      • HTML
        • Введение
        • Примеры
          • iframe
          • Страница со ссылкой
          • Сворачиваемый блок кода
          • Перейти на другую страницу по нажатии кнопки
          • Элементы, которые могут содержать ссылки
          • GET-запрос
          • Форматирование: оборачивание входного текста в блок (например при чтении локально файла или кода)
          • Random Color для всех элементов
        • Papers & Notes
      • CSS
        • Basic
        • Селекторы
          • О селекторах
          • Наследование стилей
          • Объявление и приоритеты
          • Псевдоклассы
        • CSS Свойства
          • Цвет
          • Шрифты и типографика
          • Стилизация абзацев
          • Блочная модель и отступы
          • Строчные и блочно-строчные элементы
          • Размеры элементов
          • Тени
          • Прокрутка элементов
          • Rotation
        • CSS Processors
        • Переменные
        • Браузерные стили
        • Стратегии верстки
          • Блочная и табличная верстки
          • Блочная верстка
          • Flexbox верстка
          • Grid Layout верстка
        • Frameworks
          • Gravity UI
          • Material Design
          • Materialize
          • Bootstrap
        • Советы
        • Papers
      • JS/TS
        • JavaScript
          • About
          • Basic JS
          • Async JS
          • RxJs
          • Guide
            • Proxy
            • Reflect
          • Cases
            • Борьба с CORS и Local File Read в браузере
            • Корректно нормализируем пути в JS
            • Тестирование работы с медленными ответами (slow js http response)
            • JSessionID
            • RCE
            • Замер времени отработки запроса
            • Периодические операции
            • postMessage
            • Самый простой редирект на странице
            • HTTP запросы и обработка ответов из JS
            • Использование сторонних скриптов
            • Отображение результатов списком
        • TypeScript
          • Init
          • Типы
            • Abstract classes, interfaces and types
            • Базовые типы и создание своих типов
            • Создание объектов
            • Создание сложных типов: Interfaces
            • Enums
            • Null Safe
            • Работа со строками и массивами
          • Ветвление кода и циклы
          • Фукнции и классы
            • Functions
            • Classes
          • Guards (проверка типов)
          • Generic-типы
          • Декораторы
          • Namespaces
          • Модули
          • Вспомогательные операторы
          • Дополнительные инструменты
          • Разные соглашения
        • Libraries
        • Frameworks
          • Web
            • React
              • Getting Started
              • Deploy
              • Packages
              • Security
              • Frameworks
                • Next.js
                • Remix
                • Gatsby
            • Vue.js
              • Nuxt.js
            • Angular
              • About
              • Основы фреймворка
                • Get Started
                • Angular CLI
                • Basic
                • Material Design Support
                • Components
                  • Introduction
                  • Lifecycle
                  • Create components
                  • Component Interaction
                  • Content Projection
                  • Dynamic components
                  • Angular Elements
                • Templates
                  • Text interpolation
                  • Template statements
                  • Pipes
                • Directives
                • Routing
                • Работа с сервисами
              • Packages
                • Списком
                • NgRx
                  • About
              • Cases
                • RxJs WebSockets
                • Errors
                • Code Styles And Best Practices
                • Примеры сайтов на Angular
            • SvelteJS
            • Others
              • jQuery
              • Meteor
              • AngularJS
              • Ext JS / Sencha
          • Mobile & Desktop
            • ReactNative
              • npx/react-native cli
            • Electron.js
          • State Managers
          • Rendering
          • i18n: Format.JS
        • Packet Managers
        • JS Runtime
          • Node.js
          • Deno
        • Other projects
      • CMS
      • Особенности WebStorm IDE
      • Dart/Flutter
        • About
        • Install
        • Packages & Plugins
        • Build & Run
        • Patterns
        • Dart
          • Intro
          • Variables
          • Functions
          • Operators
          • Control flow statements
          • Exceptions
          • Classes
          • Generics
          • Libraries and visibility
          • Asynchrony support
          • Generators
          • Isolates
          • Typedef
          • Packages
        • Flutter
          • Flutter CLI
          • pubspec.yaml
          • Widgets
          • Codelabs
          • Packages
          • Distribution
        • Dart & Flutter Playground
        • Кто использует Flutter
        • Papers & Tutorials
      • Сборщик JS/TS приложений
        • TODO: Webpack
        • TODO: Parcel
        • TODO: Rollup
      • Компиляторы
        • Babel
      • Testing
      • Learning
  • Others
    • Licenses
    • Фотостоки
    • Как оформить свой Github
    • Правила версионирования
    • Правила оформления коммитов
    • Стили именования переменных и классов
    • Language for IoT dev — TOIT
    • Online IDE
    • Документация по API по разным языкам в одном месте
    • Скиллы как специалиста
      • RoadMap для разных направлений
      • Задачи на программирование
      • Алгоритмы
      • Разработчик
      • Web-разработчик
      • DevOps
      • Бумажная ИБ
      • Компании ИБ
Powered by GitBook
On this page
  • About
  • Создадим базу и таблицу
  • Добавляем данные
  • Отображение данных из базы
  • Удаление данных
  1. Technologies
  2. API
  3. Хранение данных на стороне клиента
  4. Подробнее

IndexedDB

PreviousWeb Storage APINextService Worker API

Last updated 4 years ago

About

(иногда сокращают до IDB) это полная база данных, доступная в браузере, в которой вы можете хранить сложные связанные данные, типы которых не ограничиваются простыми значениями, такими как строки или числа.

Вы можете сохранить видео, фото, и почти все остальные файлы с IndexedDB.

Однако это обходится дорого: IndexedDB гораздо сложнее в использовании, чем Web Storage API.

Создадим базу и таблицу

// Create an instance of a db object for us to store the open database in
let db;
window.onload = function() {
    // Open our database; it is created if it doesn't already exist
    // (see onupgradeneeded below)
    let request = window.indexedDB.open('notes', 1);
    
    // onerror handler signifies that the database didn't open successfully
    request.onerror = function() {
      console.log('Database failed to open');
    };
    
    // onsuccess handler signifies that the database opened successfully
    request.onsuccess = function() {
      console.log('Database opened successfully');
    
      // Store the opened database object in the db variable. This is used a lot below
      db = request.result;
    
      // Run the displayData() function to display the notes already in the IDB
      displayData();
    };
    
    // Setup the database tables if this has not already been done
    request.onupgradeneeded = function(e) {
      // Grab a reference to the opened database
      let db = e.target.result;
    
      // Create an objectStore to store our notes in (basically like a single table)
      // including a auto-incrementing key
      let objectStore = db.createObjectStore('notes', { keyPath: 'id', autoIncrement:true });
    
      // Define what data items the objectStore will contain
      objectStore.createIndex('title', 'title', { unique: false });
      objectStore.createIndex('body', 'body', { unique: false });
    
      console.log('Database setup complete');
    };
};

Добавляем данные

// Create an onsubmit handler so that when the form is submitted the addData() function is run
form.onsubmit = addData;

// Define the addData() function
function addData(e) { // e Event
  // prevent default - we don't want the form to submit in the conventional way
  e.preventDefault();

  // grab the values entered into the form fields and store them in an object ready for being inserted into the DB
  let newItem = { title: titleInput.value, body: bodyInput.value };

  // open a read/write db transaction, ready for adding the data
  let transaction = db.transaction(['notes'], 'readwrite');

  // call an object store that's already been added to the database
  let objectStore = transaction.objectStore('notes');

  // Make a request to add our newItem object to the object store
  var request = objectStore.add(newItem);
  request.onsuccess = function() {
    // Clear the form, ready for adding the next entry
    titleInput.value = '';
    bodyInput.value = '';
  };

  // Report on the success of the transaction completing, when everything is done
  transaction.oncomplete = function() {
    console.log('Transaction completed: database modification finished.');

    // update the display of data to show the newly added item, by running displayData() again.
    displayData();
  };

  transaction.onerror = function() {
    console.log('Transaction not opened due to error');
  };
}

Отображение данных из базы

// Define the displayData() function
function displayData() {
  // Here we empty the contents of the list element each time the display is updated
  // If you ddn't do this, you'd get duplicates listed each time a new note is added
  while (list.firstChild) {
    list.removeChild(list.firstChild);
  }

  // Open our object store and then get a cursor - which iterates through all the
  // different data items in the store
  let objectStore = db.transaction('notes').objectStore('notes');
  objectStore.openCursor().onsuccess = function(e) {
    // Get a reference to the cursor
    let cursor = e.target.result;

    // If there is still another data item to iterate through, keep running this code
    if(cursor) {
      // Create a list item, h3, and p to put each data item inside when displaying it
      // structure the HTML fragment, and append it inside the list
      let listItem = document.createElement('li');
      let h3 = document.createElement('h3');
      let para = document.createElement('p');

      listItem.appendChild(h3);
      listItem.appendChild(para);
      list.appendChild(listItem);

      // Put the data from the cursor inside the h3 and para
      h3.textContent = cursor.value.title;
      para.textContent = cursor.value.body;

      // Store the ID of the data item inside an attribute on the listItem, so we know
      // which item it corresponds to. This will be useful later when we want to delete items
      listItem.setAttribute('data-note-id', cursor.value.id);

      // Create a button and place it inside each listItem
      let deleteBtn = document.createElement('button');
      listItem.appendChild(deleteBtn);
      deleteBtn.textContent = 'Delete';

      // Set an event handler so that when the button is clicked, the deleteItem()
      // function is run
      deleteBtn.onclick = function(e) {
        deleteItem(e);
      };

      // Iterate to the next item in the cursor
      cursor.continue();
    } else {
      // Again, if list item is empty, display a 'No notes stored' message
      if(!list.firstChild) {
        let listItem = document.createElement('li');
        listItem.textContent = 'No notes stored.'
        list.appendChild(listItem);
      }
      // if there are no more cursor items to iterate through, say so
      console.log('Notes all displayed');
    }
  };
}

Удаление данных

// Define the deleteItem() function
function deleteItem(e) {
  // retrieve the name of the task we want to delete. We need
  // to convert it to a number before trying it use it with IDB; IDB key
  // values are type-sensitive.
  let noteId = Number(e.target.parentNode.getAttribute('data-note-id'));

  // open a database transaction and delete the task, finding it using the id we retrieved above
  let transaction = db.transaction(['notes'], 'readwrite');
  let objectStore = transaction.objectStore('notes');
  let request = objectStore.delete(noteId);

  // report that the data item has been deleted
  transaction.oncomplete = function() {
    // delete the parent of the button
    // which is the list item, so it is no longer displayed
    e.target.parentNode.parentNode.removeChild(e.target.parentNode);
    console.log('Note ' + noteId + ' deleted.');

    // Again, if list item is empty, display a 'No notes stored' message
    if(!list.firstChild) {
      let listItem = document.createElement('li');
      listItem.textContent = 'No notes stored.';
      list.appendChild(listItem);
    }
  };
}
IndexedDB API