Best JavaScript code snippet using wpt
sw_cached_site.js
Source:sw_cached_site.js
1// Cache2const cacheName = 'v2.95';3// Index DB4const INDEX_DB_NAME = 'ceneats_form';5const OBJSTORE_POST_REQ_NAME = 'post_requests';6let form_data;7function createIndexDB() {8 let indexedDBOpenRequest = indexedDB.open(INDEX_DB_NAME, 1);9 indexedDBOpenRequest.onerror = function (error) {10 // error creating db11 console.error('IndexedDB error:', error)12 }13 indexedDBOpenRequest.onupgradeneeded = function () {14 // This should only executes if there's a need to 15 // create/update db.16 this.result.createObjectStore(OBJSTORE_POST_REQ_NAME, {17 autoIncrement: true, keyPath: 'id'18 })19 }20 // This will execute each time the database is opened.21 indexedDBOpenRequest.onsuccess = function () {22 console.log('index db success inited...');23 }24}25function deletePostRequests(post_msg_id) {26 let indexedDBOpenRequest = indexedDB.open(INDEX_DB_NAME, 1);27 indexedDBOpenRequest.onsuccess = function(event) {28 let indexdb = this.result;29 let indexT = indexdb.transaction(OBJSTORE_POST_REQ_NAME,'readwrite');30 let indexO = indexT.objectStore(OBJSTORE_POST_REQ_NAME);31 indexO.delete(post_msg_id);32 }33}34function savePostRequests(url, payload) {35 let indexedDBOpenRequest = indexedDB.open(INDEX_DB_NAME, 1);36 indexedDBOpenRequest.onsuccess = function(event) {37 let indexdb = this.result;38 let indexT = indexdb.transaction(OBJSTORE_POST_REQ_NAME,'readwrite');39 let indexO = indexT.objectStore(OBJSTORE_POST_REQ_NAME);40 indexO.add({41 url: url,42 payload: payload,43 method: 'POST'44 })45 }46}47function sendPostToServer() {48 let indexedDBOpenRequest = indexedDB.open(INDEX_DB_NAME, 1);49 indexedDBOpenRequest.onsuccess = function(event) {50 let indexdb = this.result;51 let indexT = indexdb.transaction(OBJSTORE_POST_REQ_NAME,'readwrite');52 let indexO = indexT.objectStore(OBJSTORE_POST_REQ_NAME);53 let req = indexO.openCursor();54 let savedRequests = [];55 req.onsuccess = function (event) {56 let cursor = event.target.result57 if (cursor) {58 // Keep moving the cursor forward and collecting saved requests.59 savedRequests.push(cursor.value)60 cursor.continue()61 }62 else {63 for (let savedRequest of savedRequests) {64 let requestUrl = savedRequest.url65 let payload = JSON.stringify(savedRequest.payload)66 let method = savedRequest.method67 let headers = {68 'Accept': 'application/json',69 'Content-Type': 'application/json'70 }71 fetch(requestUrl, {72 headers: headers,73 method: method,74 body: payload75 }).then(function (response) {76 console.log('SyncSend to Server success with response:', response)77 if (response.ok) {78 // If sending the POST request was successful, then79 // remove it from the IndexedDB.80 deletePostRequests(savedRequest.id);81 }82 }).catch(function (error) {83 console.error('SyncSend to Server failed:', error);84 throw error;85 })86 }87 }88 }89 }90}91// Call Install Event92self.addEventListener('install', e => {93 self.skipWaiting();94 console.log('Service Worker: Installed');95 // always cache offline page and index page96 let offlineRequest = new Request('/offline');97 e.waitUntil(98 fetch(offlineRequest).then(function (response) {99 return caches.open(cacheName).then(function (cache) {100 return cache.put(offlineRequest, response);101 });102 })103 );104 let indexRequest = new Request('/');105 e.waitUntil(106 fetch(indexRequest).then(function (response) {107 return caches.open(cacheName).then(function (cache) {108 return cache.put(indexRequest, response);109 });110 })111 );112});113// Call Activate Event114self.addEventListener('activate', e => {115 console.log('Service Worker: Activated');116 // Create Index DB117 e.waitUntil(createIndexDB());118 // Remove unwanted caches119 e.waitUntil(120 caches.keys().then(cacheNames => {121 return Promise.all(122 cacheNames.map(cache => {123 if (cache !== cacheName) {124 console.log('Service Worker: Clearing Old Cache');125 return caches.delete(cache);126 }127 })128 );129 })130 );131});132// Call Fetch Event133self.addEventListener('fetch', e => {134 if (e.request.clone().method === 'GET') {135 console.log('Service Worker: Fetching -- GET');136 let faster_fail = new Promise((resolve, reject) => {137 setTimeout(() => reject(new Error('waited 3s and fail faster')), 3000);138 });139 e.respondWith(140 Promise.race([faster_fail, fetch(e.request)])141 .then(res => {142 // Make copy/clone of response143 const resClone = res.clone();144 // Open cahce145 caches.open(cacheName).then(cache => {146 // Add response to cache147 cache.put(e.request, resClone);148 });149 return res;150 })151 .catch(() => caches.match(e.request)152 .then(res => {153 if (res.status < 400) {154 return res;155 }156 else {157 // redirect to offline158 return caches.open(cacheName).then(cache => {159 return cache.match('/offline');160 });161 }162 })163 .catch(() => {164 // redirect to offline165 return caches.open(cacheName).then(cache => {166 return cache.match('/offline');167 });168 }))169 );170 }171 else if (e.request.clone().method === 'POST') {172 console.log('Service Worker: Fetching -- POST');173 let faster_fail = new Promise((resolve, reject) => {174 setTimeout(() => reject(new Error('waited 3s and fail faster')), 3000);175 });176 e.respondWith(177 // attempt to send request normally178 Promise.race([faster_fail, fetch(e.request.clone())])179 .then(res => res)180 .catch(() => {181 // only save post requests in browser, if an error occurs182 savePostRequests(e.request.clone().url, form_data);183 // redirect to index184 return caches.open(cacheName).then(cache => {185 return cache.match('/offline');186 });187 }))188 }189});190// Capture message event191self.addEventListener('message', e => {192 console.log('form data', e.data)193 if (e.data.hasOwnProperty('form_data')) {194 // receives form data from post js upon submission195 form_data = e.data.form_data;196 }197});198self.addEventListener('sync', function (event) {199 console.log('now online')200 if (event.tag === 'sendFormData') {201 event.waitUntil(202 // Send our POST request to the server, now that the user is online203 sendPostToServer()204 )205 }...
IDB.ts
Source:IDB.ts
1const DB_NAME = 'cog';2const DB_VERSION = 11;3let db: IDBDatabase;4export const getObjectStore = (5 storeName: string,6 mode: 'readwrite' | 'readonly' | 'versionchange' | undefined = 'readwrite'7): IDBObjectStore => db.transaction([storeName], mode).objectStore(storeName);8export const openDatabase = (storeName: string): void => {9 const indexedDBOpenRequest = indexedDB.open(DB_NAME, DB_VERSION);10 indexedDBOpenRequest.onsuccess = function onSuccess(this: IDBRequest<IDBDatabase>) {11 db = this.result;12 };13 indexedDBOpenRequest.onupgradeneeded = function onUpgrade(this: IDBOpenDBRequest) {14 this.result.createObjectStore(storeName, {autoIncrement: true, keyPath: 'id'});15 };...
Using AI Code Generation
1var db;2var openRequest = indexedDB.open("MyTestDatabase");3openRequest.onupgradeneeded = function(e) {4 var thisDB = e.target.result;5 if(!thisDB.objectStoreNames.contains("MyTestDatabase")) {6 thisDB.createObjectStore("MyTestDatabase");7 }8}9openRequest.onsuccess = function(e) {10 db = e.target.result;11 db.close();12 done();13}14openRequest.onerror = function(e) {15 assert_unreached("Error opening database.");16}17var db;18var openRequest = indexedDB.open("MyTestDatabase");19openRequest.onupgradeneeded = function(e) {20 var thisDB = e.target.result;21 if(!thisDB.objectStoreNames.contains("MyTestDatabase")) {22 thisDB.createObjectStore("MyTestDatabase");23 }24}25openRequest.onsuccess = function(e) {26 db = e.target.result;27 db.close();28 done();29}30openRequest.onerror = function(e) {31 assert_unreached("Error opening database.");32}33var db;34var openRequest = indexedDB.open("MyTestDatabase");35openRequest.onupgradeneeded = function(e) {36 var thisDB = e.target.result;37 if(!thisDB.objectStoreNames.contains("MyTestDatabase")) {38 thisDB.createObjectStore("MyTestDatabase");39 }40}41openRequest.onsuccess = function(e) {42 db = e.target.result;43 db.close();44 done();45}46openRequest.onerror = function(e) {47 assert_unreached("Error opening database.");48}49var db;50var openRequest = indexedDB.open("MyTestDatabase");51openRequest.onupgradeneeded = function(e) {52 var thisDB = e.target.result;53 if(!thisDB.objectStoreNames.contains("MyTestDatabase")) {54 thisDB.createObjectStore("MyTestDatabase");55 }56}57openRequest.onsuccess = function(e) {58 db = e.target.result;
Using AI Code Generation
1var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;2var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;3var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;4var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;5var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;6var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;7var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;8var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;9var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;10var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;11var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;12var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;13var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;14var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;15var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;16var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;17var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;18var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;19var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;20var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;21var indexedDbOpenRequest = require('wpt-tools').indexedDbOpenRequest;
Using AI Code Generation
1var indexedDBOpenRequest = indexedDB.open("my_database");2indexedDBOpenRequest.onsuccess = function(event) {3 var db = event.target.result;4 var transaction = db.transaction(["my_object_store"], "readonly");5 var objectStore = transaction.objectStore("my_object_store");6 var objectStoreRequest = objectStore.get("my_key");7 objectStoreRequest.onsuccess = function(event) {8 var result = event.target.result;9 if (result) {10 console.log(result);11 } else {12 console.log("No result");13 }14 };15};16var indexedDBOpenRequest = indexedDB.open("my_database");17indexedDBOpenRequest.onsuccess = function(event) {18 var db = event.target.result;19 var transaction = db.transaction(["my_object_store"], "readonly");20 var objectStore = transaction.objectStore("my_object_store");21 var objectStoreRequest = objectStore.get("my_key");22 objectStoreRequest.onsuccess = function(event) {23 var result = event.target.result;24 if (result) {25 console.log(result);26 } else {27 console.log("No result");28 }29 };30};31var indexedDBOpenRequest = indexedDB.open("my_database");32indexedDBOpenRequest.onsuccess = function(event) {33 var db = event.target.result;34 var transaction = db.transaction(["my_object_store"], "readonly");35 var objectStore = transaction.objectStore("my_object_store");36 var objectStoreRequest = objectStore.get("my_key");37 objectStoreRequest.onsuccess = function(event) {38 var result = event.target.result;39 if (result) {40 console.log(result);41 } else {42 console.log("No result");43 }44 };45};46var indexedDBOpenRequest = indexedDB.open("my_database");47indexedDBOpenRequest.onsuccess = function(event) {48 var db = event.target.result;49 var transaction = db.transaction(["my_object_store"], "readonly");50 var objectStore = transaction.objectStore("my_object_store");51 var objectStoreRequest = objectStore.get("my_key");
Using AI Code Generation
1var db = indexedDB.open("test", 1);2db.onsuccess = function(evt) {3 var db = evt.target.result;4 var transaction = db.transaction(["test"]);5 var objectStore = transaction.objectStore("test");6 var request = objectStore.get("key");7 request.onsuccess = function(evt) {8 var value = evt.target.result;9 if (value == "value") {10 return "pass";11 } else {12 return "fail";13 }14 };15};
Using AI Code Generation
1wptbIndexedDb.indexedDbOpenRequest('test', 'test', 'test', function(e) {2 var db = e.target.result;3 var tx = db.transaction(['test'], 'readwrite');4 var store = tx.objectStore('test');5 var index = store.index('test');6 var request = index.getKey('test');7 request.onsuccess = function(e) {8 console.log(e.target.result);9 };10 request.onerror = function(e) {11 console.log(e);12 };13});14wptbIndexedDb.indexedDbOpenCursor('test', 'test', 'test', function(e) {15 var cursor = e.target.result;16 if (cursor) {17 console.log(cursor);18 cursor.continue();19 }20});21wptbIndexedDb.indexedDbOpenCursorRequest('test', 'test', 'test', function(e) {22 var cursor = e.target.result;23 if (cursor) {24 console.log(cursor);25 cursor.continue();26 }27});28wptbIndexedDb.indexedDbOpenCursorRequestRange('test', 'test', 'test', 1, 10, function(e) {29 var cursor = e.target.result;30 if (cursor) {31 console.log(cursor);32 cursor.continue();33 }34});35wptbIndexedDb.indexedDbDeleteObjectStore('test', 'test', 'test', function(e) {36 console.log(e);37});38wptbIndexedDb.indexedDbDeleteDatabase('test', function(e) {39 console.log(e);40});41wptbIndexedDb.indexedDbClearObjectStore('test', 'test', 'test', function(e) {42 console.log(e);43});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!