Download All PDFs with Button

Adds a button to download all PDFs from a webpage, including those in iframes

// ==UserScript==
// @name         Download All PDFs with Button
// @namespace    SWScripts
// @version      1
// @description  Adds a button to download all PDFs from a webpage, including those in iframes
// @author       BN_LOS
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Function to download a file
    function downloadFile(url, filename) {
        var link = document.createElement('a');
        link.href = url;
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    // Function to find and download all PDFs in a given document
    function downloadAllPDFs(doc) {
        var links = doc.getElementsByTagName('a');
        for (var i = 0; i < links.length; i++) {
            if (links[i].href.endsWith('.pdf')) {
                var url = links[i].href;
                var filename = url.split('/').pop();
                downloadFile(url, filename);
            }
        }
    }

    // Function to handle iframes
    function handleIframes() {
        var iframes = document.getElementsByTagName('iframe');
        for (var i = 0; i < iframes.length; i++) {
            try {
                var iframeDoc = iframes[i].contentDocument || iframes[i].contentWindow.document;
                downloadAllPDFs(iframeDoc);
            } catch (e) {
                console.log('Cannot access iframe content:', e);
            }
        }
    }

    // Function to create and add the button
    function createButton() {
        var button = document.createElement('button');
        button.innerHTML = 'Download it MAM';
        button.style.position = 'fixed';
        button.style.top = '10px';
        button.style.right = '10px';
        button.style.zIndex = 10000;
        button.style.padding = '10px 20px';
        button.style.backgroundColor = '#007bff';
        button.style.color = '#ffffff';
        button.style.border = 'none';
        button.style.borderRadius = '5px';
        button.style.cursor = 'pointer';

        button.addEventListener('click', function() {
            downloadAllPDFs(document);
            handleIframes();
        });

        document.body.appendChild(button);
    }

    // Run the createButton function when the page loads
    window.addEventListener('load', createButton);
})();