Search code examples
javascriptuserscripts

Userscript for hovercopy


Below is my userscript that will copy an HTML link to the clipboard when hovering over a hyperlink and pressing CTRL+C. It works fine when the <a> is the child-most element, but I'd like to allow it to take the text of any element being hovered over and use the href from its closest <a> parent. Here is the code as I have it now:

// ==UserScript==
// @name        Copy hyperlink using mouse hover + Ctrl + C
// @include     *
// @grant       GM_setClipboard

// ==/UserScript==

document.addEventListener('keydown', e => {
  if (e.code === 'KeyC' && e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey) {
    const a = document.querySelector('a:hover');
    if (a) {
        console.log(a)
        var lnkURL = a.href;
        var lnkText = a.text;
        var myLnk = '';
        myLnk = myLnk.concat("<a href='",lnkURL,"'>",lnkText,"</a>");
        GM_setClipboard(myLnk, 'html');

    }
  }
})

Below is an instance of where it would fail: variable "lnkText" needs to be "EI-261". How can I modify the script such that it grabs the correct text?

<a one-appnavbar="" href="/lightning/r/a064/view" draggable="false">
    <span one-appnavbar="" class="slds-truncate">
            <span one-appnavbar="">
                EI-261
            </span>
    </span>
</a>

Solution

  • You can call Element#closest() to get it:

    // ==UserScript==
    // @name        Copy hyperlink using mouse hover + Ctrl + C
    // @include     *
    // @grant       GM_setClipboard
    
    // ==/UserScript==
    
    document.addEventListener('keydown', e => {
      if (e.code === 'KeyC' && e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey) {
        const hovered = document.querySelector('a:hover, a *:hover');
        if (hovered) {
            const a = hovered.closest('a');
            console.log(a)
            var lnkURL = a.href;
            var lnkText = a.text;
            var myLnk = '';
            myLnk = myLnk.concat("<a href='",lnkURL,"'>",lnkText,"</a>");
            GM_setClipboard(myLnk, 'html');
        }
      }
    })