Set Value to input field but fail to trigger validation using tampermonkey - javascript

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");
});
});

Related

Why does Copy button copy 'undefined' instead of copying value from html dom?

I'm trying to make my own user script for https://mlwbd.ltd/movie/don-2022
I wish to copy the value of specified hidden input
preTag = document.getElementsByName("FU");
p = preTag[0];
console.log(p);
Ekra = document.getElementsByClassName("linktabs");
q = Ekra[0];
console.log(q);
function copy(ele) {
let temp = document.createElement('textarea');
document.body.appendChild(temp);
temp.value = ele.textContent;
temp.select();
document.execCommand('copy');
temp.remove();
}
btn = document.createElement("button");
btn.innerHTML = "copy"
btn.onclick = function(){
copy("p");
};
q.insertBefore(document.createElement("br"), q.childNodes[0])
q.insertBefore(btn, q.childNodes[0])
The Html code is
input type="hidden" name="FU" value="https://songslyric.site/links/46905/"
I want to copy the Value of name="FU" when I click the button.
The code I pasted is created from google chrome snippets.
Please help me.
Try this on your other question:
// ==UserScript==
// #name adsgo.digital
// #namespace http://tampermonkey.net/
// #version 0.1
// #include https://adsgo.digital/
// #include https://adsgo.digital/*
// #grant none
// ==/UserScript==
(function() {
'use strict';
const $ = document.querySelector.bind(document);
$('body').insertAdjacentHTML('beforeend', init_css() );
setTimeout(() => {
$('#mybutt').addEventListener('click', () => {
//alert('hi');
const fu = $('.posts-dynamic.posts-container form input[name=FU6]');
//console.log(fu.value);
copy2clip(fu);
});
},500);
})();
function init_css(){
return `
<button id="mybutt">Copy2Clip</button>
<style id="myInitCss">
#mybutt{position:absolute;top:90px;left:45%;height:30px;width:120px;}
#mybutt{background:#0073ea;color:white;padding-top:5px;text-align:center;}
#mybutt{z-index:99999;}
</style>
`;
}
function copy2clip(ele) {
let temp = document.createElement('textarea');
document.body.appendChild(temp);
temp.value = ele.value;
temp.select();
document.execCommand('copy');
temp.remove();
}
Notes:
You can compare this answer to the previous one and you'll notice that only one line has changed.
The topic to study to understand how to reference the HTML scaffolding as I did is called: "CSS Selectors". The JavaScript querySelector() directive uses CSS selectors to specifically target the desired HTML tag.
This will get you started:
// ==UserScript==
// #name mlwbd.ltd
// #namespace http://tampermonkey.net/
// #version 0.1
// #match https://mlwbd.ltd/movie/*
// #grant none
// ==/UserScript==
(function() {
'use strict';
const $ = document.querySelector.bind(document);
$('body').insertAdjacentHTML('beforeend', init_css() );
setTimeout(() => {
$('#mybutt').addEventListener('click', () => {
//alert('hi');
const fu = $('#download table form input[name=FU]');
//console.log(fu.value);
copy2clip(fu);
});
},500);
})();
function init_css(){
return `
<button id="mybutt">Copy2Clip</button>
<style id="myInitCss">
#mybutt{position:absolute;top:90px;left:45%;height:30px;width:120px;}
#mybutt{background:#0073ea;color:white;padding-top:5px;text-align:center;}
#mybutt{z-index:99999;}
</style>
`;
}
function copy2clip(ele) {
let temp = document.createElement('textarea');
document.body.appendChild(temp);
temp.value = ele.value;
temp.select();
document.execCommand('copy');
temp.remove();
}
Notes:
Despite the $ character, this code is not jQuery (it is vanilla javascript)
You can uncomment the alert() and console.log to see how things are working at that point.

Tempermonkey script: fandom login

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.

Stop UserScript from automatically clicking

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);

Why Javascript keep on running even after array finished in pop()

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);

Works as javascript, but doesn't work as a Greasemonkey script?

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.

Categories