Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GM_setClipboard (and other GM functions) gives an error in a Firefox but not Chrome/Tampermonkey?

I'm working in Firefox and trying to create a function that will copy a link's text when I press Shift+* (Numpad).

The code works in Chrome Tampermonkey usually, but for some reason it's doing nothing in Firefox.
The following error is reported in the console:

"ReferenceError: GM_setClipboard is not defined"

This is my code:

document.addEventListener( "keydown", function(i) {
    var selectLink = $('a').eq(8); // The link by index
    var targetLink = selectLink.text(); // The link text

    if (i.keyCode === 106 && i.shiftKey) // Shift+Num*
    {
        GM_setClipboard(targetLink); // Copy to clipboard
    }
});
like image 315
DjH Avatar asked Feb 23 '16 11:02

DjH


2 Answers

Greasemonkey requires explicit @grant statements to use GM_ functions. Whereas Tampermonkey still does some auto detection (a potential security hole).

So:

  1. You need to specify // @grant GM_setClipboard in your metadata block.

  2. However, this switches the sandbox back on (a good thing), so you also need to make sure you've @required jQuery.

This script will work in both Greasemonkey and Tampermonkey:

// ==UserScript==
// @name     _YOUR_SCRIPT_NAME
// @match    http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant    GM.setClipboard
// ==/UserScript==

document.addEventListener ( "keydown", function (i) {
    var selectLink = $('a').eq (8); // The link by index
    var targetLink = selectLink.text ().trim (); // The link text

    if (i.keyCode === 106  &&  i.shiftKey) // Shift+Num*
    {
        GM.setClipboard (targetLink); // Copy to clipboard
    }
} );
like image 147
Brock Adams Avatar answered Sep 28 '22 10:09

Brock Adams


https://clipboardjs.com/ is a good choice.

A pretty common use case is to copy content from another element. You can do that by adding a data-clipboard-target attribute in your trigger element.

enter image description here

like image 28
Du Peng Avatar answered Sep 28 '22 09:09

Du Peng