~callum/beavers-dam

77c122bb68545b96fff4b171c46e9628766ef289 — Callum Brown 1 year, 2 months ago 30f69d5
Export and Import
2 files changed, 54 insertions(+), 2 deletions(-)

M options/options.html
M options/options.js
M options/options.html => options/options.html +6 -0
@@ 11,5 11,11 @@
		<input type="number" id="min-words"></input>
		<br>
		<button id="save">Save</button>
		<br><br>
		<button id="export">Export Data</button>
		<br>
		<label for="import">Import Data (Overwrites existing data!)</label>
		<br>
		<input type="file" accept=".json,text/plain" id="import"></input>
	</body>
</html>

M options/options.js => options/options.js +48 -2
@@ 1,4 1,17 @@
let minWordsInput = document.getElementById("min-words");
async function exportData() {
	const data = JSON.stringify({
		sync: await chrome.storage.sync.get(null),
		local: await chrome.storage.local.get(null),
	});
	const blob = new Blob([data], { type: "application/json" });
	var a = document.createElement('a');
	a.download = `Beavers Dam Export - ${new Date().toISOString()}.json`,
	a.href = window.URL.createObjectURL(blob);
	a.click();
	a.remove();
};

const minWordsInput = document.getElementById("min-words");

// Load saved options
chrome.storage.sync.get(


@@ 7,10 20,43 @@ chrome.storage.sync.get(
	minWordsInput.value = items.minWords;
});


document.getElementById("save").addEventListener("click", () => {
	// TODO: type check before saving
	chrome.storage.sync.set(
		{ minWords: minWordsInput.value }
	);
});

document.getElementById("export").addEventListener("click", exportData);

const importInput = document.getElementById("import");
importInput.addEventListener("change", () => {
	const [file] = importInput.files;
	if (file) {
		const reader = new FileReader();
		reader.addEventListener("load", () => {
			let data;
			let parsed = false;
			try {
				data = JSON.parse(reader.result);
				parsed = true;
			} catch (error) {
				window.alert("Could not parse file.");
				return;
			};
			// XXX: This assumes the data["sync"] and data["local"] objects
			// only contain primative values, `Array`s, `Date`s, and `Regex`s,
			// which can be serialised by the Chrome Storage API.
			// See docs for StorageArea.set
			chrome.storage.sync.set(data["sync"]).then(
				() => chrome.storage.local.set(data["local"]).then(
					() => {
						window.alert("Import successful");
						location.reload();
					}
				)
			);
		});
		reader.readAsText(file);
	}
});