0

I would like to rewrite the <html> content using Greasemonkey.

I tried this:

document.open()
document.write(html)
document.close()

Not working.

document.body.innerHTML = html only replaces the content.

Some suggestions?

Brock Adams
  • 82,642
  • 19
  • 207
  • 268
mykiwi
  • 1,572
  • 1
  • 15
  • 32

1 Answers1

3

Don't use document.write(). It has all kinds of security restrictions (due to abuse by bad guys) and is fraught with pitfalls.

if you try to use it, as in your question, in a userscript; Firefox will typically either stall the page completely or go into a perpetual Connecting... then reload cycle -- depending on when your script fires and whether you use unsafeWindow.stop().
This kind of code still works in Chrome (for now), but remains a bad practice. Not sure about other browsers.

The correct approach is to use DOM methods. For example:

var D       = document;
var newDoc  = D.implementation.createHTMLDocument ("My new page title");
window.content = newDoc;

D.replaceChild (
    D.importNode (newDoc.documentElement, true),
    D.documentElement
);

D.body.innerHTML = '<h1>Standby...</h1>';

For enhanced performance, you may also wish to use:

// @run-at      document-start
// @grant       unsafeWindow

and then place an unsafeWindow.stop (); at the top of the userscript code.




Re: "How do I rewrite the head content with this solution?":

This example already rewrites the <head>. The new head will be:

<head><title>My new page title</title></head>

in this case.

To add additional head elements, use DOM code like:

var newNode     = D.createElement ('base');
newNode.href    = "http://www.example.com/dir1/page.html";
var targ        = D.getElementsByTagName ('head')[0];
targ.appendChild (newNode);

Except:

  1. Just use GM_addStyle() to easily create <style> nodes.
  2. Adding <script> nodes is almost always pointless in your scenario. Just have your userscript do any needed JS processing.
  3. Some tags like <meta> will be added but not processed (especially in Firefox). Depending on the parameters, these are only parsed on initial load from a server.
Community
  • 1
  • 1
Brock Adams
  • 82,642
  • 19
  • 207
  • 268