You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript和HTML程序化下载Google Drive公开文件夹文件

Google Drive 无API脚本下载文件问题

目标

  • 在Chrome浏览器中打开指定公开Google Drive文件夹
  • 运行JavaScript脚本完成以下操作:
    • 选中文件夹内第一个文件
    • 下载该文件

补充说明

不使用Google Drive API

已实现功能

  • 选中文件代码:
    document.querySelector('div[jsname=LvFR7c]').click()
    
  • 展开文件右上角三点选项菜单代码:
    document.getElementsByClassName("pc7nUb I5YcP Dk9rmd").click()
    

未实现功能

点击页面左上角的下载按钮(文件选中后显示)或文件选项菜单中的下载按钮均无响应

问题分析

Google Drive页面的HTML元素多带有button、menu、menuitem等aria角色,部分元素带有jsaction属性。代码点击部分元素有效,但下载按钮点击无效果,寻求解决思路。

下载按钮元素定位

  • 页面左上角下载按钮:
    document.querySelector('div[aria-label=Download]')
    
  • 文件选项菜单中的下载按钮:
    document.querySelectorAll('div[aria-label=Download]')[3]
    

已尝试操作(针对上述下载按钮元素)

element.click()
element.dispatchEvent(new Event('click'))
element.dispatchEvent(new Event('keydown')) // (初始化Event时添加过更多参数)
element.dispatchEvent(new Event('keyup'))
element.focus()
element.setAttribute('aria-expanded', true)
element.setAttribute('aria-pressed', true)
element.ariaPressed = true

解决方向建议

  1. 模拟真实用户交互事件:Google Drive的事件监听可能需要更贴近真实用户的触发逻辑,使用带完整参数的MouseEvent:
    const clickEvent = new MouseEvent('click', {
      bubbles: true,
      cancelable: true,
      view: window,
      clientX: 100,
      clientY: 100 // 模拟鼠标位置,更贴近真实点击
    });
    element.dispatchEvent(clickEvent);
    
  2. 触发元素的jsaction逻辑:若下载按钮带有jsaction属性,可通过查看元素绑定的事件找到对应的处理函数并执行。可通过getEventListeners(element)在控制台查看元素的事件绑定,定位点击事件的处理逻辑。
  3. 确保元素完全就绪:使用MutationObserver或延迟等待,确保下载按钮元素完全渲染且事件绑定完成后再执行点击:
    function waitForElementReady(selector, callback) {
      const observer = new MutationObserver((mutations) => {
        const element = document.querySelector(selector);
        if (element && getComputedStyle(element).display !== 'none') {
          observer.disconnect();
          callback(element);
        }
      });
      observer.observe(document.body, { childList: true, subtree: true });
    }
    waitForElementReady('div[aria-label=Download]', (el) => el.click());
    
  4. 模拟键盘快捷键:选中文件后,通过脚本模拟Ctrl+S(Windows/Linux)或Cmd+S(Mac)触发下载:
    // Windows/Linux
    document.dispatchEvent(new KeyboardEvent('keydown', { key: 's', ctrlKey: true, bubbles: true }));
    document.dispatchEvent(new KeyboardEvent('keyup', { key: 's', ctrlKey: true, bubbles: true }));
    
    // Mac
    // document.dispatchEvent(new KeyboardEvent('keydown', { key: 's', metaKey: true, bubbles: true }));
    // document.dispatchEvent(new KeyboardEvent('keyup', { key: 's', metaKey: true, bubbles: true }));
    

内容的提问来源于stack exchange,提问作者Amr Sharaki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 19:35:30