我对Greasemonkey的世界相当新,我想知道如何在JavaScript中创建一个按钮。
我想说我想在YouTube或Google上放一个按钮吗?我该如何调用它或制作它?
我很困惑,无法找到任何东西。除非有人与这些网站的HTML进行交互并将它们添加到Greasemonkey脚本中吗?
答案 0 :(得分:26)
好的,这是一个完整的脚本,为SO问题页面添加了一个实时按钮 1 :
// ==UserScript==
// @name _Adding a live button
// @description Adds live example button, with styling.
// @match *://stackoverflow.com/questions/*
// @match *://YOUR_SERVER.COM/YOUR_PATH/*
// @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 ( `
#myContainer {
position: absolute;
top: 0;
left: 0;
font-size: 20px;
background: orange;
border: 3px outset black;
margin: 5px;
opacity: 0.9;
z-index: 1100;
padding: 5px 20px;
}
#myButton {
cursor: pointer;
}
#myContainer p {
color: red;
background: white;
}
` );
1 令人惊讶的是,这个问题在SO之前似乎没有被这样问过。
答案 1 :(得分:2)
如果你问我,你可以做得更小(使用HTML5和es6),如:
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
}
示例脚本(用于选择Google收件箱中的所有已读电子邮件):
// ==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)
}
}())