// ==UserScript== // @name PDD主图和视频一键下载 // @namespace http://tampermonkey.net/ // @version 0.1 // @description 在PDD详情页添加按钮,一键下载主图和视频 // @author 提需求请加微信: ponysixty // @match *://*.yangkeduo.com/* // @match *://*.pinduoduo.com/* // @grant none // ==/UserScript== (function() { 'use strict'; // 创建按钮 const button = document.createElement('button'); button.textContent = '一键下载主图和视频'; button.style.position = 'fixed'; button.style.top = '0'; button.style.left = '0'; button.style.backgroundColor = 'red'; button.style.color = 'white'; button.style.padding = '10px 20px'; button.style.border = 'none'; button.style.borderRadius = '5px'; button.style.cursor = 'pointer'; // 添加按钮到页面 const targetElement = document.querySelector('body'); // 根据实际页面结构调整 targetElement.appendChild(button); // 按钮点击事件 button.addEventListener('click', () => { // 提取轮播图图片 const carouselImages = document.querySelectorAll('.goods-container-v2 > div:first-child img'); carouselImages.forEach((img, index) => { const imgUrl = img.src; console.log(index,imgUrl); // 调试用,可删除 imgUrl && downloadFile(imgUrl, `main-image-${index + 1}.jpg`); }); // 提取视频 const video = document.querySelector('.goods-container-v2 > div:first-child video'); if (video) { const videoUrl = video.src; console.log(videoUrl); // 调试用,可删除 videoUrl && downloadFile(videoUrl, 'main-video.mp4'); } }); const triggerDownload = (name, blob) => { // 创建 Blob 对象的 URL const blobUrl = URL.createObjectURL(blob); // 创建一个临时链接元素 const tempLink = document.createElement("a"); tempLink.href = blobUrl; tempLink.download = name; // 将链接添加到 DOM 并模拟点击 document.body.appendChild(tempLink); // 避免某些浏览器安全限制 tempLink.click(); // 清理临时链接元素 document.body.removeChild(tempLink); // 从 DOM 中移除临时链接 URL.revokeObjectURL(blobUrl); // 释放 URL console.info(`文件已成功下载: ${name}`); } const downloadFile = async (link, name, trigger = true, retries = 5) => { if (!link) { return false; } //使用URL中的goods_id作为文件名 const url = new URL(window.location.href); const goods_id = url.searchParams.get("goods_id"); name = goods_id + '_' + name; for (let attempt = 1; attempt <= retries; attempt++) { try { // 使用 fetch 获取文件数据 const response = await fetch(link, {method: "GET"}); // 检查响应状态码 if (!response.ok) { console.error(`下载失败,状态码: ${response.status},URL: ${link},尝试次数: ${attempt}`); continue; // 继续下一次尝试 } const blob = await response.blob(); if (trigger) { triggerDownload(name, blob); return true; } else { return blob; } } catch (error) { console.error(`下载失败 (${name}),错误信息:`, error, `尝试次数: ${attempt}`); if (attempt === retries) { return false; // 如果达到最大重试次数,返回失败 } } } return false; // 如果所有尝试都失败,返回失败 }; })();