如何在脚本中使用javascript创建按钮和文本。 (Tampermonkey)

时间:2016-09-22 16:48:48

标签: javascript google-chrome

我正在使用篡改猴子创建脚本(Javascript)。此平台上最常用的脚本创建按钮和框,以便在他们希望脚本发生的网站上输入文本(例如,在google.com上创建一个额外的按钮,单击它时会执行一项功能)。我有一些例子,例如你直接在youtube网站上管你的mp4转换器。 (如果这有帮助)如果这需要HTML或CSS在不熟悉这些语言。 如何创建像此脚本一样的按钮和文本框以放入我的JavaScript代码?

Script

1 个答案:

答案 0 :(得分:1)

此代码将创建一个按钮(Add a JavaScript button using Greasemonkey or Tampermonkey?):

// ==UserScript==
// @name        _Adding a live button
// @description Adds live example button, with styling.
// @include     https://stackoverflow.com/questions/*
// @grant       GM_addStyle
// ==/UserScript==

/*--- Create a button in a container div.  It will be styled and
    positioned with CSS.
*/
var zNode       = document.createElement ('div');
zNode.innerHTML = '<button id="myButton" type="button">'
                + 'For Pete\'s sake, don\'t click me!</button>'
                ;
zNode.setAttribute ('id', 'myContainer');
document.body.appendChild (zNode);

//--- Activate the newly added button.
document.getElementById ("myButton").addEventListener (
    "click", ButtonClickAction, false
);

function ButtonClickAction (zEvent) {
    /*--- For our dummy action, we'll just add a line of text to the top
        of the screen.
    */
    var zNode       = document.createElement ('p');
    zNode.innerHTML = 'The button was clicked.';
    document.getElementById ("myContainer").appendChild (zNode);
}

//--- Style our newly added elements using CSS.
GM_addStyle ( multilineStr ( function () {/*!
    #myContainer {
        position:               absolute;
        top:                    0;
        left:                   0;
        font-size:              20px;
        background:             orange;
        border:                 3px outset black;
        margin:                 5px;
        opacity:                0.9;
        z-index:                222;
        padding:                5px 20px;
    }
    #myButton {
        cursor:                 pointer;
    }
    #myContainer p {
        color:                  red;
        background:             white;
    }
*/} ) );

function multilineStr (dummyFunc) {
    var str = dummyFunc.toString ();
    str     = str.replace (/^[^\/]+\/\*!?/, '') // Strip function () { /*!
            .replace (/\s*\*\/\s*\}\s*$/, '')   // Strip */ }
            .replace (/\/\/.+$/gm, '') // Double-slash comments wreck CSS. Strip them.
            ;
    return str;
}