0

I'm working on highlighting feature for one project, that in theory would work like that:

  1. User selects something on page and clicks a button to highlight it (for that we are using tsv.annotator that works with rangy)
  2. After clicking the button we call document.getSelection()
  3. We save the anchor and focus nodes, as well as offsets into database
  4. When user opens the page again we get the nodes from db and highlight it

But that doesn't work because JSON.stringify returns empty object when passed document.getSelection().

The selection object as requested: selection

A minimal reproducible example would be like that:

let selection = JSON.stringify(document.getSelection()); // => outputs {}
bdkopen
  • 494
  • 1
  • 6
  • 16
Michal Gally
  • 127
  • 1
  • 9
  • 3
    Without providing a [mcve] that demonstrates the issue, it is hard for anyone to help troubleshoot this without guessing – charlietfl Mar 14 '21 at 15:00
  • Does [this](https://stackoverflow.com/questions/38542265/why-does-json-stringify-return-empty-object-notation-for-an-object-that-see) help? You will have to copy the values you want to save to a new object and save that – marks Mar 14 '21 at 15:04
  • 1
    Probably the selection `toString` returns an empty object. You can just extract whatever properties you need (and can be stringify of course). For example: `const {anchorOffset, baseOffset} = document.getSelection()`. – Mosh Feu Mar 14 '21 at 15:56
  • @MoshFeu the output is the same = {} – Michal Gally Mar 14 '21 at 18:38
  • Try `const {anchorOffset, baseOffset} = document.getSelection(); console.log({anchorOffset, baseOffset})` – Mosh Feu Mar 14 '21 at 21:03
  • I understand that, but if I stringify this it still results in an empty object. – Michal Gally Mar 15 '21 at 09:30

0 Answers0