JS library that "reloads" a page to mimic pre-load code injection?
<p>Apologies if the title is vague, but it's not the easiest question to describe. Currently, if you want to wrap/overload a built-in function in the browser, such as <code>XmlHttpRequest.prototype.open = function(){return oldOpen(...)}</code>, and you want to do it before any scripts in the page execute, you'd need to use a browser extension/addon that executes before the document starts being parsed. The thing is, browser extensions often have a low conversion rate of users who agree to install them. I'd love to be able to use bookmarklets to do the same thing (and Pinterest has shown that bookmarklets aren't a barrier for them!). But alas, bookmarklets by definition run long after the document has loaded.</p>

<p>What I'd like to do, and what I think is theoretically possible, is to fake a page reload, but with a script inserted already. The process would look something like this:</p>

<ol>
<li>Download, via XHR, the original document from <code>window.location</code>.</li>
<li>Remove all elements from the DOM, including all the script tags. Maybe throw up a nice splash screen for a good user experience.</li>
<li>Clear all timeouts and intervals (on FF and Chrome the IDs seem to count up from 1, so no a priori knowledge is needed AFAIK).</li>
<li>Delete/undefine all keys in <code>window</code> and <code>document</code> that aren't there in a blank document... which, given that there might be some extensions installed, might require some iframe trickery/messaging to actually get a reference blank document.</li>
<li>Inject your scripts into the now-blank document.</li>
<li>Re-insert all the tags from the XHR'd original document, including the scripts, which should then reload and re-execute in your new context.</li>
<li>Take down the splash screen, and you're good to go!</li>
</ol>

<p>Now, I'd be perfectly willing to take a stab at this and open source it, but has anyone tried something like this before? It'll be a lot of work, and I'd rather not reinvent the wheel unless what we're using now is the equivalent of square boulders on sticks.</p>
