1

I want to be able to click on certain text on specific sites and have it selected and copied to keyboard. So far I use something like this to select the text within specific classes using Stylus.

.classname {
    user-select: all;
}

How can I have it copied to keyboard too? Trying this for IATE did work on selecting the string but did not work on copying (clicking on any of the translations there).

// ==UserScript==
// @name         Iate select
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://iate.europa.eu/*
// @icon         data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

  let style = document.createElement('style');
  style.innerHTML = 'app-iate-search-term-refine{ user-select: all !important; }';

  document.body.appendChild(style);

const element = document.querySelector('app-iate-search-term-refine');

element.addEventListener('click', () => {
const text = element.textContent;

    GM_setClipboard(text);
});
})();
double-beep
  • 5,031
  • 17
  • 33
  • 41
greektranslator
  • 499
  • 1
  • 6
  • 19

2 Answers2

1

Add click event listener on the element whose text you want to copy, then use GM_setClipboard. Note that:

  • The elements aren't accessible when the DOM is "ready". Therefore, the script below uses waitForKeyElements, a utility developed by Brock Adams.
  • There are more elements of type app-iate-search-term-refine, you need to query them all, then loop throgh each and add the same event listener.

This example should work:

// ==UserScript==
// @name         Iate select
// @version      0.1
// @author       greektranslator
// @match        https://iate.europa.eu/*
// @require      https://gist.githubusercontent.com/BrockA/2625891/raw/waitForKeyElements.js
// @grant        GM_setClipboard
// @grant        GM_addStyle
// ==/UserScript==
/* globals waitForKeyElements */

(function() {
    'use strict';

    GM_addStyle('app-iate-search-term-refine { user-select: all !important; }');

    waitForKeyElements('app-iate-search-term-refine', addListener, false);

    function addListener() {
        const elements = document.querySelectorAll('app-iate-search-term-refine');

        elements.forEach(element => {
            element.addEventListener('click', () => {
                const text = element.textContent.trim();

                GM_setClipboard(text);
            });
        });
    }
})();
double-beep
  • 5,031
  • 17
  • 33
  • 41
0

This code can be used. It worked for me one day.

element.addEventListener('click', () => {
    const text = element.textContent;

    navigator.clipboard.writeText(text)
    .then(() => {
      // Here you can handle successful copying
    })
    .catch(err => {
      // Here you can handle error (err)
    });
});
SNBS
  • 671
  • 2
  • 22