3

This code (courtesy of this page), does its job well when used inside a plain html file. In particular, it successfully copies selected text to clipboard.

function copySelectionText(){
  var copysuccess
  try {
    copysuccess = document.execCommand("copy")
  } catch(e) {
    console.log(e)
    copysuccess = false
  }
  return copysuccess
}
document.addEventListener('mouseup', function(){
  var copysuccess = copySelectionText()
}, false)

However, I couldn't make it work when used inside a tampermonkey custom script inside this:

(function() {
    // 'use strict';
    // Your code here...

})();

Disclaimers:

  • This is my first time to write a tampermonkey script.
  • I intend to use this on a particular website a friend of mine owns and not abusively on any other website.
  • Using vanilla javascript (no libraries) would be a major plus.

Question: How do I make this function work inside a tampermonkey custom script?

I followed the instructions in the tampermonkey/greasemonkey documentation.

Console shows "copysuccess is not defined". console.log(e) also produces nothing.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • It is very hard to help you in this case. I would advise you to do some debugging first so we exactly now what the error is. You do a try catch, but don't log the error it catches. This would be a great start. Also just add console.log() to every phase, maybe the event listener doesn't even fire. Put your debug details in the question and you will get an answer more quickly :) – Wimanicesir Apr 05 '23 at 13:16

2 Answers2

0

I believe you may be failing the strictness check. Since you are using 'use strict', your JavaScript needs to be compliant. For more information on strict mode, see: MDN: Strict mode.

Also, you are not doing anything except for storing the successfulness of the copy command. You are neither logging, nor alerting anything. Also, to get the actual clipboard text, you will need to access the clipboard object.

The following script works in Violentmonkey. It uses the new async clipboard API.

// ==UserScript==
// @name         Copy Selected Text
// @namespace    Stack Overflow
// @match        https://stackoverflow.com/questions/75939654/*
// @grant        none
// @version      1.0.0
// @author       Mr. Polywhirl
// @description  Userscript for copying text on a website.
// ==/UserScript==
(function() {
  // 'use strict';
  function copySelectionText() {
    let copysuccess;
    try {
      copysuccess = document.execCommand("copy");
    } catch(e) {
      console.log(e);
      copysuccess = false;
    }
    return copysuccess;
  }

  async function onMouseUp() {
    const copysuccess = copySelectionText();
    if (copysuccess) {
      // See: https://stackoverflow.com/a/49886460/1762224
      const clipboardText = await navigator.clipboard.readText();
      alert(clipboardText);
    }
  }

  document.addEventListener('mouseup', onMouseUp, false);
})();
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • Thanks for the very specific approach to the problem. I also discovered from your answer a simple but major defect in the original code I mentioned which worked without modification, only by specifying something other than just a `https://*` value in the `//@match`. – JitteryNutmeg Apr 05 '23 at 14:00
  • @JitteryNutmeg Although the actual copy mechanism still works, the article you linked was last updated in 2015. I would stick to using articles written in the last 1-2 years instead. Also, take a look at the [Greasemonkey Manual](https://wiki.greasespot.net/Greasemonkey_Manual). It gives you an idea of the structure of a userscript. Also, there is a [GM.grantClipboard](https://stackoverflow.com/a/35584467/1762224) function that may be of interest. – Mr. Polywhirl Apr 05 '23 at 14:09
0

I think the reason why it doesn't fire is that the script doesn't finish loading the page is triggered, so the easiest way is to add a setTimeOut() function to delay it for a few seconds before triggering