Tampermonkey油猴 跨域请求下载图片示例

6 篇文章 0 订阅
3 篇文章 0 订阅

Tampermonkey油猴 跨域请求下载图片示例

前言

需要用油猴采集并下载一个网站的图片,直接下下不了,搜了一下,是禁止跨域,使用CORS Unblock也不行,所以使用油猴自带的GM_xmlhttpRequest发送跨域请求。

项目

目标网站

目标网站

代码编写

代码仅作为学习使用,禁止商用。

// ==UserScript==
// @name         ***** Image Downloader and Zipper with GM_xmlhttpRequest
// @namespace    http://tampermonkey.net/
// @version      1.7
// @description  Download all matching product images as a zip file from the **** product page using GM_xmlhttpRequest (For learning purposes only)
// @author       slowfeather@163.com
// @match        
// @icon         
// @grant        GM_xmlhttpRequest
// @grant        GM_download
// @require      https://cdnjs.cloudflare.com/ajax/libs/jszip/3.7.1/jszip.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js
// ==/UserScript==

(function() {
    'use strict';

    // List to store image URLs
    let imageUrls = new Set();

    // Function to periodically collect image URLs
    function collectImageUrls() {
        const imageElements = document.querySelectorAll('img');
        const regex1 = /*****\.com\/package-screenshot\/.+?_scaled\.jpg$/;
        const regex2 = /*****\.****\.com\/key-image\/.+?\.jpg$/;

        imageElements.forEach((img) => {
            const url = img.src;
            if ((regex1.test(url) || regex2.test(url)) && !imageUrls.has(url)) {
                imageUrls.add(url);
                showNotification('捕获了一张图片地址 :'+url);
            }
        });
    }

    // Function to show notification
    function showNotification(message) {
        const notification = document.createElement('div');
        notification.innerText = message;
        notification.style.position = 'fixed';
        notification.style.top = '50px';
        notification.style.right = '10px';
        notification.style.zIndex = 1000;
        notification.style.backgroundColor = 'lightgreen';
        notification.style.padding = '5px';
        notification.style.border = '1px solid green';
        notification.style.borderRadius = '5px';
        document.body.appendChild(notification);

        setTimeout(() => {
            document.body.removeChild(notification);
        }, 1000);
    }

    // Set an interval to collect image URLs every second
    setInterval(collectImageUrls, 300);

    // Function to download all images in the list and zip them
    async function downloadAndZipImages() {
        const zip = new JSZip();
        let count = 0;

        const fetchImage = (url, filename) => {
            return new Promise((resolve, reject) => {
                GM_xmlhttpRequest({
                    method: 'GET',
                    url: url,
                    responseType: 'blob',
                    onload: function(response) {
                        if (response.status === 200) {
                            zip.file(filename, response.response);
                            count++;
                            resolve();
                        } else {
                            reject(`HTTP error! status: ${response.status}`);
                        }
                    },
                    onerror: function(error) {
                        reject(`Failed to fetch image ${url}: ${error}`);
                    }
                });
            });
        };

        const fetchPromises = Array.from(imageUrls).map((url, index) => {
            const filename = `image_${index + 1}.jpg`;
            return fetchImage(url, filename);
        });

        try {
            await Promise.all(fetchPromises);
            if (count > 0) {
                const content = await zip.generateAsync({ type: "blob" });
                saveAs(content, "images.zip");
            } else {
                alert("No matching images found.");
            }
        } catch (error) {
            console.error(error);
        }
    }

    // Wait for the page to fully load
    window.addEventListener('load', () => {
        // Create a button to trigger the download
        const button = document.createElement('button');
        button.innerText = 'Download All Images as Zip';
        button.style.position = 'fixed';
        button.style.top = '10px';
        button.style.right = '10px';
        button.style.zIndex = 1000;
        button.addEventListener('click', downloadAndZipImages);
        document.body.appendChild(button);
    });
})();

运行效果

成功捕获图片
下载图片

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 form 跨域请求示例: 假设我们有两个网站,分别为 A 网站和 B 网站。我们想在 A 网站上通过表单提交数据到 B 网站的服务器上。 在 A 网站上的 HTML 代码: ``` <!DOCTYPE html> <html> <head> <title>表单跨域请求示例</title> </head> <body> <form id="myForm" action="http://www.b.com/submit" method="post"> <label for="username">用户名:</label> <input type="text" id="username" name="username"><br><br> <label for="password">密码:</label> <input type="password" id="password" name="password"><br><br> <input type="submit" value="提交"> </form> <script> // 在表单提交时,禁止默认的表单提交行为 document.getElementById("myForm").addEventListener("submit", function(event){ event.preventDefault(); }); // 在表单提交时,通过 AJAX 方式提交表单数据到 B 网站的服务器上 document.getElementById("myForm").addEventListener("submit", function(event){ var xhr = new XMLHttpRequest(); xhr.open("POST", "http://www.b.com/submit"); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function(){ if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200){ alert(xhr.responseText); } }; var formData = new FormData(document.getElementById("myForm")); xhr.send(formData); }); </script> </body> </html> ``` 在 B 网站的服务器上,可以通过接收表单数据并返回一个 JSON 格式的响应来测试该示例。例如,可以在 B 网站的服务器端代码中添加以下代码: ``` app.post('/submit', function(req, res){ var username = req.body.username; var password = req.body.password; var result = { "status": "success", "message": "提交成功!", "username": username, "password": password }; res.send(result); }); ``` 注意:在真实的生产环境中,为了保证安全性,需要对表单数据进行验证和过滤,避免出现安全漏洞。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值