Search code examples
javascripttampermonkeyuserscripts

userscript (violentmonkey) script runs on first page, does not run on subsequent pages


I am trying to make a userscript that will open the invoices from Amazon in new tabs, so that I can try to categorize my spending better. It's a PITA.

Here's the link: https://www.amazon.com/cpe/yourpayments/transactions

My script works on the first page, but when I press the "Next Page" button at the bottom and the script doesn't run on the new pages. I've tried the different @run-at options but they don't make a difference.

I think is due to some sort of dynamic generation or loading of the subsequent pages, but I don't know how to hook that and I don't seem to be phrasing my search terms in a way that I'm getting hints on how to help it.

// ==UserScript==
// @name        Open payment invoices in new tab
// @namespace   Violentmonkey Scripts
// @match       https://www.amazon.com/cpe/yourpayments/transactions*
// @grant       none
// @version     1.0
// @author      -
// @description 2/5/2024, 12:24:35 PM
// ==/UserScript==


var TargetLink = document.querySelectorAll('.a-span12 a');

var len = TargetLink.length;

for(var i=0; i<len; i++)
{
   TargetLink[i].setAttribute('target', '_blank');
}

Solution

  • Here is the code that worked. Thanks to @wOxxOm for pointing the way.

    // ==UserScript==
    // @name        Open payment invoices in new tab
    // @namespace   Violentmonkey Scripts
    // @match       https://www.amazon.com/*
    // @grant       none
    // @version     1.0
    // @author      -
    // @description 2/5/2024, 12:24:35 PM
    // ==/UserScript==
    
    
    window.addEventListener("click", function(evnt){
        if (evnt.target.matches('.a-span12 a'))  {
          evnt.target.setAttribute('target', '_blank');
        }
    });