11487 sujets

JavaScript, DOM et API Web HTML5

bonjour,

j'ai fait 2 scripts violentmonkey grace à l'aide de chatgpt car je ne connais pas bien javascript avec une mini interface utilisateur pour un même site mais différentes url, les 2 fonctionnent très bien à 1 truc prêt qui est que l'interface utilisateur ne s'actualise pas au changement de page. j'ai séparé les 2 scripts sinon ça me provoquait des problèmes en boucle.

- 1er script pour https://exemple.com/home
upload/1707233874-79710-1.jpg
// ==UserScript==
// @name        Exemple - Home page new features
// @description New features for Exemple's home page
// @namespace    http://exemple.com/home
 
// @match        http://exemple.com/home
 
// @version     1.04
// @author      BreatFR
// @icon         https://exemple.com/favicon.ico
 
// @license     GNU GPL v3 (https://www.gnu.org/licenses/quick-guide-gplv3.en.html)
// ==/UserScript==

(function() {
    'use strict';

    // Function to set cookie
    function setCookie(name, value, days) {
        var expires = '';
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = '; expires=' + date.toUTCString();
        }
        document.cookie = name + '=' + (value || '') + expires + '; path=/';
    }

    // Function to get cookie
    function getCookie(name) {
        var nameEQ = name + '=';
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }

    // Load user preferences from cookies
    var autoConfirmEnabled = getCookie('autoConfirmEnabled') === 'true';
    var autoFocusEnabled = getCookie('autoFocusEnabled') === 'true';

    // User interface
    var uiContainer = document.createElement('div');
    uiContainer.style.position = 'fixed';
    uiContainer.style.top = '5px';
    uiContainer.style.left = '15%';
    uiContainer.style.color = '#cbcbcb';
    uiContainer.style.zIndex = '9999';

    var autoConfirmCheckbox = document.createElement('input');
    autoConfirmCheckbox.type = 'checkbox';
    autoConfirmCheckbox.checked = autoConfirmEnabled;
    autoConfirmCheckbox.addEventListener('change', function() {
        autoConfirmEnabled = autoConfirmCheckbox.checked;
        setCookie('autoConfirmEnabled', autoConfirmEnabled, 30); // Save user preference in cookie
    });

    var autoConfirmLabel = document.createElement('label');
    autoConfirmLabel.innerText = 'Auto Confirm Regenerate ';
    autoConfirmLabel.appendChild(autoConfirmCheckbox);

    var autoFocusCheckbox = document.createElement('input');
    autoFocusCheckbox.type = 'checkbox';
    autoFocusCheckbox.checked = autoFocusEnabled;
    autoFocusCheckbox.addEventListener('change', function() {
        autoFocusEnabled = autoFocusCheckbox.checked;
        setCookie('autoFocusEnabled', autoFocusEnabled, 30); // Save user preference in cookie
    });

    var autoFocusLabel = document.createElement('label');
    autoFocusLabel.innerText = 'Auto Focus Textarea ';
    autoFocusLabel.appendChild(autoFocusCheckbox);

    uiContainer.appendChild(autoConfirmLabel);
    uiContainer.appendChild(document.createElement('br'));
    uiContainer.appendChild(autoFocusLabel);

    document.body.appendChild(uiContainer);

    // Autoconfirm regenerate
    function autoConfirmRegenerate() {
        if (!autoConfirmEnabled) {
            return;
        }
    
        // Cherchez le bouton "Confirm" dans le message de régénération
        const confirmButton1 = document.querySelector('.css-mqmatd .chakra-text');
        const confirmButton2 = document.querySelector('.css-1jbciej'); // Ajout du sélecteur pour le bouton Confirm
    
        // Vérifiez d'abord si le texte spécifique est présent avant de sélectionner le bouton Confirm
        const confirmationText = document.querySelector('.css-10813k0');
        if (confirmationText && confirmationText.textContent.includes("Are you sure you want to regenerate this message?")) {
            if (confirmButton1 && confirmButton1.textContent === 'Confirm') {
                confirmButton1.click();
            } else if (confirmButton2) { // Utilisation du deuxième sélecteur si le premier n'est pas trouvé
                confirmButton2.click();
            }
        }
    
        // Vérifiez régulièrement si le bouton réapparaît
        setTimeout(autoConfirmRegenerate, 500);
    }

    autoConfirmRegenerate();

    // Autofocus on textarea
    function focusTextarea() {
        var textareaElement = document.querySelector('.css-ymugf1');
        if (textareaElement) {
            textareaElement.focus();
        }
    }

    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (autoFocusEnabled) {
                focusTextarea();
            }
        });
    });

    observer.observe(document.body, { childList: true, subtree: true });

    setInterval(function() {
        if (autoFocusEnabled) {
            focusTextarea();
        }
    }, 500);
})();

- 2ème script pour https://exemple.com/selfies
upload/1707233886-79710-2.jpg
// ==UserScript==
// @name        Exemple - Selfies page new features
// @description New features for Exemple's selfies page
// @namespace    http://exemple.com/selfies
 
// @match        http://exemple.com/selfies
 
// @version     1.01
// @author      BreatFR
// @icon         https://exemple.com/favicon.ico
 
// @license     GNU GPL v3 (https://www.gnu.org/licenses/quick-guide-gplv3.en.html)
// ==/UserScript==

