greenbeanyum / Download From Browse

// ==UserScript==
// @name         Download From Browse
// @description  Adds download button to browse.php
// @version      0.0.1
// @updateURL    https://openuserjs.org/meta/greenbeanyum/Download_From_Browse.meta.js
// @downloadURL  https://openuserjs.org/install/greenbeanyum/Download_From_Browse.user.js
// @license      GPL-3.0-or-later
// @match        https://extremebits.net/browse.php*
// @icon         https://extremebits.net/img/favicon.png
// ==/UserScript==

// ==OpenUserJS==
// @author greenbeanyum
// ==/OpenUserJS==


/*jshint esversion: 6 */

// Create elements
const getId = /.*id=(.*?)\D/;

function addListener() {
    let rows = document.querySelectorAll('table tbody tr');
    // Check if the table is loaded yet. If not, wait 100ms and try again.
    if (rows == null) {
        setTimeout(function () { addListener() }, 100);
    }
    if (rows) {
        rows.forEach(tr => {
            // Add DL to the header
            if (tr.classList.contains("colhead")){
                let headTd = document.createElement("td");
                headTd.innerText = "DL";
                tr.insertCell(2).appendChild(headTd);
            }
            // Accessing the second <td> element
            let secondTd = tr.children[1];
            if (secondTd && secondTd.hasAttribute('style')) {
                var styleText = secondTd.getAttribute("style");
                if (styleText === "text-align:left;") {
                    let nestedHref = secondTd.querySelector('a').href;
                    if (nestedHref.includes("id=")) {
                        let id = getId.exec(nestedHref)[1];
                        let downloadLink = document.createElement('a');
                        let downloadIcon = document.createElement('img');
                        downloadIcon.src = 'img/disk.png';
                        downloadIcon.alt = 'Download!';
                        downloadLink.href = `download.php?id=${id}`;
                        downloadLink.appendChild(downloadIcon);
                        let newTd = document.createElement('td');
                        newTd.appendChild(downloadLink);
                        tr.insertCell(2).appendChild(newTd);
                    }
                }
            }
        });
    }
}

addListener();