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