How can I save document body edits across refresh page?

77 Views Asked by At

I have a JavaScript bookmarklet that lets me edit a pages body: document.body.contentEditable = true;

I would like to make a bookmarklet that allows me to save these edits so if I refresh the page it will keep them, or display them when I click the bookmarklet.

I know local storage exists, but I'm not sure how to update corresponding elements using local storage.

Any ideas?

2

There are 2 best solutions below

1
LordJuicy On

I found a way. Using JavaScript I can just save the entire HTML body, then load that and replace the pages original content with the saved HTML.

It uses an IF check to see if the page is currently editable, then it will save the data. If it is not editable, then is will load that data.

The JavaScript:

javascript:(function() {
  // Check if content is editable
  if (document.body.isContentEditable) {
    // Save the edited content to localStorage
    localStorage.setItem('editedContent', document.body.innerHTML);
    alert('Changes saved!');
  } else {
    // Load saved content from localStorage
    var savedContent = localStorage.getItem('editedContent');
    if (savedContent !== null) {
      // Set the saved content to the page's body
      document.body.innerHTML = savedContent;
      document.body.contentEditable = true;
    } else {
      alert('No saved content found.');
    }
  }
})();

the actuall bookmarklet:

javascript:(function()%7Bjavascript%3A(function() %7B%0A  %2F%2F Check if content is editable%0A  if (document.body.isContentEditable) %7B%0A    %2F%2F Save the edited content to localStorage%0A    localStorage.setItem('editedContent'%2C document.body.innerHTML)%3B%0A    alert('Changes saved!')%3B%0A  %7D else %7B%0A    %2F%2F Load saved content from localStorage%0A    var savedContent %3D localStorage.getItem('editedContent')%3B%0A    if (savedContent !%3D%3D null) %7B%0A      %2F%2F Set the saved content to the page's body%0A      document.body.innerHTML %3D savedContent%3B%0A      document.body.contentEditable %3D true%3B%0A    %7D else %7B%0A      alert('No saved content found.')%3B%0A    %7D%0A  %7D%0A%7D)()%3B%7D)()%3B```
0
Glitch On

javascript: (function() {
  function save() {
    localStorage.setItem('SavedState', document.body.innerHTML);
    alert('State saved!');
  }

  function load() {
    var savedContent = localStorage.getItem('SavedState');
    if (savedContent !== null) {
      document.body.innerHTML = savedContent;
      alert('State loaded!');
    } else {
      alert('No saved state found.');
    }
  }
  var saveorload = prompt('save or load? It must be exactly save or load.');
  if (saveorload == 'save') {
    save();
  }
  if (saveorload == 'load') {
    load();
  }
})()