Skip to content

Instantly share code, notes, and snippets.

@louy2
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save louy2/51ee2951029029a03cb2 to your computer and use it in GitHub Desktop.
Save louy2/51ee2951029029a03cb2 to your computer and use it in GitHub Desktop.
A naive tampermonkey script enabling "drag to download" direct links. #user.js
// ==UserScript==
// @name Drag To Download
// @namespace
// @version 0.1
// @description Drag direct links to files to computer.
// @author Lou Yufan
// @match http://*/*
// @match https://*/*
// @grant none
// ==/UserScript==
// Reference
// Drag out files like Gmail | The CSS Ninja
// http://www.thecssninja.com/javascript/gmail-dragout
// get all links in the page
var links = document.getElementsByTagName("a");
// define the postfixes of files
// add additional postfixes here
var postfixes = [".exe",".zip",".tar.gz"];
// turn postfixed into regex to match the links
// remember the matched filename
// using (?:<pattern>) to group postfixes
// (?:<group>|<group|...)
var refile = ".*/(.+(?:";
postfixes.forEach(function(postfix){
refile += "(?:\\"+postfix+")|";
});
refile = new RegExp( refile.slice(0,-1)+"))$", "i" );
// match the regexp
var files = [];
for (var i = 0; i < links.length; ++i){
if (refile.test(links[i].getAttribute("href"))){
files.push(links[i]);
}
}
files.forEach(function(file,ind,arr){
var downloadurl = file.getAttribute("href");
// make sure downloadurl is absolute
var reabs = new RegExp("^https?"); // absolute path test
var reroot = new RegExp("^/"); // root path test
if (!reabs.test(downloadurl)){
if (reroot.test(downloadurl)) {
downloadurl = location.origin + downloadurl;
} else {
downloadurl = location.href + downloadurl;
}
}
// set matched filename as default name
downloadurl = refile.exec(downloadurl)[1] + ":" + downloadurl;
// use arbitrary MIME-type
downloadurl = "application/octet-stream:" + downloadurl;
// add event
file.addEventListener("dragstart",function(evt){
evt.dataTransfer.setData("DownloadURL", downloadurl);
},false);
});
@louy2
Copy link
Author

louy2 commented Nov 24, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment