Make Bookmarklets from Javascript URLs

When it sees a link to a userscript or general Javascript URL, adds a Bookmarklet besides it, which you can drag to your toolbar to load the script when you next need it (running outside Greasemonkey of course).

当前为 2015-08-21 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Make Bookmarklets from Javascript URLs
  3. // @namespace MBFU
  4. // @description When it sees a link to a userscript or general Javascript URL, adds a Bookmarklet besides it, which you can drag to your toolbar to load the script when you next need it (running outside Greasemonkey of course).
  5. // @include http://hwi.ath.cx/*/gm_scripts/*
  6. // @include http://hwi.ath.cx/*/userscripts/*
  7. // @include http://*userscripts.org/*
  8. // @include https://*userscripts.org/*
  9. // @include http://openuserjs.org/*
  10. // @include https://openuserjs.org/*
  11. // @include http://greasyfork.org/*
  12. // @include https://greasyfork.org/*
  13. // @include http://*/*
  14. // @include https://*/*
  15. // @exclude http://hwi.ath.cx/code/other/gm_scripts/joeys_userscripts_and_bookmarklets_overview.html
  16. // @exclude http://neuralyte.org/~joey/gm_scripts/joeys_userscripts_and_bookmarklets_overview.html
  17. // @grant none
  18. // @version 1.2.5
  19. // ==/UserScript==
  20.  
  21. // BUG: We had (i%32) in a userscript (DLT) but when this was turned into a bookmarklet and dragged into Chrome, the debugger showed it had become (i2), causing the script to error with "i2 is not defined". Changing the code to (i % 32) worked around the problem.
  22.  
  23. // TODO: All links with using dummy=random should change the value on mouseover/mousemove/click, so they can be re-used live without refreshing the page.
  24. // Static bookmarklets could timeout and re-build after ... 10 seconds? ^^
  25.  
  26. // Most people will NOT want the NoCache version. It's only useful for script developers.
  27.  
  28. // Firefox/Greasemonkey does not like to install scripts ending ".user.js?dummy=123"
  29. // But in Chrome it is a useful way to prevent the script from being cached when you are developing it.
  30. var inGoogleChrome = window && window.navigator && window.navigator.vendor.match(/Google/);
  31.  
  32. var preventBrowserFromCachingBookmarklets = inGoogleChrome;
  33.  
  34. // Sometimes Chrome refuses to acknowledge that a script has been updated, and repeatedly installs an old version from its cache!
  35. var preventCachingOfInstallScripts = inGoogleChrome;
  36. // BUG: Chrome sometimes installs a new instance of an extension for each click, rather than overwriting (upgrading) the old. However disabling preventBrowserFromCachingBookmarklets does not fix that. It may have been the name "Wikimedia+"?
  37.  
  38. var addGreasemonkeyLibToBookmarklets = true;
  39.  
  40. // DONE: All bookmarklets optionally preload the Fallback GMAPI.
  41. // DONE: All bookmarklets optionally load in non-caching fashion (for changing scripts).
  42.  
  43. // DONE: Use onload event to ensure prerequisite scripts are loaded before dependent scripts.
  44.  
  45. // DONE via FBGMAPI: We could provide neat catches for GM_ API commands so they won't fail entirely.
  46.  
  47. // TODO: Provide extra feature, which allows the Bookmarks to actually trigger
  48. // the userscript properly-running inside Greasemonkey, if this userscript is
  49. // present to handle the request, otherwise (with warning) load outside GM.
  50.  
  51. // TODO: Support @include/@excude and @require meta rules?
  52. // This requires parsing the script's header using XHR before creating each bookmarklet.
  53.  
  54. // DONE: Optionally create static bookmarklet, with all code inline, rather than loaded from a URL.
  55. // // comments will need to be removed or converted to /*...*/ comments
  56.  
  57. var addDateToStaticBookmarklets = true;
  58.  
  59. var defaultScripts = [];
  60. var includeGMCompat = addGreasemonkeyLibToBookmarklets;
  61. if (includeGMCompat) {
  62. // defaultScripts.push("http://hwi.ath.cx/code/other/gm_scripts/fallbackgmapi/fallbackgmapi.user.js");
  63. defaultScripts.push("http://neuralyte.org/~joey/gm_scripts/fallbackgmapi/fallbackgmapi.user.js");
  64. }
  65.  
  66. function buildLiveBookmarklet(link) {
  67. var neverCache = preventBrowserFromCachingBookmarklets;
  68.  
  69. var scriptsToLoad = defaultScripts.slice(0);
  70.  
  71. scriptsToLoad.push(link.href);
  72.  
  73. var neverCacheStr = ( neverCache ? "+'?dummy='+new Date().getTime()" : "" );
  74.  
  75. /*
  76. var toRun = "(function(){\n";
  77. for (var i=0;i<scriptsToLoad.length;i++) {
  78. var script = scriptsToLoad[i];
  79. toRun += " var newScript = document.createElement('script');\n";
  80. toRun += " newScript.src = '" + script + "'" + neverCacheStr + ";\n";
  81. toRun += " document.body.appendChild(newScript);\n";
  82. }
  83. toRun += "})();";
  84. */
  85.  
  86. var toRun = "(function(){\n";
  87. // Chrome has no .toSource() or uneval(), so we use JSON. :f
  88. toRun += "var scriptsToLoad="+JSON.stringify(scriptsToLoad)+";\n";
  89. toRun += "function loadNext() {\n";
  90. toRun += " if (scriptsToLoad.length == 0) { return; }\n";
  91. toRun += " var next = scriptsToLoad.shift();\n";
  92. toRun += " var newScript = document.createElement('script');\n";
  93. toRun += " newScript.src = next"+neverCacheStr+";\n";
  94. toRun += " newScript.onload = loadNext;\n";
  95. toRun += " newScript.onerror = function(e){ console.error('Problem loading script: '+next,e); };\n";
  96. toRun += " document.body.appendChild(newScript);\n";
  97. toRun += "}\n";
  98. toRun += "loadNext();\n";
  99. toRun += "})(); (void 0);";
  100.  
  101. var name = getNameFromFilename(link.href);
  102. /*
  103. if (neverCache) {
  104. name = name + " (NoCache)";
  105. }
  106. if (includeGMCompat) {
  107. name = name + " (FBAPI)";
  108. }
  109. */
  110.  
  111. var newLink = document.createElement("A");
  112. newLink.href = "javascript:" + toRun;
  113. newLink.textContent = name;
  114. newLink.title = newLink.href;
  115.  
  116. var newContainer = document.createElement("div");
  117. // newContainer.style.whiteSpace = 'nowrap';
  118. newContainer.appendChild(document.createTextNode("(Live Bookmarklet: "));
  119. newContainer.appendChild(newLink);
  120. var extraString = ( neverCache || includeGMCompat ? neverCache && includeGMCompat ? " (no-caching, with GM fallbacks)" : neverCache ? " (no-caching)" : " (with GM fallbacks)" : "" );
  121. // DISABLED HERE:
  122. extraString = "";
  123. if (extraString) {
  124. // newContainer.appendChild(document.createTextNode(extraString));
  125. // var extraText = document.createElement("span");
  126. // extraText.style.fontSize = '80%';
  127. var extraText = document.createElement("small");
  128. extraText.textContent = extraString;
  129. newContainer.appendChild(extraText);
  130. }
  131. newContainer.appendChild(document.createTextNode(")"));
  132. newContainer.style.paddingLeft = '8px';
  133. // link.parentNode.insertBefore(newContainer,link.nextSibling);
  134. return newContainer;
  135. }
  136.  
  137. function reportMessage(msg) {
  138. console.log(msg);
  139. }
  140.  
  141. function reportWarning(msg) {
  142. console.warn(msg);
  143. }
  144.  
  145. function reportError(msg) {
  146. console.error(msg);
  147. }
  148.  
  149. function doesItCompile(code) {
  150. try {
  151. var f = new Function(code);
  152. } catch (e) {
  153. return false;
  154. }
  155. return true;
  156. }
  157.  
  158. /* For more bugs try putting (function(){ ... })(); wrapper around WikiIndent! */
  159.  
  160. function fixComments(line) {
  161.  
  162. //// Clear // comment line
  163. line = line.replace(/^[ \t]*\/\/.*/g,'');
  164.  
  165. //// Wrap // comment in /*...*/ (Dangerous! if comment contains a */ !)
  166. // line = line.replace(/^([ \t]*)\/\/(.*)/g,'$1/*$2*/');
  167.  
  168. //// Clear trailing comment (after a few chars we deem sensible)
  169. //// This still doesn't handle some valid cases.
  170. var trailingComment = /([;{}()\[\],\. \t])\s*\/\/.*/g;
  171. //// What might break: An odd number of "s or 's, any /*s or */s
  172. var worrying = /(["']|\/\*|\*\/)/;
  173. // Here is a breaking example:
  174. // var resNodes = document.evaluate("//div[@id='res']//li", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
  175. // var hasTrailingComment = line.match(trailingComment);
  176. var hasTrailingComment = trailingComment.exec(line);
  177. if (hasTrailingComment) {
  178. /*
  179. if (line.match(worrying)) {
  180. reportWarning("Warning: trailingComment matches: "+hasTrailingComment);
  181. }
  182. */
  183. var compiledBefore = doesItCompile(line);
  184. var newLine = line.replace(trailingComment,'$1');
  185. var compilesAfter = doesItCompile(newLine);
  186. if (compiledBefore && !compilesAfter) {
  187. reportWarning("Aborted // stripping on: "+line);
  188. } else {
  189. // Accept changes
  190. line = newLine;
  191. }
  192. }
  193. return line;
  194.  
  195. }
  196.  
  197. function cleanupSource(source) {
  198. // console.log("old length: "+source.length);
  199. var lines = source.split('\n');
  200. // console.log("lines: "+lines.length);
  201. for (var i=0;i<lines.length;i++) {
  202. lines[i] = fixComments(lines[i]);
  203. }
  204. // source = lines.join('\n');
  205. source = lines.join(' ');
  206. // console.log("new length: "+source.length);
  207. //// For Bookmarklet Builder's reformatter:
  208. source = source.replace("(function","( function",'g');
  209. return source;
  210. }
  211.  
  212. // We could cache urls, at least during this one page visit
  213. // Specifically the ones we request repeatedly for statis bmls (fbgmapi).
  214. var sourcesLoaded = {};
  215.  
  216. // My first "promise":
  217. function getSourceFor(url) {
  218. return {
  219. then: function(handleResponse){
  220. // I found this was needed one time on Chrome!
  221. // It probably doesn't need to be linked to preventCachingOfInstallScripts or preventBrowserFromCachingBookmarklets.
  222. url += "?dummy="+Math.random();
  223. console.log("Loading "+url);
  224. getURLThen(url, handlerFn, onErrorFn);
  225.  
  226. function handlerFn(res) {
  227. var source = res.responseText;
  228. handleResponse(source);
  229. }
  230.  
  231. function onErrorFn(res) {
  232. reportError("Failed to load "+url+": HTTP "+res.status);
  233. }
  234.  
  235. // CONSIDER: We should return the next promise?
  236. }
  237. };
  238. }
  239.  
  240. /* To avoid a multitude of premature network requests, the bookmarklet is not actually "compiled" until mouseover. */
  241. function buildStaticBookmarklet(link) {
  242.  
  243. var newLink = document.createElement("a");
  244. newLink.textContent = getNameFromFilename(link.href);
  245.  
  246. var newContainer = document.createElement("div");
  247. // newContainer.style.whiteSpace = 'nowrap';
  248. // Experimental:
  249. newContainer.appendChild(document.createTextNode("(Static Bookmarklet: "));
  250. newContainer.appendChild(newLink);
  251. newContainer.appendChild(document.createTextNode(")"));
  252. newContainer.style.paddingLeft = '8px';
  253.  
  254. newLink.style.textDecoration = 'underline';
  255. // newLink.style.color = '#000080';
  256. newLink.style.color = '#333366';
  257.  
  258. // link.parentNode.insertBefore(newContainer,link.nextSibling);
  259.  
  260. // The href may change before we fire (e.g. if dummy is appended) so we make a copy.
  261. var href = link.href;
  262.  
  263. // setTimeout(function(){
  264. // ,2000 * staticsRequested);
  265. newLink.onmouseover = function(){
  266. getStaticBookmarkletFromUserscript(href,whenGot);
  267. newLink.style.color = '#ff7700';
  268. newLink.onmouseover = null; // once
  269. };
  270.  
  271. function whenGot(staticSrc, report) {
  272.  
  273. var extraText = "";
  274.  
  275. // Does it parse?
  276. try {
  277. var testFn = new Function(staticSrc);
  278. newLink.style.color = ''; // Success! Color like a normal link
  279. } catch (e) {
  280. var msg = "PARSE FAILED";
  281. // Firefox has this:
  282. if (e.lineNumber) {
  283. msg += " on line "+e.lineNumber;
  284. }
  285. msg += ":";
  286. console.log("["+href+"] "+msg,e);
  287. newLink.title = msg+" "+e;
  288. newLink.style.color = 'red'; // color as error
  289. window.lastParseError = e;
  290. // return;
  291. }
  292.  
  293. newLink.href = "javascript:" + staticSrc;
  294.  
  295. if (addDateToStaticBookmarklets) {
  296. var d = new Date();
  297. //var dateStr = d.getFullYear()+"."+(d.getMonth()+1)+"."+d.getDate();
  298. var dateStr = d.toISOString().substring(0,10);
  299. newLink.textContent = newLink.textContent + " ("+dateStr+")";
  300. }
  301.  
  302. if (report.needsGMFallbacks) {
  303. extraText += " uses GM";
  304. } else {
  305. extraText += " GM free";
  306. }
  307.  
  308. if (extraText) {
  309. newLink.parentNode.insertBefore( document.createTextNode(extraText), newLink.nextSibling);
  310. }
  311.  
  312. // Just in case the browser is dumb, force it to re-analyse the link.
  313. newLink.parentNode.insertBefore(newLink, newLink.nextSibling);
  314. }
  315.  
  316. return newContainer;
  317.  
  318. }
  319.  
  320. function getStaticBookmarkletFromUserscript(href, callbackGotStatic) {
  321.  
  322. getSourceFor(href).then(function (userscriptSource) {
  323. var hasGrantNone = userscriptSource.match('\\n//\\s*@grant\\s+none\\s*\\n');
  324. var needsGMFallbacks = ! hasGrantNone;
  325.  
  326. var scriptsToLoad = needsGMFallbacks ? defaultScripts.slice(0) : [];
  327.  
  328. loadScripts(scriptsToLoad, allSourcesLoaded);
  329.  
  330. function allSourcesLoaded(scriptSources) {
  331. scriptSources.push(userscriptSource);
  332.  
  333. var toRun = "";
  334. for (var i=0; i<scriptSources.length; i++) {
  335. if (!scriptSources[i]) {
  336. reportError("Expected contents of "+scriptsToLoad[i]+" but got: "+scriptSources[i]);
  337. }
  338. var cleaned = cleanupSource(scriptSources[i]);
  339. toRun += "(function(){\n";
  340. toRun += cleaned;
  341. toRun += "})();\n";
  342. }
  343. toRun += "(void 0);";
  344.  
  345. var report = {
  346. needsGMFallbacks: needsGMFallbacks,
  347. };
  348.  
  349. callbackGotStatic(toRun, report);
  350. }
  351. });
  352.  
  353. function loadScripts(scriptsToLoad, callbackScriptsLoaded) {
  354. if (scriptsToLoad.length === 0) {
  355. return callbackScriptsLoaded([]);
  356. }
  357.  
  358. var scriptSources = [];
  359. var numLoaded = 0;
  360.  
  361. for (var i=0; i<scriptsToLoad.length; i++) {
  362. loadSourceIntoArray(i);
  363. }
  364.  
  365. function loadSourceIntoArray(i) {
  366. getSourceFor(scriptsToLoad[i]).then(function(source){
  367. if (!source) {
  368. reportError("Failed to acquire source for: "+href);
  369. }
  370. scriptSources[i] = source;
  371. numLoaded++;
  372. if (numLoaded == scriptsToLoad.length) {
  373. callbackScriptsLoaded(scriptSources);
  374. }
  375. });
  376. }
  377. }
  378.  
  379. }
  380.  
  381. // In this case, link points to a folder containing a userscript.
  382. // We guess the userscript's name from the folder's name.
  383. function addQuickInstall(link) {
  384. if (link.parentNode.tagName == 'TD') {
  385. link.parentNode.style.width = '60%';
  386. }
  387. var br2 = document.createElement("br");
  388. link.parentNode.insertBefore(br2,link.nextSibling);
  389. var br = document.createElement("br");
  390. link.parentNode.insertBefore(br,link.nextSibling.nextSibling);
  391. var name = link.href.match(/([^\/]*)\/$/)[1];
  392. var newLink = document.createElement("A");
  393. newLink.href = link.href + name+".user.js";
  394. newLink.textContent = "Install Userscript"; // name+".user.js";
  395. var newContainer = document.createElement("span");
  396. newContainer.appendChild(document.createTextNode(" ["));
  397. newContainer.appendChild(newLink);
  398. newContainer.appendChild(document.createTextNode("]"));
  399. newContainer.style.paddingLeft = '8px';
  400. link.parentNode.insertBefore(newContainer,br);
  401. link.style.color = 'black';
  402. link.style.fontWeight = 'bold';
  403. newContainer.appendChild(buildLiveBookmarklet(newLink));
  404. newContainer.appendChild(buildStaticBookmarklet(newLink));
  405. newContainer.appendChild(buildLiveUserscript(newLink));
  406. popupSourceOnHover(newLink);
  407. // Do this after the other two builders have used the .href
  408. if (preventCachingOfInstallScripts) {
  409. newLink.href = newLink.href + '?dummy='+new Date().getTime();
  410. }
  411. }
  412.  
  413. function getURLThen(url,handlerFn,onErrorFn) {
  414. var req = new XMLHttpRequest();
  415. req.open("get", url, true);
  416. req.onreadystatechange = function (aEvt) {
  417. if (req.readyState == 4) {
  418. if(req.status == 200) {
  419. // Got it
  420. handlerFn(req);
  421. } else {
  422. var msg = ("XHR failed with status "+req.status+"\n");
  423. window.status = msg;
  424. onErrorFn(req);
  425. console.warn(msg);
  426. }
  427. }
  428. };
  429. req.send(null);
  430. }
  431.  
  432. var frame = null;
  433.  
  434. function loadSourceViewer(url, newLink, evt) {
  435.  
  436. // window.lastEVT = evt;
  437.  
  438. if (frame && frame.parentNode) {
  439. frame.parentNode.removeChild(frame);
  440. }
  441. frame = document.createElement("div");
  442.  
  443. function reportToFrame(msg) {
  444. frame.appendChild( document.createTextNode(msg) );
  445. }
  446.  
  447. // This doesn't work. Loading it directly into the iframe triggers Greasemonkey to install it!
  448. //frame.src = url;
  449. // What we need to do is get the script with an XHR, then place it into the div.
  450.  
  451. // This seems to fire immediately in Firefox!
  452. var cleanup = function(evt) {
  453. frame.parentNode.removeChild(frame);
  454. document.body.removeEventListener("click",cleanup,false);
  455. // frame.removeEventListener("mouseout",cleanup,false);
  456. };
  457. document.body.addEventListener("click",cleanup,false);
  458.  
  459. getURLThen(url, function(res){
  460. // We were using pre instead of div to get monospace like <tt> or <code>
  461. // However since we are commonly reading the description, sans seems better.
  462. var displayDiv = document.createElement("div");
  463. displayDiv.style.fontSize = '0.8em';
  464. displayDiv.style.whiteSpace = "pre-wrap";
  465. var displayCode = document.createElement("pre");
  466. displayCode.textContent = res.responseText;
  467. displayCode.style.maxHeight = "100%";
  468. displayCode.style.overflow = "auto";
  469. displayDiv.appendChild(displayCode);
  470. while (frame.firstChild) {
  471. frame.removeChild(frame.firstChild);
  472. }
  473. frame.appendChild(displayDiv);
  474. if (typeof Rainbow != null) {
  475. /*
  476. // Works fine in Chrome, but in Firefox it causes Rainbow to fail with "too much recursion".
  477. Rainbow.extend('javascript', [
  478. {
  479. 'name': 'importantcomment',
  480. 'pattern': /(\/\/|\#) @(name|description|include) [\s\S]*?$/gm
  481. },
  482. ], false);
  483. */
  484. setTimeout(function(){
  485. displayCode.setAttribute('data-language', "javascript");
  486. displayCode.style.fontSize = '100%';
  487. Rainbow.color(displayCode.parentNode, function(){
  488. console.log("Rainbow finished.");
  489. });
  490. },50);
  491. }
  492. // frame.addEventListener("mouseout",cleanup,false);
  493. // newLink.title = res.responseText;
  494. var lines = res.responseText.split("\n");
  495. for (var i=0;i<lines.length;i++) {
  496. var line = lines[i];
  497. if (line.match(/@description\s/)) {
  498. var descr = line.replace(/.*@description\s*/,'');
  499. newLink.title = descr;
  500. break;
  501. }
  502. }
  503. }, function(res){
  504. reportToFrame("Failed to load "+url+": HTTP "+res.status);
  505. });
  506.  
  507. /*
  508. frame.style.position = 'fixed';
  509. frame.style.top = evt.clientY+4+'px';
  510. frame.style.left = evt.clientX+4+'px';
  511. */
  512. // frame.style.position = 'absolute';
  513. // frame.style.top = evt.layerY+12+'px';
  514. // frame.style.left = evt.layerX+12+'px';
  515. // frame.style.top = evt.layerY - window.innerHeight*35/100 + 'px';
  516. // frame.style.left = evt.layerX + 64 + 'px';
  517. // frame.style.width = "70%";
  518. // frame.style.height = "70%";
  519. frame.style.position = 'fixed';
  520. frame.style.right = '2%';
  521. frame.style.width = '50%';
  522. frame.style.top = '10%';
  523. frame.style.height = '80%';
  524. frame.style.backgroundColor = 'white';
  525. frame.style.color = 'black';
  526. frame.style.padding = '8px';
  527. frame.style.border = '2px solid #555555';
  528. document.body.appendChild(frame);
  529.  
  530. reportToFrame("Loading...");
  531.  
  532. }
  533.  
  534. function buildSourceViewer(link) {
  535. var newLink = document.createElement("A");
  536. // newLink.href = '#';
  537. newLink.textContent = "Source";
  538.  
  539. newLink.addEventListener('click',function(e) {
  540. loadSourceViewer(link.href,newLink,e);
  541. },false);
  542.  
  543. // TODO: Problem with .user.js files and Chrome:
  544. // In Chrome, opens an empty iframe then the statusbar says it wants to install an extension.
  545. // For Chrome we could try: frame.src = "view-source:"+...;
  546. var extra = document.createElement("span");
  547. extra.appendChild(document.createTextNode("["));
  548. extra.appendChild(newLink);
  549. extra.appendChild(document.createTextNode("]"));
  550. extra.style.paddingLeft = '8px';
  551.  
  552. // link.parentNode.insertBefore(extra,link.nextSibling);
  553. return extra;
  554. }
  555.  
  556. function popupSourceOnHover(link) {
  557. var hoverTimer = null;
  558. function startHover(evt) {
  559. stopHover(evt);
  560. hoverTimer = setTimeout(function(){
  561. loadSourceViewer(link.href, link, evt);
  562. stopHover(evt);
  563. // link.removeEventListener("mouseover",startHover,false);
  564. // link.removeEventListener("mouseout",stopHover,false);
  565. },1500);
  566. }
  567. function stopHover(evt) {
  568. clearTimeout(hoverTimer);
  569. hoverTimer = null;
  570. }
  571. link.addEventListener("mouseover",startHover,false);
  572. link.addEventListener("mouseout",stopHover,false);
  573. // If they click on it before waiting to hover, they probably don't want the popup:
  574. link.addEventListener("click",stopHover,false);
  575. }
  576.  
  577. function buildLiveUserscript(link) {
  578. //// This isn't working any more. data:// lost its power circa 2006 due to abuse.
  579. //// Create a clickable link that returns a sort-of file to the browser using the "data:" protocol.
  580. //// That file would be a new userscript for installation.
  581. //// We can generate the contents of this new userscript at run-time.
  582. //// The current one we generate runs (no @includes), and loads the latest userscript from its website via script injection.
  583. /* DISABLED
  584. // BUG: data:{...}.user.js does not interest my Chromium
  585. var name = getNameFromFilename(link.href)+" Live!";
  586. var name = "Install LiveLoader";
  587. var whatToRun = '(function(){\n'
  588. + ' var ns = document.createElement("script");\n'
  589. + ' ns.src = "' + encodeURI(getCanonicalUrl(link.href)) + '";\n'
  590. + ' document.getElementsByTagName("head")[0].appendChild(ns);\n'
  591. + '})();\n';
  592. var newLink = document.createElement("a");
  593. newLink.textContent = name;
  594. newLink.href = "data:text/javascript;charset=utf-8,"
  595. + "// ==UserScript==%0A"
  596. + "// @namespace LiveLoader%0A"
  597. + "// @name " + name + " LIVE%0A"
  598. + "// @description Loads " +name+ " userscript live from " + link.href + "%0A"
  599. + "// ==/UserScript==%0A"
  600. + "%0A"
  601. + encodeURIComponent(whatToRun) + "%0A"
  602. + "//.user.js";
  603. var extra = document.createElement("span");
  604. extra.appendChild(document.createTextNode("["));
  605. extra.appendChild(newLink);
  606. extra.appendChild(document.createTextNode("]"));
  607. extra.style.paddingLeft = '8px';
  608. link.parentNode.insertBefore(extra,link.nextSibling);
  609. */
  610. return document.createTextNode("");
  611. }
  612.  
  613. function getCanonicalUrl(url) {
  614. if (url.substring(0,1)=="/") {
  615. url = document.location.protocol + "://" + document.location.domain + "/" + url;
  616. }
  617. if (!url.match("://")) {
  618. url = document.location.href.match("^[^?]*/") + url;
  619. }
  620. return url;
  621. }
  622.  
  623. function getNameFromFilename(href) {
  624. var isUserscript = href.match(/\.user\.js$/);
  625. // Remove any leading folders and trailing ".user.js"
  626. var name = href.match(/[^\/]*$/)[0].replace(/\.user\.js$/,'');
  627.  
  628. name = decodeURIComponent(name);
  629.  
  630. // The scripts on userscripts.org do not have their name in the filename,
  631. // but we can get the name from the page title!
  632. if (document.location.host=="userscripts.org" && document.location.pathname=="/scripts/show/"+name) {
  633. var scriptID = name;
  634. name = document.title.replace(/ for Greasemonkey/,'');
  635. // Optionally, include id in name:
  636. name += " ("+scriptID+")";
  637. }
  638.  
  639. if (isUserscript) {
  640. var words = name.split("_");
  641. for (var i=0;i<words.length;i++) {
  642. if (words[i].length) {
  643. var c = words[i].charCodeAt(0);
  644. if (c>=97 && c<=122) {
  645. c = 65 + (c - 97);
  646. words[i] = String.fromCharCode(c) + words[i].substring(1);
  647. }
  648. }
  649. }
  650. name = words.join(" ");
  651. } else {
  652. // It's just a Javascript file
  653. name = "Load "+name;
  654. }
  655. return name;
  656. }
  657.  
  658. var links = document.getElementsByTagName("A");
  659. //// We used to process backwards (for less height recalculation).
  660. //// But this was messing up maxStaticsToRequest.
  661. //// But now backwards processing is restored, to avoid producing multiple bookmarks!
  662. for (var i=links.length;i--;) {
  663. //for (var i=0;i<links.length;i++) {
  664. var link = links[i];
  665.  
  666. if (link.getAttribute('data-make-bookmarklet') === 'false') {
  667. continue;
  668. }
  669.  
  670. // If we see a direct link to a user script, create buttons for it.
  671. if (link.href.match(/\.js$/)) { // \.user\.js
  672. var where = link;
  673. function insert(newElem) {
  674. where.parentNode.insertBefore(newElem,where.nextSibling);
  675. where = newElem;
  676. }
  677. insert(buildLiveBookmarklet(link));
  678. insert(buildStaticBookmarklet(link));
  679. insert(buildLiveUserscript(link));
  680. insert(buildSourceViewer(link));
  681. }
  682.  
  683. // If the current page looks like a Greasemonkey Userscript Folder, then
  684. // create an installer for every subfolder (assuming a script is inside it).
  685. if (document.location.pathname.match(/\/(gm_scripts|userscripts)\//)) {
  686. if (link.href.match(/\/$/) && link.textContent!=="Parent Directory") {
  687. addQuickInstall(link);
  688. }
  689. }
  690.  
  691. }
  692.  
  693. /*
  694. var promise(getURLThen,url) {
  695. var handler;
  696.  
  697. getURLThen(url,handlerFn,handlerFn);
  698.  
  699. function handlerFn(res) {
  700. var source = res.responseText;
  701. if (handler) {
  702. handler(source);
  703. } else {
  704. reportError("No handler set for: "+
  705. }
  706. }
  707.  
  708. return {
  709. then: function(handleResponse){
  710. handler = handleResponse;
  711. }
  712. };
  713. }
  714. */
  715.