4

I have html page built by javascript at runtime. At some moment of time I want to create a backup of this page to be able to restore it later. The page is described by DOM, so it's logically to save the DOM itself. The problem is - it seems there are no legit ways to do so.

I only found XMLSerializer interface which can be used to serialize html only (so, that's not the right tool). But I need to save mutation observers and event listeners, such 'restored' page would behave as it's ancestor.

I also thought about recording to log file javascript operations over DOM. But the page that is building itself in runtime is huge and complicated, so such approach will cost a lot of time.

Any ideas?

  • 1
    There is no magic way to do this - keep a track of observers/event listeners you install (make an array log) and add that to your dump. – Benjamin Gruenbaum May 03 '15 at 08:20
  • Usually the way this is done is that you don't specifically save the HTML and event listeners of the page, but rather as you build the page with JS, you build up a state object that describes what has been done to the page. Then, you write code that can read that state object to rebuild the page in the same way. If you're really good, you can make the rebuild code be the same code as the code that builds the page the first time. – jfriend00 May 03 '15 at 09:43
  • You can think of the problem like the code that is used to maintain an undo stack. Rather than save the entire state of the document after each change, an undo stack typically saves incremental commands/data that modify the page and you can get back to any particular state by just reapplying (or in the case of undo by reversing) those commands. You can do the same for changes to the DOM. The higher level commands you save, the less data you typically need to store. – jfriend00 May 03 '15 at 09:45

1 Answers1

0

All infos including listeners are stored in the window object. You can inspect it: console.log(window).

To dump the window object just copy it and send it to an api to store it.

webcodecs
  • 217
  • 2
  • 9
  • No. Listeners are not stored on the `window` object. Also, can you please describe a reliable way to serialize `window` (to copy and send it around)? `JSON.stringify` does not work. – Bergi May 03 '15 at 09:07
  • I found another [post](http://stackoverflow.com/questions/4079653/stringify-domwindow-object#answer-29804164) on stackoverflow. There is a snippet to stringify more complex objects. But your right with the event listeners. Otherwise you have to put them in a queue on creation and on restoring the backup you could reinitialise the stored event listeners. – webcodecs May 03 '15 at 12:59
  • Yeah, you could use [such](http://stackoverflow.com/a/14145840/1048572) to get a stringification, but really there's no reason to stringify `window` when you want the DOM (which should be serialised as XML, not JSON) – Bergi May 03 '15 at 13:50