Search code examples
javascriptgreasemonkeywindow.openwindow.location

How do I modify an existing button's onclick to open a new tab using Greasemonkey?


I have a bunch of buttons on a page that I want to cause to open in a new tab because I'm on dialup and I hate having to hit the back button and wait for the page to load again before I can click the next button.

The button code looks like this:

<button onclick="window.location.href='?act=stock&amp;i=273';return false;" class="wide">Stock in Shop</button>

<button onclick="window.location.href='?act=stock&amp;i=287';return false;" class="wide">Stock in Shop</button>

<button onclick="window.location.href='?act=stock&amp;i=193';return false;" class="wide">Stock in Shop</button>


I think I somehow need to change window.location.href to window.open() and the URL to start with http://www.felisfire.com/possessions? then add the href part from the original onclick... but I have no idea how to go about this and searching 3 hours for answers hasn't helped...

Please! How would I change those buttons with Greasemonkey?


Possible code so far, but I don't think it works:

var buttons = document.getElementsByClassName('wide');
for (var i = 0; i < buttons.length; i++) {
  buttons[i]=button.onclick="window.open('http://www.felisfire.com/possessions + *how do I get the part I need from the original onclick?*');">Stock in Shop</button>

}

Solution

  • Be careful when working with onclick from a userscript; see the Greasemonkey pitfalls.

    Use jQuery or querySelectorAll to get the buttons and then use jQuery or addEventListener to set your new click handler.

    The following extracts the key bit from the old onclick, stores it in a data attribute and replaces the onclick with a web 2.0 handler:

    var stockBtns   = document.querySelectorAll ("button.wide[onclick*='window']");
    
    for (var J = stockBtns.length - 1;  J >= 0;  --J) {
        var oldClick    = stockBtns[J].getAttribute ("onclick");
        var payloadMtch = oldClick.match (/(act=.+?)';return/);
        if (payloadMtch  &&  payloadMtch.length > 1) {
            var payload = payloadMtch[1];
            //-- Don't use onclick!
            stockBtns[J].removeAttribute ("onclick");
            //-- Store payload value.
            stockBtns[J].setAttribute ("data-destQry", payload);
    
            //-- Activate click the proper way, especially for userscripts
            stockBtns[J].addEventListener ("click", openNewTab, false);
        }
    }
    
    function openNewTab (zEvent) {
        var baseURL     = "http://www.felisfire.com/possessions"
        /* Or be smart and use:
        var baseURL     = location.protocol + "//"
                        + location.host
                        + location.pathname
                        ;
        */
        window.open (baseURL + "?" + zEvent.target.getAttribute ("data-destQry") );
        return false;
    }