I am learning to use Greasemonkey on Firefox.
On a Google search results page, I am trying to find a link and click on it.
I gave the search query "cookie cutter".. Among the results, there is a result for the url merriam-webster.com which I am trying to find and click.
This is what I have written so far.
function clickURLWithText () {
var links = $('a[href*="merriam-webster.com"]');
var randomNum = Math.floor(Math.random()*links.length);
var targetLink = links.get(randomNum);
triggerMouseEvent (targetLink, "click");
}
function triggerMouseEvent (node, eventType) {
// code comes here
}
However it seems Google search scrambles the url like this:
<a href="/url?sa=t&rct=j&q=&esrc=s&source=web&cd=9&cad=rja&uact=8&ved=2ahUKEwjltNj8w9ngAhVNip4KHQdJDdQQFjAIegQIDBAB&url=https%3A%2F%2Fwww.merriam-webster.com%2Fdictionary%2Fcookie-cutter&usg=AOvVaw3PbUvVz6q2bSTgondh9KCq" onmousedown="return rwt(this,'','','','9','AOvVaw3PbUvVz6q2bSTgondh9KCq','','2ahUKEwjltNj8w9ngAhVNip4KHQdJDdQQFjAIegQIDBAB','','',event)" data-cthref="/url?sa=t&rct=j&q=&esrc=s&source=web&cd=9&cad=rja&uact=8&ved=2ahUKEwjltNj8w9ngAhVNip4KHQdJDdQQFjAIegQIDBAB&url=https%3A%2F%2Fwww.merriam-webster.com%2Fdictionary%2Fcookie-cutter&usg=AOvVaw3PbUvVz6q2bSTgondh9KCq">
<h3 class="LC20lb">Cookie-cutter | Definition of Cookie-cutter by Merriam-Webster</h3>
<br>
<div class="TbwUpd"><cite class="iUh30">https://www.merriam-webster.com/dictionary/cookie-cutter</cite></div>
</a>
In this case, how do I find merriam-webster.com and click on the href part of it?
It seems jQuery is not defined on Google search results page (type $.fn.jquery in the console). Hence you can change your code to:
function clickURLWithText () {
var links = document.querySelectorAll('a[href*="merriam-webster.com"]');
var randomNum = Math.floor(Math.random()*links.length);
var targetLink = links[randomNum];;
targetLink.click();
}