(function() {
    'use strict';

    // Import JSZip library
    var script = document.createElement('script');
    script.src = 'https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js';
    document.head.appendChild(script);

    // User interface
    var uiContainer = document.createElement('div');
    uiContainer.style.position = 'fixed';
    uiContainer.style.top = '5px';
    uiContainer.style.left = '15%';
    uiContainer.style.color = '#cbcbcb';
    uiContainer.style.zIndex = '9999';

    var autoLoadMoreCheckbox = document.createElement('input');
    autoLoadMoreCheckbox.type = 'checkbox';
    autoLoadMoreCheckbox.checked = getCookie('autoLoadMoreEnabled') === 'true'; // Set checkbox value based on cookie
    autoLoadMoreCheckbox.addEventListener('change', function() {
        autoLoadMoreEnabled = autoLoadMoreCheckbox.checked;
        // Set cookie to remember user choice
        setCookie('autoLoadMoreEnabled', autoLoadMoreEnabled, 30);
        // Trigger autoLoadMore function when the checkbox is changed
        autoLoadMore();
    });

    var autoLoadMoreLabel = document.createElement('label');
    autoLoadMoreLabel.innerText = 'See All Images ';
    autoLoadMoreLabel.appendChild(autoLoadMoreCheckbox);

    var downloadAllButton = document.createElement('button');
    downloadAllButton.innerText = 'Download All Images';
    downloadAllButton.title = 'Please make sure to enable "See All Images" before downloading.'; // Add tooltip
    downloadAllButton.addEventListener('click', function() {
        downloadAllImages();
    });

    var downloadStatus = document.createElement('span');

    uiContainer.appendChild(autoLoadMoreLabel);
    uiContainer.appendChild(document.createElement('br'));
    uiContainer.appendChild(downloadAllButton);
    uiContainer.appendChild(downloadStatus);

    document.body.appendChild(uiContainer);

    // Check if autoLoadMore is enabled from cookie
    var autoLoadMoreEnabled = autoLoadMoreCheckbox.checked;

    // Function to set cookie
    function setCookie(name, value, days) {
        var expires = '';
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = '; expires=' + date.toUTCString();
        }
        document.cookie = name + '=' + (value || '') + expires + '; path=/';
    }

    // Function to get cookie
    function getCookie(name) {
        var nameEQ = name + '=';
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }

    // Auto load more images
    function autoLoadMore() {
        console.log('Auto Load More:', autoLoadMoreEnabled);
        if (!autoLoadMoreEnabled) {
            return;
        }

        // Find the "Load More" button
        var loadMoreButton = document.querySelector('button.chakra-button.css-1q03dzc');
        console.log('Load More Button:', loadMoreButton);
        if (loadMoreButton) {
            // Click the "Load More" button
            loadMoreButton.click();
            // Hide the "Load More" button
            loadMoreButton.style.display = 'none';
        }
    }

    // Download all images
    function downloadAllImages() {
        console.log('Download All Images');
        var images = document.querySelectorAll('.css-1dq4ssc img.css-1regj17');
        console.log('Found Images:', images);
        if (images.length === 0) {
            alert('No images found.');
            return;
        }

        var zip = new JSZip();
        var count = 0;
        var totalImages = images.length;
        downloadStatus.innerText = ' Downloading... (0/' + totalImages + ')';
        images.forEach(function(image, index) {
            fetch(image.src)
                .then(response => response.blob())
                .then(blob => {
                    var filename = ('0000' + (totalImages - index)).slice(-4) + '.jpg'; // Reverse numbering
                    zip.file(filename, blob);
                    count++;
                    downloadStatus.innerText = ' Downloading... (' + count + '/' + totalImages + ')';
                    if (count === totalImages) {
                        zip.generateAsync({ type: 'blob' })
                            .then(content => {
                                // Trigger file download
                                var a = document.createElement('a');
                                a.href = URL.createObjectURL(content);
                                a.download = 'Kindroid.zip';
                                a.click();
                                downloadStatus.innerText = '';
                                // Show the "Load More" button again after download is complete
                                var loadMoreButton = document.querySelector('button.chakra-button.css-1q03dzc');
                                if (loadMoreButton) {
                                    loadMoreButton.style.display = 'block';
                                }
                            });
                    }
                });
        });
    }

    // Call autoLoadMore function when the page is loaded
    window.addEventListener('load', function() {
        autoLoadMore();

        // Observe mutations in the DOM to detect addition of new elements
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                autoLoadMore();
            });
        });

        // Start observing mutations
        observer.observe(document.body, { childList: true, subtree: true });
    });
})();
mon problème est le suivant, je commence par aller sur la page https://exemple.com/home, j'ai bien la bonne interface qui s'affiche puis je vais sur https://exemple.com/selfie et et là j'ai encore l'interface ajouté par mon script pour https://exemple.com/home au lieu d'avoir celle du script pour https://exemple.com/selfies. pour corriger ça je dois faire f5.

bien sûr le problème est également présent dans l'autre sens, si je commence par aller sur https://exemple.com/selfie j'ai bien l'interface ajoutée par mon script pour la page selfie puis si je vais sur la page home alors j'ai toujours mon interface ajoutée de la page selfie tant que je ne fais pas f5.

quelqu'un aurait une solution ?
Modifié par Breat (06 Feb 2024 - 20:47)