PageSourceSearch

https://ren.pt/js/utils/downloadtablefiles.js

js ren.pt collected 2026-09-24 09:23:28 UTC 3,715 bytes, 108 lines download raw bytes

1/*eslint-disable no-unused-vars*/
2document.addEventListener('DOMContentLoaded', function () {
3
4    document.addEventListener('click', function (e) {
5        const downloadBtn = e.target.closest('.btn-ren--table-dowload, .btn-ren--table-dowload-dark');
6        if (downloadBtn) {
7            e.preventDefault();
8            const tableId = downloadBtn.getAttribute('data-table-id');
9            if (tableId) {
10                DownloadTableFiles(tableId);
11            }
12        }
13    });
14});
15
16async function DownloadTableFiles(tableId) {
17    const table = document.getElementById(tableId);
18    if (!table) return;
19
20    const rows = table.querySelectorAll('tbody tr');
21    const fileUrls = [];
22
23    rows.forEach(row => {
24        const lastCell = row.querySelector('td:last-child');
25        if (lastCell) {
26            const links = lastCell.querySelectorAll('a[href]');
27            links.forEach(link => {
28                const url = link.getAttribute('href');
29                if (url && url.trim() !== '') {
30                    fileUrls.push(url);
31                }
32            });
33        }
34    });
35
36    if (fileUrls.length === 0) {
37        alert('Nenhum ficheiro encontrado para descarregar.');
38        return;
39    }
40
41    if (fileUrls.length === 1) {
42        // Single file
43        window.open(fileUrls[0], '_blank');
44    } else {
45        // Multiple files - create ZIP
46        try {
47            if (typeof JSZip === 'undefined') {
48                console.error('JSZip library not loaded');
49                alert('Erro: Biblioteca de compressão não carregada.');
50                return;
51            }
52
53            const zip = new JSZip();
54            const filePromises = [];
55
56            for (let i = 0; i < fileUrls.length; i++) {
57                const url = fileUrls[i];
58
59                let fileName = url.split('/').pop();
60                if (!fileName || fileName.indexOf('.') === -1) {
61                    fileName = `documento_${i + 1}.pdf`;
62                }
63
64                let finalFileName = fileName;
65                let counter = 1;
66                while (zip.file(finalFileName)) {
67                    const nameParts = fileName.split('.');
68                    const extension = nameParts.pop();
69                    const baseName = nameParts.join('.');
70                    finalFileName = `${baseName}_${counter}.${extension}`;
71                    counter++;
72                }
73
74                const promise = fetch(url)
75                    .then(response => {
76                        if (!response.ok) throw new Error(`Failed to fetch ${url}`);
77                        return response.blob();
78                    })
79                    .then(blob => {
80                        zip.file(finalFileName, blob);
81                    })
82                    .catch(err => console.error(`Error downloading ${url}:`, err));
83
84                filePromises.push(promise);
85            }
86
87            // Wait for all downloads
88            await Promise.all(filePromises);
89
90            // Generate ZIP
91            const zipBlob = await zip.generateAsync({ type: 'blob' });
92
93            // Download ZIP
94            const link = document.createElement('a');
95            link.href = URL.createObjectURL(zipBlob);
96            link.download = 'documentos.zip';
97            document.body.appendChild(link);
98            link.click();
99            document.body.removeChild(link);
100            URL.revokeObjectURL(link.href);
101
102        } catch (error) {
103            console.error('Error creating ZIP:', error);
104            alert('Erro ao criar arquivo ZIP.');
105        }
106    }
107}
108/*eslint-enable no-unused-vars*/

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.