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 ();
Related
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);
Im using tampermonkey to make a script in js to copy and password and open the site for that password so i can easily paste it in. However, I am having some trouble with the copying part. from what i see there is a need user interaction to copy something and i understand this is for security purposes and people dont want random things going into their clipboard. Is there a way to turn this off in my browser (Chrome). If not i have one more idea. I use a key combo (CTRL DOWN ARROW) to activate the script to copy and open a new tab and i use that user interaction to copy the text.
This is what i have so far
(function() {
'use strict';
function KeyPress(e) {
var evtobj = window.event ? event : e
if (evtobj.keyCode == 40 && evtobj.ctrlKey) {
var aTags = document.getElementsByTagName("td");
var searchText = "WP-Admin Password";
//Finding The Password
var pass;
var found1;
for (var i = 0; i < aTags.length; i++) {
if (aTags[i].textContent == searchText) {
//found 1 is the element that has the search phrase
found1 = aTags[i];
//This is where im trying to copy to my clipboard the text content.
found1.nextSibling.firstChild.textContent; //wp Admin Password
;
break;
}
}
//Finding a Dev url if they have one
var pass3;
var found3;
var dev;
for (var k = 0; k < aTags.length; k++) {
if (aTags[k].textContent == "Development URL") {
found3 = aTags[k];
if (found3.nextSibling.firstChild.firstChild !== "") {
found3.nextSibling.firstChild.firstChild.click();
} else {
dev = false;
}
break;
}
}
//fining the live url and going to it
var pass2;
var found2;
if (!dev) {
for (var j = 0; j < aTags.length; j++) {
if (aTags[j].textContent == "Website") {
found2 = aTags[j];
found2.nextSibling.firstChild.firstChild.click();; //url
break;
}
}
}
}
}
document.onkeydown = KeyPress;
})();
Try GM_setClipboard
Detail at: https://github.com/scriptish/scriptish/wiki/GM_setClipboard
// ==UserScript==
// #name _YOUR_SCRIPT_NAME
// #include http://YOUR_SERVER.COM/YOUR_PATH/*
// #grant GM_setClipboard
// ==/UserScript==
GM_setClipboard ("The clipboard now contains this sentence.");
Alright I figured out a solution
This solution ONLY works if you are using tamper monkey or grease monkey
you can add
// #grant GM_setClipboard
To your script and it will allow you to use the Gm_setclipboard() func. to copy things to clipboard.
I am just a beginner in jquery. I have used the tooltip script from this site. http://www.twinhelix.com/dhtml/supernote/demo/#demo4 .They used the following function to close the tooltip on clicking the close button.
<script type="text/javascript">
// SuperNote setup: Declare a new SuperNote object and pass the name used to
// identify notes in the document, and a config variable hash if you want to
// override any default settings.
var supernote = new SuperNote('supernote', {});
// Available config options are:
//allowNesting: true/false // Whether to allow triggers within triggers.
//cssProp: 'visibility' // CSS property used to show/hide notes and values.
//cssVis: 'inherit'
//cssHid: 'hidden'
//IESelectBoxFix: true/false // Enables the IFRAME select-box-covering fix.
//showDelay: 0 // Millisecond delays.
//hideDelay: 500
//animInSpeed: 0.1 // Animation speeds, from 0.0 to 1.0; 1.0 disables.
//animOutSpeed: 0.1
// You can pass several to your "new SuperNote()" command like so:
//{ name: value, name2: value2, name3: value3 }
// All the script from this point on is optional!
// Optional animation setup: passed element and 0.0-1.0 animation progress.
// You can have as many custom animations in a note object as you want.
function animFade(ref, counter)
{
//counter = Math.min(counter, 0.9); // Uncomment to make notes translucent.
var f = ref.filters, done = (counter == 1);
if (f)
{
if (!done && ref.style.filter.indexOf("alpha") == -1)
ref.style.filter += ' alpha(opacity=' + (counter * 100) + ')';
else if (f.length && f.alpha) with (f.alpha)
{
if (done) enabled = false;
else { opacity = (counter * 100); enabled=true }
}
}
else ref.style.opacity = ref.style.MozOpacity = counter*0.999;
};
supernote.animations[supernote.animations.length] = animFade;
// Optional custom note "close" button handler extension used in this example.
// This picks up click on CLASS="note-close" elements within CLASS="snb-pinned"
// notes, and closes the note when they are clicked.
// It can be deleted if you're not using it.
addEvent(document, 'click', function(evt)
{
var elm = evt.target || evt.srcElement, closeBtn, note;
while (elm)
{
if ((/note-close/).test(elm.className)) closeBtn = elm;
if ((/snb-pinned/).test(elm.className)) { note = elm; break }
elm = elm.parentNode;
}
if (closeBtn && note)
{
var noteData = note.id.match(/([a-z_\-0-9]+)-note-([a-z_\-0-9]+)/i);
for (var i = 0; i < SuperNote.instances.length; i++)
if (SuperNote.instances[i].myName == noteData[1])
{
setTimeout('SuperNote.instances[' + i + '].setVis("' + noteData[2] +
'", false, true)', 100);
cancelEvent(evt);
}
}
});
// Extending the script: you can capture mouse events on note show and hide.
// To get a reference to a note, use 'this.notes[noteID]' within a function.
// It has properties like 'ref' (the note element), 'trigRef' (its trigger),
// 'click' (whether its shows on click or not), 'visible' and 'animating'.
addEvent(supernote, 'show', function(noteID)
{
// Do cool stuff here!
});
addEvent(supernote, 'hide', function(noteID)
{
// Do cool stuff here!
});
// If you want draggable notes, feel free to download the "DragResize" script
// from my website http://www.twinhelix.com -- it's a nice addition :).
</script>
I have tried to edit this function for closing the tooltip on clicking the esckey too. But i couldn't. How can i modify the function?
I found myself reading the same questions over and over, so I wanted a way to hide questions.
I have a script to does what is suppose to do, however it cripples existing javascript, such as the upvote button and adding tags when asking questions. Does anyone know why this is happening, or how to fix it?
Edit: oh, in the error console I am getting:
Error: $ is not a function
Source File: http://cdn.sstatic.net/js/stub.js?v=b7084478a9a4
Line: 1
Edit2:
The solution
(fixed #17/06/2014)
// ==UserScript==
// #name StackOverflowHidePosts
// #namespace StackOverflowHidePosts
// #description Allows you to hide questions on Stack Overflow.
// #include http://stackoverflow.com/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
// ==/UserScript==
var idListString = GM_getValue('idList', '');
var idList = idListString.split(',');
GM_setValue('idList', idList.join(','));
function getId (idString)
{
return idString.split('-')[2];
}
function removeQuestion (e)
{
var id = getId(e.data.questionSummaryDiv.id);
$(e.data.questionSummaryDiv).hide(250);
idList.push(id);
setTimeout(function() {
GM_setValue('idList', idList.join(','));
}, 0);
return false;
}
$('div.question-summary').each(function (index, questionSummaryDiv)
{
var id = getId(questionSummaryDiv.id);
if (idList.indexOf(id) != -1)
{
$(questionSummaryDiv).hide();
return;
}
var link = $('<a><em>(Hide Post)</em></a>');
link.attr('href', '#' + questionSummaryDiv.id);
link.click({questionSummaryDiv: questionSummaryDiv}, removeQuestion);
$('div.started', questionSummaryDiv).append(link);
});
Never inject JS if you don't have to, and never use the page's jQuery in FF GM -- that's the main source of errors in this case.
The entire script should be:
// ==UserScript==
// #name StackOverflowImTooStupidMarker
// #namespace StackOverflowImTooStupidMarker
// #description Allows you to hide questions on Stack Overflow when you can't answer them.
// #include http://stackoverflow.com/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==
var idListString = GM_getValue('idList', '');
var idList = idListString.split(',');
GM_setValue('idList', idList.join(','));
function getId (idString)
{
return idString.split('-')[2];
}
function removeQuestion (e)
{
var id = getId(e.data.questionSummaryDiv.id);
$(e.data.questionSummaryDiv).hide(250);
idList.push(id);
setTimeout(function() {
GM_setValue('idList', idList.join(','));
}, 0);
return false;
}
$('div.question-summary').each(function (index, questionSummaryDiv)
{
var id = getId(questionSummaryDiv.id);
if (idList.indexOf(id) != -1)
{
$(questionSummaryDiv).hide();
return;
}
var link = $('<a><em>(Too Stupid)</em></a>');
link.attr('href', '#' + questionSummaryDiv.id);
link.click({questionSummaryDiv: questionSummaryDiv}, removeQuestion);
$('div.started', questionSummaryDiv).append(link);
});
That script attempts to include jQuery first thing:
(function()
{
if (typeof unsafeWindow.jQuery == 'undefined')
{
var GM_Head = document.getElementsByTagName('head')[0] || document.documentElement, GM_JQ = document.createElement('script');
GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
GM_JQ.type = 'text/javascript';
GM_JQ.async = true;
GM_Head.insertBefore(GM_JQ, GM_Head.firstChild);
}
GM_wait();
})();
This issue there is that jQuery is guaranteed to be loaded on Stack Overflow to begin with...if it's not present you have much bigger issues. That whole jQuery replacement shouldn't happen, as it's both impacting already registered plugins (nuking then) and using a newer version of jQuery that Stack Exchange currently does, meaning other potentially breaking changes as well.
Since the script needs none of the latest functionality, that entire chunk above should simply be:
GM_wait();
For the other issues, there are a few more $ conflicts...but you still want to be safe with respect to load order here. Here's a cheaper and still safe version that...well, works:
var idListString = GM_getValue('idList', '');
var idList = idListString.split(',');
GM_setValue('idList', idList.join(','));
GM_wait();
function GM_wait() {
if (typeof unsafeWindow.jQuery == 'undefined') {
window.setTimeout(GM_wait, 100);
return;
}
unsafeWindow.jQuery(function($) {
var link = $('<em>(Too Stupid)</em>').click(removeQuestion);
$('div.question-summary').each(function (index, questionSummaryDiv) {
var id = getId(questionSummaryDiv.id);
if (idList.indexOf(id) != -1) {
$(questionSummaryDiv).hide();
} else {
$('div.started', questionSummaryDiv).append(link.clone(true));
}
});
});
}
function getId (idString) {
return idString.split('-')[2];
}
function removeQuestion () {
var q = unsafeWindow.jQuery(this).closest("div.question-summary").hide(250);
idList.push(getId(q.attr("id")));
setTimeout(function() {
GM_setValue('idList', idList.join(','));
}, 0);
return false;
}
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.