title: Trouble saving scroll position in Chrome extension popup
body: <p>I'm relatively new to programming and am working on a Chrome extension with a popup. I want to save the scroll position between popup invocations. It seems like I've found a lot of info on the internet, but so far I haven't been able to solve my problem. Saving the scroll position almost works within my extension, but I'm seeing 2 issue:</p>
  
  <p><strong>1)</strong> To save the scroll position at each scroll event, I use:</p>
  
  <pre><code>addEventListener('scroll', function(){
     localStorage.scrollTop = document.body.scrollTop;
  });
  </code></pre>
  
  <p>When the popup is opened, I use:</p>
  
  <pre><code>document.body.scrollTop = localStorage.scrollTop
  </code></pre>
  
  <p>This seems to work fine until my scroll position exceeds the popup height. The max popup height for visible content in a Chrome extension is 600px. <code>document.body.style.height</code> is also always a fixed value greater than 600px. When the scroll position is greater than <code>document.body.style.height</code> - 600px, say 900px - 600px, <code>document.body.scrollTop</code> is reset to 300px. Even if the last scroll position (<code>document.body.scrollTop</code>) was 400px before the popup is closed, scroll position is reset to 300px when the popup is re-opened. Obviously, I get the wrong scroll position because the proper scroll position value of 400px (for example) is then overwritten by 300px.</p>
  
  <p>However, it doesn't always happen. Sometimes I can properly save a scroll position of, say 500px with a window height of 900px, and other times I can't. I don't know for sure why this has any effect, but as the content in the popup is taller the problem seems to magically go away and the proper scroll position is saved.</p>
  
  <p>How can I properly save the scroll position when the scroll position in this situation? Perhaps I'm doing something fundamentally wrong?</p>
  
  <p>(This seems confusing to read. I hope it's possible to help with the code above.)</p>
  
  <p><strong>2)</strong> I think might be intertwined with the above issue, but I'm not sure. For every scroll event (first code block in this post), I see a pair of scroll events fired.</p>
  
  <p>If I just open the popup but don't scroll the mousewheel, I see code inside my event listener fire. When the first event happens, <code>document.body.scrollTop</code> is reset to the "wrong" value (300px in the example above). I think this might be the root cause of both issues.</p>
  
  <p>Shouldn't the event listener only fire if the mousewheel is moved, and thus the code inside the event listener doesn't execute if the popup is opened but the mousewheel isn't touched?</p>