jquerygreasemonkey-4

Finding URL on a page by giving a search string


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&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=9&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwjltNj8w9ngAhVNip4KHQdJDdQQFjAIegQIDBAB&amp;url=https%3A%2F%2Fwww.merriam-webster.com%2Fdictionary%2Fcookie-cutter&amp;usg=AOvVaw3PbUvVz6q2bSTgondh9KCq" onmousedown="return rwt(this,'','','','9','AOvVaw3PbUvVz6q2bSTgondh9KCq','','2ahUKEwjltNj8w9ngAhVNip4KHQdJDdQQFjAIegQIDBAB','','',event)" data-cthref="/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=9&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwjltNj8w9ngAhVNip4KHQdJDdQQFjAIegQIDBAB&amp;url=https%3A%2F%2Fwww.merriam-webster.com%2Fdictionary%2Fcookie-cutter&amp;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?


Solution

  • 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();                    
    }