Last active
August 29, 2015 14:10
-
-
Save louy2/51ee2951029029a03cb2 to your computer and use it in GitHub Desktop.
A naive tampermonkey script enabling "drag to download" direct links. #user.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reference: Drag out files like Gmaill | CSS Ninja