There are three components:
- import simplemde
- add a
textarea
- add scripts to:
- initialize simplemde,
- save changes to localstorage every second
- check for more recent entry based on time from other tabs
- import scripts
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.css"
/>
<script src="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.js"></script>
- textarea & wrapping column for context
<div style="display: flex; flex-direction: column; padding-top: 1.4rem">
<div
style="opacity: 0.5;
margin-left: 4rem;
max-width: 400px;
min-width: 400px;
width: 100%;">
<textarea style="width: 400px; height: 600px; max-width: 400px"></textarea>
</div>
</div>
- initialize simplemde, and save to / pull from localstorage (thank you gpt)
<script>
var simplemde = new SimpleMDE({
autofocus: true,
spellChecker: false,
toolbar: false,
status: false,
});
let lastSavedContent = localStorage.getItem('content') || simplemde.value();
let lastSavedTimestamp = localStorage.getItem('timestamp') || Date.now();
// Load the latest content from localStorage
if (lastSavedContent) {
simplemde.value(lastSavedContent);
}
// Check for changes every second
setInterval(() => {
const currentContent = simplemde.value();
const currentTimestamp = Date.now();
// If the content in localStorage is fresher, use that instead
if (currentTimestamp < lastSavedTimestamp && currentContent !== lastSavedContent) {
simplemde.value(lastSavedContent);
} else if (currentContent !== lastSavedContent) {
// If the content has changed, save it to localStorage
localStorage.setItem('content', currentContent);
localStorage.setItem('timestamp', currentTimestamp.toString());
lastSavedContent = currentContent;
lastSavedTimestamp = currentTimestamp;
}
}, 1000);
// Listen for changes to localStorage from other tabs
window.addEventListener('storage', function(e) {
if (e.key === 'content') {
lastSavedContent = e.newValue;
simplemde.value(lastSavedContent);
} else if (e.key === 'timestamp') {
lastSavedTimestamp = e.newValue;
}
});
</script>