0

I'm trying to make a simple no flash .js file for tampermonkey, that searches a webpage for a file url(google drive for instance) and copies only the first link to the clipboard.

Here is the code UPDATED:

(function() {
    'use strict';

    const urls = Array.from(document.querySelectorAll("a")); //get all link elements into an array.

const fileLinks = urls.filter(x=>
    {
    const test = x.src.indexOf("drive.google.com/file") || undefined
    // add `|| x.src.indexOf("other search conditions")` before the last undefined to add search conditions;
    if(test){return x}
    //return only those that have the correct info in the src attribute

});
console.log(fileLinks);

navigator.clipboard.writeText(fileLinks[0])
   .then(()=> console.log('success!'))
.catch(err=>console.error(`fail: ${err}`));
})();

Here are some references:

https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard

https://w3c.github.io/clipboard-apis/ https://developers.google.com/web/updates/2018/03/clipboardapi

Copy output of a JavaScript variable to the clipboard

Javascript copy text to clipboard without click any button on page load

How do I copy to the clipboard in JavaScript?

https://github.com/lgarron/clipboard-polyfill

Vello
  • 11
  • 1
  • The purpose of Stackoverflow is to assist with coding based questions and this is far to broad to be offered any real help short of someone doing the work for you. Please consider submitting some code examples with details of the trouble you are experiencing. – Sean Aug 26 '20 at 22:19

2 Answers2

0

this is untested.

Since you have no code to correct, start off with this - this should at least be very close.

const urls = Array.from(document.querySelectorAll("a")); //get all link elements into an array.

const fileLinks = urls.filter(x=>
    {
    const test = x.src.indexOf("drive.google.com/file") || undefined 
    // add `|| x.src.indexOf("other search conditions")` before the last undefined to add search conditions;
    if(test){return x} 
    //return only those that have the correct info in the src attribute

}); 
console.log(fileLinks);

navigator.clipboard.writeText(fileLinks[0])
   .then(()=> console.log('success!'))
   .catch(err=>console.error(`fail: ${err}`));



edit: small errors in the code have been fixed.

altruios
  • 986
  • 1
  • 10
  • 29
  • 2 errors: const urls = Array.from(document.querySelectorAll(a)); //gives error 'a' undefined var a=""; //added this line above it .catch(err)console.error(`fail: ${err}`)); //Gives error eslint:null - Parsing error: Unexpected token console - I just added two // in front to comment out. But it does not copy the google drive link into the clipboard – Vello Aug 26 '20 at 23:22
  • ah, so I was unsure of how to target "a" html tags with the query selector... try "a" instead of a – altruios Aug 26 '20 at 23:24
  • the second error seems to be from the query failing. that first line should work as is with no variable declaration above it... 99% sure the a just needs to be wrapped in quotes. – altruios Aug 26 '20 at 23:26
  • Added the double quotes around const urls = Array.from(document.querySelectorAll("a")); // 1st error is gone, but second error remains, and it's not from the query failing, it is the debugger giving the error – Vello Aug 26 '20 at 23:40
  • ah... there's a typo in my code. try the .catch(err=>console.error(`fail:${err}`)) ...fixed it in the answer. – altruios Aug 27 '20 at 06:29
  • 1
    thinking on it - I'm not sure if you can copy directly to the clipboard without a user click or action... for security reasons... might have to tie it into a button. – altruios Aug 27 '20 at 06:32
  • I read that it can be done using the Clipboard API without user interaction. Might require modifying the user.js for firefox permission. Chrome also has a new navigator.clipboard API. I added links to the original question. – Vello Aug 27 '20 at 17:13
0

There are browser APIs for this, but… it's complicated.

I was in a similar situation and discovered that navigator.clipboard.writeText only works in very limited contexts, when the "content" part of the browser window is in focus, and/or the user has interacted with it, for security reasons. The Firefox console error was mysterious, but Chrome was explicit: DOMException: Document is not focused.

Short answer: I don't think it's worth your while to try and do this the hard way in a userscript.

It's probably better to let the Tampermonkey author wrap the browser APIs for you, and let him (and the Tampermonkey contributors) deal with all the compatibility issues. If all you need to do is copy text to the clipboard, then GM_setClipboard is probably the solution you're looking for. Don't forget to @grant GM_setClipboard.

Here is a minimal working example. Google Drive doesn't create <a> links for files, so I used the download directory for GNU findutils instead. Modify as necessary for your purposes, paying close attention to the href vs. src attribute (say, for images).

I hope this helps.

// ==UserScript==
// @name         GNU findutils first download link
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Copy first .tar.gz link from findutils' download page to the clipboard
// @author       You
// @match        https://ftp.gnu.org/*
// @grant        GM_setClipboard
// ==/UserScript==

(function() {
    'use strict';
    var urls = Array.from(document.querySelectorAll("a"));
    var fileLinks = urls.filter(x => {
        return x.href.endsWith(".tar.gz");
        // separate other conditions with '||'
        // e.g., || x.href.contains("4.4.")
    }).map(x => x.href);
    GM_setClipboard(fileLinks[0]);
})();
TheDudeAbides
  • 1,821
  • 1
  • 21
  • 29