Greasemonkey - 你如何点击这个youglish.com 页面的隐藏按钮?

问题描述

我是 Greasemonkey 和 javascript 的新手。我有一个 youglish.com 页面:网址:https://youglish.com/pronounce/get%20caught%20off%20guard/english/us?

我想让 Chrome (Tampermonkey) 中的 GreaseMonkey 在页面加载后自动点击“[分享]”按钮,然后点击出现的“复制链接”(以便我可以将 URL 复制到剪贴板)(请参阅下面两张图片1

这是我的代码,但在我加载后什么也没有发生..我做错了什么?我怀疑这是我指定的 getElementById(...) 中的按钮 id 不正确,但不确定

// ==UserScript==
// @name         Youglish button click
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://youglish.com/*
// @icon         https://www.google.com/s2/favicons?domain=google.com
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    window.addEventListener('load',  function(){
        document.getElementById("Share").dispatchEvent(new MouseEvent('click'));
        document.getElementById("copy link").dispatchEvent(new MouseEvent('click'));
    });
})();

enter image description here

enter image description here

解决方法

我不使用 Greasemonkey,但您试图通过 id 获取文档的元素,但该元素没有任何元素,其中的文本不是元素的 id,您可以在此处了解更多信息:{{3 }}。

share thing中给出的链接只是页面的url,你可以简单地使用:

document.location.href

如果这是您想要实现的目标。

如果不是,那么请让我更详细地了解您正在尝试做什么。

,

您应该记住的一些事项。首先触发 DOMContentLoaded 事件,然后页面从服务器获取其他内容。由于我们正在寻找的链接是那些获取的项目之一,我们必须等待它,这就是使用 setInterval 的原因。找到链接后,我们使用 copyLinkLoaded 函数清除Interval。 Javascript 很难自动将某些内容复制到剪贴板,因此直接单击该按钮将不起作用。一旦链接可用,我们可以使用它的 href 属性并复制它,如果我们使用@grant GM_setClipboard。让我知道此脚本是否适合您。

// ==UserScript==
// @name         Youglish button click
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @match        https://youglish.com/*
// @icon         https://www.google.com/s2/favicons?domain=google.com
// @grant        GM_setClipboard
// ==/UserScript==

var copyLinkClear;

let copyLinkLoaded = () => {
  clearInterval(copyLinkClear);
  console.log('the interval has been cleared');
}

let findCopyLink = () => {
  copyLinkClear = setInterval(() => {
    const link = document.querySelectorAll('[class="tb_copy"] > [class="nodec"]')[0];
    if (link) {
      console.log(`The link to be copied is: ${link.href}`);
      GM_setClipboard(link.href);
      copyLinkLoaded();
    } else {
      console.log('The link has not loaded yet');
    }
  },100)
}

let findshareLinkLink = () => {
  const shareLink = document.querySelector('[data-trgid="a_share"]');
  if (shareLink) {       // We make sure the shareLink button was selected properly
    shareLink.click();  // We click on the shareLink button.
    console.log('The shareLink button was clicked');
    findCopyLink();
  } else {
    console.log('The shareLink button was not properly selected');
  }
}

findshareLinkLink();