使用Greasemonkey将html内容添加到页面的基本方法?

bus*_*ver 13 html javascript greasemonkey tampermonkey

是否有Greasemonkey方法将基本HTML内容附加到<body>标记之后或页面结尾之前的页面末尾?

我在方法之前/之后找到了但我需要知道可能会改变页面到页面的元素的名称.

Bro*_*ams 24

快速而肮脏的方式:请仅innerHTML用于全新的内容.

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

document.body.appendChild (newHTML);
Run Code Online (Sandbox Code Playgroud)

一个完整的脚本显示了更好的jQuery方式(以及新的ECMAScript 6,多行字符串):

// ==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>
` );
Run Code Online (Sandbox Code Playgroud)

两种方法都会将新内容放置如下:

<!-- NEW STUFF INSERTED HERE -->
</body>
Run Code Online (Sandbox Code Playgroud)

这是一个好地方.

即使HTML位于页面的末尾,您也可以使用CSS在任何地方显示它,例如:

GM_addStyle ( "                         \
    #gmSomeID {                         \
        position:       fixed;          \
        top:            0px;            \
        left:           0px;            \
    }                                   \
" );
Run Code Online (Sandbox Code Playgroud)


dwj*_*ton 5

如果您不想因为不得不转义多行 html 而烦恼 - 您可以将 HTML 放在本地文件中,并使用GM_getResourceText. 确保您已启用 Greasemonkey/Tampermonkey 以使用本地文件。

例如:

// ==UserScript==
// @name         Tamper Test
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        file:///C:/david/sandbox/tampermonkey/tamper.html
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @resource html      file:///C:/david/sandbox/tampermonkey/foo.html
// @resource style     file:///C:/david/sandbox/tampermonkey/style.css
// @grant        GM_addStyle
// @grant  GM_getResourceText
// ==/UserScript==


(function() {
    'use strict';

    $("body").append('<div id = "dwj-tamper">new content from tamper script</div>');  

    GM_addStyle(GM_getResourceText("style"));    
    $("body").append(GM_getResourceText("html"));

})();
Run Code Online (Sandbox Code Playgroud)

如果篡改脚本仅供您自己使用,则此解决方案很好。您可以类似地在线保存资源。例如:

// @resource pastebin http://pastebin.com/raw/9WfbN24i

//...

 $("body").append(GM_getResourceText("pastebin"));
Run Code Online (Sandbox Code Playgroud)

也有效

在此处输入图片说明