I would like to click a buy now button using greasemonkey.
// ==UserScript==
// @name script
// @namespace sc
// @include *
// @version 1
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant GM_addStyle
// ==/UserScript==
waitForKeyElements ("#buy-now", triggerMostButtons);
function triggerMostButtons (jNode) {
triggerMouseEvent (jNode[0], "mouseover");
triggerMouseEvent (jNode[0], "mousedown");
triggerMouseEvent (jNode[0], "click");
triggerMouseEvent (jNode[0], "mouseup");
}
function triggerMouseEvent (node, eventType) {
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent (eventType, true, true);
node.dispatchEvent (clickEvent);
}
Html of the buttons:
<div class="buy-now"><a data-spm-anchor-id="0.0.0.0" data-widget-cid="widget-14" tabindex="-1" id="buy-now" class="buy-now-btn" href="#">Buy Now</a><a id="add-to-cart" class="add-to-cart-btn" href="#">Add to Cart</a></div>
I have tried other codes like
var TargetLink = $("a:contains('Ik neem er een!')")
if (TargetLink.length)
window.location.assign (TargetLink[0].href);
and
waitForKeyElements ("a.class:contains('buy-now-btn')", clickOnFollowButton);
function clickOnFollowButton (jNode) {
var clickEvent = document.createEvent ('MouseEvents');
clickEvent.initEvent ('click', true, true);
jNode[0].dispatchEvent (clickEvent);
}
Could someone give me an explenation what to put in the waitForKeyElements as first parameter for clicking the button?
I wonder if the code below is what you want.
Demo
It seems some scripts have not been loaded on the page you mentioned at the time of DOMContentLoaded. Adding a delay solved the problem for me, that is,