Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

javascript - 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..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 (and with new, ECMAScript 6, multiline string):

// ==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 used to restore the proper 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;            
    }                                   
" );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...