Search code examples
javascripttampermonkey

How to convert a specific onclick popup link to direct link href with tampermonkey?


I am trying to create a tampermonkey script to modify a single link in a specific webpage. I tried almost all the suggestions but couldn't go anywhere with my newly found js skills. Take this:

<p class="g2 gsp"><img src="https://ptt.org/t/ss.gif"> <a href="#" onclick="return popUp('https://somelink',480,320)">Maka Pato</a></p>

and convert to this:

<p class="g2 gsp"><img src="https://ptt.org/t/ss.gif"> <a href="https://somelink">Maka Pato</a></p>

Basically, remove onclick popup and point href to a link instad of #

I have managed to extract "https://somelink" but I couldn't manage to modify the original.

//function to extract the link
function xpathSelector(xpath) {
    return document.evaluate(xpath, document.body, null, XPathResult.FIRST_ORDERED_NODE_TYPE,
        null).singleNodeValue;
};
//save the link
var mak = xpathSelector('.//a[text() = "Maka Pato"]');

var x = document.getElementsByClassName("g2 gsp")[0]

Solution

  • You can extract the value with getAttribute and a regular expression, then remove it with removeAttribute and set the href.

    function xpathSelector(xpath) {
        return document.evaluate(xpath, document.body, null, XPathResult.FIRST_ORDERED_NODE_TYPE,
            null).singleNodeValue
    }
    
    const mak = xpathSelector('.//a[text() = "Maka Pato"]')
    
    const x = document.getElementsByClassName("g2 gsp")[0]
    
    // parentheses create a capture inside the match
    // index 0 is the full match, then indexes 1+ are each capture
    const url = mak.getAttribute('onclick').match(/'(https?:\/\/\S+)'/)[1]
    
    mak.removeAttribute('onclick')
    
    mak.href = url
    
    console.log(x.outerHTML)
    <p class="g2 gsp"><img src="https://ptt.org/t/ss.gif"> <a href="#" onclick="return popUp('https://somelink',480,320)">Maka Pato</a></p>