Created
September 13, 2019 22:35
-
-
Save n-bell/b375c80b638d3a59a250e903afb4a36b to your computer and use it in GitHub Desktop.
Tampermonkey / Greasemonkey Dexie.js database storage in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name TESTDatabase | |
// @namespace foobar.com | |
// @version 0.1.1 | |
// @description testing database functionality | |
// @include https://sample.somesite.com/* | |
// @require https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js | |
// @require https://unpkg.com/dexie@latest/dist/dexie.js | |
// @grant GM_getValue | |
// @grant GM_setValue | |
// @grant GM.getValue | |
// @grant GM.setValue | |
// ==/UserScript== | |
/* global $ */ | |
/* eslint-disable no-multi-spaces, curly */ | |
(function () { | |
'use strict'; | |
const MAX_VALUE_INT = 2147483647; | |
const dbName = 'proof-of-concept-db-test-6'; | |
const tmObj = 'proof-concept-tm-obj-6'; | |
// database ref for use right when the TamperMonkey script loads on the current page | |
var db = initDB(); | |
function initDB() { | |
console.log('initDB - start'); | |
// #1 check to see if Tampermonkey already has the database stored; | |
let tmDBObj = GM.getValue(tmObj); | |
tmDBObj.then( | |
function (data) { | |
if (data == null) { | |
console.log('tampermonkey does not hold the database'); | |
let databaseTEST = new Dexie(dbName); | |
databaseTEST.version(1).stores( | |
{ logHistory: '++id,state,elapsedtime' } | |
); | |
// I think dexie require opening the database at least once, thus doing it when creating the database | |
let openData = databaseTEST.open(); | |
openData.then( | |
function (data) { | |
console.log('opened the database! - ' + data); | |
return databaseTEST.logHistory.add( | |
{ | |
state: 'Sample-State', | |
time: new Date().getTime() | |
} | |
); | |
} | |
).catch( | |
function (e) { | |
console.log('error --- ' + e); | |
} | |
); | |
GM.setValue(tmObj, JSON.stringify(databaseTEST)); | |
} else { | |
console.log('tampermonkey has a stored database, time to load it up!'); | |
let openDBFromFile = JSON.parse(GM.getValue(tmObj)); // this should be our Dexie DB | |
let results = openDBFromFile.logHistory | |
.where("id") | |
.between(0, MAX_VALUE_INT); // line throws error, "SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data" | |
} | |
} | |
).catch( | |
function (error) { | |
console.log('error - ' + error); | |
} | |
); | |
} | |
})(); |
Intended use - store a database in a Tampermonkey storage in order to access cross sites.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Posted on behalf of the Stackoverflow question - https://stackoverflow.com/q/57929417/6393165