bushdiver bushdiver - 1 month ago 14
HTML Question

Basic method to Add html content to the page with Greasemonkey?

Is there a Greasemonkey method to append basic HTML content to the end of a page right after the

<body>
tag, or right before it ends?

I found before/after methods but I need to know names of elements which may change page to page..

Answer

The quick and dirty way: Please only use innerHTML for brand-new content.

var newHTML         = document.createElement ('div');
newHTML.innerHTML   = '             \
    <div id="gmSomeID">             \
        <p>Some paragraph</p>       \
        etc.                        \
    </div>                          \
';

document.body.appendChild (newHTML);


A complete script showing the somewhat better jQuery way:

// ==UserScript==
// @name     YOUR_SCRIPT_NAME
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/
$("body").append ( '                \
    <div id="gmSomeID">             \
        <p>Some paragraph</p>       \
        etc.                        \
    </div>                          \
' );


Both methods will place the new content like this:

<!-- NEW STUFF INSERTED HERE -->
</body>

Which is a good place for it.

Even though the HTML is at the end of the page, you can use CSS to display it anywhere with something like:

GM_addStyle ( "                         \
    #gmSomeID {                         \
        position:       fixed;          \
        top:            0px;            \
        left:           0px;            \
    }                                   \
" );
Comments