I'm trying to automate some button clicking and data inserting into a webpage by using TamperMonkey. However, even after all the data from the array has been inserted, the javascript keep on clicking on the button. How do I set it so that once the data from the array has been finished inserted, the javascript should stop running.
Here's the code, to automate batch input of gift cards into shopify.
// ==UserScript==
// #name Shopify Gift Card Generator
// #namespace http://tampermonkey.net/
// #version 0.1
// #description Generate Gift Cards from a list
// #author You
// #grant GM.getValue
// #grant GM.setValue
// #require http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js
// #match https://[myshopname].myshopify.com/admin/gift_cards
// #run-at document-idle
// ==/UserScript==
/* globals $ */
(function() {
'use strict';
//add recipient list
var rec = ["2920469463099",
"2920466415675",
];
function generateCard(code){
if($('button:contains("Issue gift card")') !== "undefined"){
//click generate gift card
$('button:contains("Issue gift card")').click();
//set recipient based on id
$('#gift_card_customer_id').attr("value", code);
//select the dollar amount eq(0) = 10, eq(1) = 25, eq(2) = 50, eq(3) = 100
$('.segmented-control.large li:eq(2) label')[0].click();
//submit!
//$('form.new_gift_card')[0].submit();
$('input[type=submit]').click();
var success = false;
function closeWindow(){
if($('.gift-card-success-heading h2:contains("RM50.00 MYR gift card successfully issued")').length == 1){
if ($('#gift-card-issue-errors:contains("There ")').length == 0) {
//close the modal and restart!
$('a.close-modal').click();
console.log('last successful recipient id: ');
console.log(GM.getValue('last'));
setTimeout(function(){
generateCard(rec.pop());
}, 750);
} else {
console.log('generation error. last code:');
console.log(GM.getValue('last'));
success = false;
}
} else {
setTimeout(function(){ closeWindow(); }, 500);
}
}
closeWindow();
return success;
} else {
generateCard(code);
}
}
function begin(){
//wait for the page to load / not over-request the shopify server
setTimeout(function(){
generateCard(rec.pop());
}, 1500);
}
begin();
})();
Any suggestions on how to solve the issue? Thank you.
Don't start the next timer when rec is empty.
if (rec.length > 0) {
setTimeout(function(){
generateCard(rec.pop());
}, 750);
}
Add check before calling the generateCard method in setTimeout.
Currently this method is getting called with undefined value after array is empty.
setTimeout(function() {
if (rec.length > 0) {
generateCard(rec.pop());
}
}, 1500);
You can use a reducer method with your code inside the function for each array item. That way when you finish the last item of the array execution stops.
let yourArray = [...yourData];
const reducer = (accumulator, currentValue) => {
//your button clicking logic here
};
yourArray.reduce(reducer);
Related
So I am attempting to write a auto login script for this website
https://www.urbtix.hk/login/?redirect=%252Fperformance-detail%253FeventId%253D9269%2526performanceId%253D41302
but I fail to trigger the validation for the input field, so I cant actually unlock the login button.
I have observed the event fired using monitorEvents($0) in chrome devtool, and I see there is a change event, so attempt to simulate that too but still I fail to trigger the validation. Any clue on how I can get a string filled into the input filed?
// ==UserScript==
// #name urbtixLoginAutoFill
// #namespace http://tampermonkey.net/
// #version 0.1
// #description try to take over the world!
// #author You
// #match https://www.urbtix.hk/login/*
// #icon https://www.google.com/s2/favicons?sz=64&domain=urbtix.hk
// #require https://code.jquery.com/jquery-3.6.0.min.js
// #require https://gist.github.com/raw/2625891/waitForKeyElements.js
// ==/UserScript==
function setControl(elemSelector, value) {
var zInput = $(elemSelector);
zInput.val(value);
console.log("setControl", zInput);
// var changeEvent = document.createEvent("HTMLEvents");
// changeEvent.initEvent("change", true, true);
// zInput[0].dispatchEvent(changeEvent);
const change = new Event("change");
zInput[0].dispatchEvent(change);
}
const sleep = async (milliseconds) => {
await new Promise((resolve) => {
return setTimeout(resolve, milliseconds);
});
};
var _username = "username";
var _password = "password";
var userInputSelector = "input[name='loginId']";
var passwordInputSelector = "input[name='password']";
var loginButtonSelector =
"#root > div > div.main___3Egpk > div > div > div.field-row.field-row-login-button > div.button-wrapper.login-button.blue.disabled";
$(document).ready(async function () {
await window.addEventListener("load", function load() {
console.log("before load");
setControl(userInputSelector, _username);
setControl(passwordInputSelector, _password);
console.log("after load");
// $(loginButtonSelector).removeClass("disabled");
});
});
I want to tampermonkey script to login into a website. Enter username and password and click on submit button. So far I couldn't figure out how to do it.
Website: https://www.fandom.com/signin
Below code is what I have found by searching but isn't working.
// ==UserScript==
// #name Ghost
// #namespace http://tampermonkey.net/
// #version 0.1
// #description try to take over the world!
// #author You
// #match https://www.fandom.com/signin
// #grant none
// ==/UserScript==
function username() {
const firstInputElement = document.getElementsByID('loginUsername')[0];
firstInputElement.oninput = (event) => {
const inputValue = event.currentTarget.value;
firstInputElement.value = /^[a-z]+/i.test(inputValue) ? 'username123' : ''
};
}
username();
function password() {
const firstInputElement = document.getElementsByID('loginPassword')[0];
firstInputElement.oninput = (event) => {
const inputValue = event.currentTarget.value;
firstInputElement.value = /^[a-z]+/i.test(inputValue) ? 'password!123123' : ''
};
}
password();
function login() {
'use strict';
document.getElementsByClassName("form-submit")[0].click();
};
login();
document.getElementsByID is not a javascript function. You are looking for document.getElementByID singular. Javascript error - document.getElementsById is not a function
Also since you are only going to return one element instead of a list of elements the [0] in document.getElementByID('loginUsername')[0]; and document.getElementByID('loginPassword')[0]; is not needed.
The code below is part of a JavaScript UserScript I'm creating to add comment buttons on a specific subreddit on Reddit:
// ==UserScript==
// #name Assholedesign Repost Commenter
// #namespace Reddit
// #version 0.1
// #description Add repost buttons to r/assholedesign
// #author Duncan Yang
// #include https://*.reddit.com/r/assholedesign/comments/*
// #include http://*.reddit.com/r/assholedesign/comments/*
// #run-at document-start
// ==/UserScript==
window.addEventListener("DOMContentLoaded", function() {
var edit_form = document.querySelector("form > div.usertext-edit").parentNode;
var btns = edit_form.querySelector("div.usertext-edit > div.bottom-area > div.usertext-buttons");
var save_btn = btns.querySelector("button.save");
var edit_textbox = edit_form.querySelector("div.usertext-edit > div > textarea");
var repost_text = function(a) {
edit_textbox.value = a;
console.log(a);
}
try
{
var cancel_btn = btns.querySelector("button.cancel");
var a00 = document.createElement("button");
var a01 = document.createElement("button");
var a02 = document.createElement("button");
// This section of code is
a00.setAttribute("class", "save");
a00.innerHTML = "Repost";
a00.addEventListener("click", repost_text("Repost"));
a01.setAttribute("class", "save");
a01.innerHTML = "General Repostii";
a01.addEventListener("click", repost_text("[General Repostii](https://reddit.com/r/assholedesign/wiki/common_topics)"));
a02.setAttribute("class", "save");
a02.innerHTML = "Cold One";
a02.addEventListener("click", repost_text("[General Repostii, you are a cold one.](https://reddit.com/r/assholedesign/wiki/common_topics)"));
// where I am having problems.
btns.insertBefore(a00, cancel_btn);
btns.insertBefore(a01, cancel_btn);
btns.insertBefore(a02, cancel_btn);
}
catch (err)
{
console.log(err);
}
}, false);
This script is currently disabled, because it has a problem of automatically clicking one or more of the buttons right when the page is loaded. How could I fix this so that the false clicks are no more?
The problem is your addEventListener callback which runs immediately.
The callback in functions such as addEventListener, need to be a function that doesn't run immediately.
For example, the following will alert('Hello') as soon as the code is injected.
target.addEventListener('click', alert('Hello'));
However, the right way is to wrap it in a function like this:
target.addEventListener('click', function() { alert('Hello'); });
Above will only run after the event is fired.
In your code, the following will run immediately.
a00.addEventListener("click", repost_text("Repost"));
Change it to:
a00.addEventListener("click", function() { repost_text("Repost"); });
Or arrow function:
a00.addEventListener("click", () => repost_text("Repost"));
Just for info, if you didn't want to pass data to the function, the following would have been fine too:
a00.addEventListener("click", repost_text);
I am using the following excellent userscript (for Chrome, Chrome's Tampermonkey and Firefox Greasemonkey). It's supposed to display movie ratings next to each IMDb movie link, but it stopped working properly.
This is the complete script:
// ==UserScript==
// #name Add IMDb rating next to all IMDb links (+voter count)
// #author Ali
// #description Adds movie ratings and number of voters to any IMDb link. Modified version of http://userscripts.org/scripts/show/9174
// #include *
// #version 2013-05-12
// #namespace http://userscripts.org/scripts/show/96884
// #grant GM_xmlhttpRequest
// #downloadURL http://www.alibakir.com/upload/addimdbratings.js
// #updateURL http://www.alibakir.com/upload/addimdbratings.js
// ==/UserScript==
var IMDBpluginlinks = document.links;
var IMDBcontinueelement=document.createElement("button");
IMDBcontinueelement.innerHTML="Get rating";
function processIMDBLinks(s){
IMDBcontinueelement.style.display = 'none';
var r=0;
for (IMDBi = s; IMDBi < IMDBpluginlinks.length; IMDBi++) {
if (IMDBpluginlinks[IMDBi].href.indexOf("/title/") != -1 && IMDBpluginlinks[IMDBi].href.indexOf("imdb.") != -1){
if(r>300){
IMDBcontinueelement.onclick=function(){ processIMDBLinks(IMDBi); };
IMDBcontinueelement.style.display='inline';
IMDBpluginlinks[IMDBi].parentNode.insertBefore(IMDBcontinueelement, IMDBpluginlinks[IMDBi]);
break;
}
r++;
GM_xmlhttpRequest({
method: 'get',
headers: {
},
url: IMDBpluginlinks[IMDBi].href,
onload: function (IMDBi){return function(result) {
rating = result.responseText.match(/Users rated this (.*) \(/);
votes = result.responseText.match(/\((.*) votes\) -/);
IMDBpluginlinks[IMDBi].parentNode.insertBefore(document.createElement("span"), IMDBpluginlinks[IMDBi]).innerHTML = (rating ? "<b> [" + rating[1] + " - "+votes[1]+"] </b>" : "<b style='color: red;'>[NA] </b> ");
}}(IMDBi)
});
}
}
}
processIMDBLinks(0);
And this is how an example page looks at the moment:
As you can see, the script displays the results in the wrong places.
Why does it present them in the wrong place and how can it be fixed?
The issue causing your main complaint (results in the wrong places) is that GM_xmlhttpRequest operates asynchronously (which is good) and the onload was improperly constructed.
You either need to wrap the call to GM_xmlhttpRequest in a proper closure or provide a context in the GM_xmlhttpRequest call. (See the code below.)
For more information on why closures are needed, see this answer to the same type of problem.
Other big problems include AJAX-fetching dozens of improper links and firing on every page and iframe. Both of these slow the browser down quite a bit.
Don't use #include *. Even if you don't mind, other users of the script will. Add #include or #match lines for just the sites that you know have IMDB links.
I thought that I might want to use this script myself, so I started cleaning it up. You can read the inline comments and compare to the original script for an idea of some of the lesser problems. (Don't use onclick and always check match returns, etc.)
// ==UserScript==
// #name add IMDb rating next to all IMDb links (+voter count)
// #description Adds movie ratings and number of voters to any imdb link. Modified version of http://userscripts.org/scripts/show/96884
// #match *://www.imdb.com/*
// #grant GM_xmlhttpRequest
// ==/UserScript==
var maxLinksAtATime = 50; //-- pages can have 100's of links to fetch. Don't spam server or browser.
var fetchedLinkCnt = 0;
function processIMDB_Links () {
//--- Get only links that could be to IMBD movie/TV pages.
var linksToIMBD_Shows = document.querySelectorAll ("a[href*='/title/']");
for (var J = 0, L = linksToIMBD_Shows.length; J < L; J++) {
var currentLink = linksToIMBD_Shows[J];
/*--- Strict tests for the correct IMDB link to keep from spamming the page
with erroneous results.
*/
if ( ! /^(?:www\.)?IMDB\.com$/i.test (currentLink.hostname)
|| ! /^\/title\/tt\d+\/?$/i.test (currentLink.pathname)
)
continue;
if (! currentLink.getAttribute ("data-gm-fetched") ){
if (fetchedLinkCnt >= maxLinksAtATime){
//--- Position the "continue" button.
continueBttn.style.display = 'inline';
currentLink.parentNode.insertBefore (continueBttn, currentLink);
break;
}
fetchTargetLink (currentLink); //-- AJAX-in the ratings for a given link.
//---Mark the link with a data attribute, so we know it's been fetched.
currentLink.setAttribute ("data-gm-fetched", "true");
fetchedLinkCnt++;
}
}
}
function fetchTargetLink (linkNode) {
//--- This function provides a closure so that the callbacks can work correctly.
/*--- Must either call AJAX in a closure or pass a context.
But Tampermonkey does not implement context correctly!
(Tries to JSON serialize a DOM node.)
*/
GM_xmlhttpRequest ( {
method: 'get',
url: linkNode.href,
//context: linkNode,
onload: function (response) {
prependIMDB_Rating (response, linkNode);
},
onload: function (response) {
prependIMDB_Rating (response, linkNode);
},
onabort: function (response) {
prependIMDB_Rating (response, linkNode);
}
} );
}
function prependIMDB_Rating (resp, targetLink) {
var isError = true;
var ratingTxt = "** Unknown Error!";
if (resp.status != 200 && resp.status != 304) {
ratingTxt = '** ' + resp.status + ' Error!';
}
else {
if (/\(awaiting \d+ votes\)|\(voting begins after release\)|in development/i.test (resp.responseText) ) {
ratingTxt = "NR";
isError = false;
}
else {
var ratingM = resp.responseText.match (/Users rated this (.*) \(/);
var votesM = resp.responseText.match (/\((.*) votes\) -/);
if (ratingM && ratingM.length > 1 && votesM && votesM.length > 1) {
isError = false;
ratingTxt = ratingM[1] + " - " + votesM[1];
}
}
}
var resltSpan = document.createElement ("span");
resltSpan.innerHTML = '<b> [' + ratingTxt + '] </b> ';
if (isError)
resltSpan.style.color = 'red';
//var targetLink = resp.context;
//console.log ("targetLink: ", targetLink);
targetLink.parentNode.insertBefore (resltSpan, targetLink);
}
//--- Create the continue button
var continueBttn = document.createElement ("button");
continueBttn.innerHTML = "Get ratings";
continueBttn.addEventListener ("click", function (){
fetchedLinkCnt = 0;
continueBttn.style.display = 'none';
processIMDB_Links ();
},
false
);
processIMDB_Links ();
I'm making a Greasemonkey script to add download links beside videos on cnn.com.
I used a saved version of the HTML page to test my script and was able to get it to work perfectly. Then when I put the javascript into Greasemonkey and tried it on the actual site, it didn't work.
This is the not the full script, but the part of the script with the problem. It is simply supposed to add a link at the bottom of every div with the "sec_video_box" class (as seen in the picture).
// ==UserScript==
// #name CNN Download
// #namespace Cool
// #description CNN Download
// #include http://*cnn.com/video/*
// ==/UserScript==
var getClass = function(clssName, rootNode /*optional*/){
var root = rootNode || document,
clssEls = [],
elems,
clssReg = new RegExp("\\b"+clssName+"\\b");
// use the built in getElementsByClassName if available
if (document.getElementsByClassName){
return root.getElementsByClassName(clssName);
}
// otherwise loop through all(*) nodes and add matches to clssEls
elems = root.getElementsByTagName('*');
for (var i = 0, len = elems.length; i < len; i+=1){
if (clssReg.test(elems[i].className)) clssEls.push(elems[i])
}
return clssEls;
};
function insertlinks() {
var boxes = getClass("sec_video_box");
for (i=0; i<boxes.length; i++) {
var theboxid = boxes[i].getAttribute("id");
document.getElementById(theboxid).innerHTML = document.getElementById(theboxid).innerHTML + 'link';
}
}
window.onload = insertlinks ();
Can someone tell me what I'm doing wrong?
The 3 biggest problems with that script are:
You can't use window.onload that way; see GM Pitfall #2: Event Handlers. Always use addEventListener() or jQuery.
Those video objects are AJAXed-in after the document loads, anyway.
Those video objects can change, via AJAX; so you'll want to monitor for new objects.
There are some minor issues but first note that the entire existing script can be simplified to this, with jQuery:
// ==UserScript==
// #name CNN Download
// #namespace Cool
// #description CNN Download
// #include http://*cnn.com/video/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==
function insertlinks () {
var boxes = $(".sec_video_box");
boxes.each ( function () {
var theboxid = this.id;
$(this).append ('link');
} );
}
$(window).load (insertlinks);
(Important: This sample code will still not work.)
Handling the AJAX issues, it becomes:
// ==UserScript==
// #name CNN Download
// #namespace Cool
// #description CNN Download
// #include http://*cnn.com/video/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==
function insertlink (jNode) {
var theboxid = jNode.attr ('id');
jNode.append ('link');
}
waitForKeyElements (".sec_video_box", insertlink, false);
function waitForKeyElements (
selectorTxt, /* Required: The jQuery selector string that
specifies the desired element(s).
*/
actionFunction, /* Required: The code to run when elements are
found. It is passed a jNode to the matched
element.
*/
bWaitOnce, /* Optional: If false, will continue to scan for
new elements even after the first match is
found.
*/
iframeSelector /* Optional: If set, identifies the iframe to
search.
*/
)
{
var targetNodes, btargetsFound;
if (typeof iframeSelector == "undefined")
targetNodes = $(selectorTxt);
else
targetNodes = $(iframeSelector).contents ()
.find (selectorTxt);
if (targetNodes && targetNodes.length > 0) {
/*--- Found target node(s). Go through each and act if they
are new.
*/
targetNodes.each ( function () {
var jThis = $(this);
var alreadyFound = jThis.data ('alreadyFound') || false;
if (!alreadyFound) {
//--- Call the payload function.
actionFunction (jThis);
jThis.data ('alreadyFound', true);
}
} );
btargetsFound = true;
}
else {
btargetsFound = false;
}
//--- Get the timer-control variable for this selector.
var controlObj = waitForKeyElements.controlObj || {};
var controlKey = selectorTxt.replace (/[^\w]/g, "_");
var timeControl = controlObj [controlKey];
//--- Now set or clear the timer as appropriate.
if (btargetsFound && bWaitOnce && timeControl) {
//--- The only condition where we need to clear the timer.
clearInterval (timeControl);
delete controlObj [controlKey]
}
else {
//--- Set a timer, if needed.
if ( ! timeControl) {
timeControl = setInterval ( function () {
waitForKeyElements ( selectorTxt,
actionFunction,
bWaitOnce,
iframeSelector
);
},
500
);
controlObj [controlKey] = timeControl;
}
}
waitForKeyElements.controlObj = controlObj;
}
(Which does work.)
window.onload = insertlinks;
Remove the (), they cause the function to run immediately and the return value (null in this case) is assigned to onload. Locally, this is fine since loading is near-instant. Online, however, it will fail.