Add a JavaScript button using Greasemonkey or Tampermonkey?

Viewed 45746

I am fairly new to the world of Greasemonkey and I was wondering how to make a button in JavaScript.

Say I wanted to put a button on YouTube or Google for instance? How would I go about calling it or making it?

I'm very confused and cant find anything on it. Unless is there someway to interact with the HTML of these sites and add them to Greasemonkey scripts?

2 Answers

if you ask me, you can do it lot smaller( with HTML5 n es6) like:

function addButton(text, onclick, cssObj) {
    cssObj = cssObj || {position: 'absolute', bottom: '7%', left:'4%', 'z-index': 3}
    let button = document.createElement('button'), btnStyle = button.style
    document.body.appendChild(button)
    button.innerHTML = text
    button.onclick = onclick
    btnStyle.position = 'absolute'
    Object.keys(cssObj).forEach(key => btnStyle[key] = cssObj[key])
    return button
}

example script (for selecting all the read emails in google inbox):

// ==UserScript==
// @name        mark unread
// @namespace   all
// @include     https://inbox.google.com/*
// @version     1
// @grant       none
// ==/UserScript==

(function(){
    'use strict'

  window.addEventListener('load', () => {
    addButton('select read', selectReadFn)
    })

    function addButton(text, onclick, cssObj) {
        cssObj = cssObj || {position: 'absolute', bottom: '7%', left:'4%', 'z-index': 3}
        let button = document.createElement('button'), btnStyle = button.style
        document.body.appendChild(button)
        button.innerHTML = text
        button.onclick = onclick
        Object.keys(cssObj).forEach(key => btnStyle[key] = cssObj[key])
        return button
    }

    function selectReadFn() {
        [...document.getElementsByClassName('MN')].filter(isRead).forEach(element => element.click())
    }

    function isRead(element) {
        childs = element.parentElement.parentElement.parentElement.getElementsByClassName('G3')
        return ![...childs].some(e => e.innerText.search(/unread/i)!==-1)
    }

}())
Related