Tampermonkey Support Library

to reduce repetition in creating scripts for Tampermonkey support

当前为 2020-09-14 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/23115/847901/Tampermonkey%20Support%20Library.js

  1. var areTmClassesAdded = false;
  2. var isTamperClickAdded = false;
  3. var defaultTamperlabelBkgd = 'radial-gradient(circle, rgba(63,94,251,1) 0%, rgba(0,0,0,0) 50%)';
  4. var tm = {
  5. addGlobalStyle: function (css) {
  6. var head, style;
  7. head = document.getElementsByTagName('head')[0];
  8. if (!head) { return; }
  9. style = document.createElement('style');
  10. style.type = 'text/css';
  11. style.innerHTML = css;
  12. head.appendChild(style);
  13. },
  14. log: function (msg) {
  15. console.log('Tampermonkey: ' + msg);
  16. },
  17. selectText: function (targetClass) {
  18. var textToCopy, range;
  19. try {
  20. if (document.selection) {
  21. range = document.body.createTextRange();
  22. range.moveToElementText(document.getElementsByClassName(targetClass)[0]);
  23. range.select();
  24. } else if (window.getSelection) {
  25. var selection = window.getSelection();
  26. range = document.createRange();
  27. range.selectNode(document.getElementsByClassName(targetClass)[0]);
  28. selection.removeAllRanges();
  29. selection.addRange(range);
  30. }
  31. } catch (err) {
  32. tm.log('Failed to select text');
  33. }
  34. },
  35. sysFriendly: function (el) {
  36. var text = $(el).text();
  37. $(el).text(text.replace(/\/|\:|\<|\>|\\|\||\*|\?/g, '-'));
  38. },
  39. ping: function (ip, callback) { // via http://jsfiddle.net/GSSCD/203/
  40. if (!this.inUse) {
  41. this.status = 'unchecked';
  42. this.inUse = true;
  43. this.callback = callback;
  44. this.ip = ip;
  45. var _that = this;
  46. this.img = new Image();
  47.  
  48. this.img.onload = function () {
  49. _that.inUse = false;
  50. _that.callback('responded');
  51. };
  52.  
  53. this.img.onerror = function (e) {
  54. if (_that.inUse) {
  55. _that.inUse = false;
  56. _that.callback('error', e);
  57. }
  58. };
  59.  
  60. this.start = new Date().getTime();
  61. this.img.src = "http://" + this.ip;
  62. this.timer = setTimeout(function () {
  63. if (_that.inUse) {
  64. _that.inUse = false;
  65. _that.callback('timeout');
  66. }
  67. }, 1500);
  68. }
  69. },
  70. isTagIn: function (targetString, tags) {
  71. var isFound = false;
  72. _.each(tags, function scanTarget (tag) {
  73. if (targetString.toLowerCase().indexOf(tag.toLowerCase()) > -1) {
  74. isFound = true;
  75. }
  76. });
  77. return isFound;
  78. },
  79. copyTextToClipboard: function (text) {
  80. var copyFrom = document.createElement("textarea");
  81. copyFrom.textContent = text;
  82. var body = document.getElementsByTagName('body')[0];
  83. body.appendChild(copyFrom);
  84. copyFrom.select();
  85. document.execCommand('copy');
  86. body.removeChild(copyFrom);
  87. },
  88. showModal: function (modalId, modalBody) {
  89. if ($('#' + modalId).is(":visible")) {
  90. $('#' + modalId).remove();
  91. } else {
  92. $('body').append('<div role="dialog" aria-label="modal for ' + modalId + '" class="popupDetailWindow" id="' + modalId + '">' +
  93. ' <div class="popupDetailTitle">&nbsp;</div>' +
  94. ' <div class="popupDetailContent fingery tamperModalClose" style="text-align:right;" onclick="$(this).parent().remove()">[CLOSE]</div>' +
  95. ' ' + modalBody +
  96. '</div>');
  97. }
  98. },
  99. waitTimers: [],
  100. getContainer: function (opts) {
  101. var options = {
  102. id: opts.id ? opts.id : opts.el.replace(/[ (:)]/g, ''),
  103. el: opts.el,
  104. try: 0,
  105. max: opts.max ? opts.max : 20,
  106. spd: opts.spd ? opts.spd : 500
  107. };
  108. clearTimeout(tm.waitTimers[options.id]);
  109. return new Promise(function (resolve, reject) {
  110. tm.waitForContainerElement(resolve, options);
  111. });
  112. },
  113. getElementsByText: function (str, tag) {
  114. var tagIndex = 0,
  115. foundElements,
  116. tagRange = ['a', 'button', 'input', 'div', 'span'],
  117. checkTag = function (checkStr, checkTag) {
  118. utils.log('checkTag( ' + checkStr + ', ' + checkTag + ')');
  119. return Array.prototype.slice.call(document.getElementsByTagName(checkTag)).filter(el => el.textContent.trim() === checkStr.trim());
  120. };
  121. if (tag != null) {
  122. return checkTag(str, tag);
  123. } else {
  124. while ((foundElements == null || foundElements.length === 0) && tagIndex < tagRange.length) {
  125. foundElements = checkTag(str, tagRange[tagIndex]);
  126. tagIndex++;
  127. };
  128. return foundElements;
  129. }
  130. },
  131. waitForContainerElement: function (resolve, options) {
  132. var $configElement = $(options.el);
  133. if ($configElement.length === 0) {
  134. options.try++;
  135. if (options.try < options.max) {
  136. tm.waitTimers[options.id] = setTimeout(tm.waitForContainerElement.bind(this, resolve, options), options.spd);
  137. } else {
  138. $('#output').val($('#output').val() + 'Maximum searches reached\n');
  139. }
  140. } else {
  141. resolve($configElement);
  142. }
  143. },
  144. copyPreferences: function (prefs) {
  145. tm.copyTextToClipboard(JSON.stringify(prefs));
  146. $.growl.notice({'message': 'Favorites copied to Clipboard'});
  147. },
  148. savePreferences: function (name, value) {
  149. if (value && value.mergeRequestNotes && value.mergeRequestNotes.length === 0) {
  150. $.growl.notice({'message': 'MR NOTES EMPTY', duration: 200});
  151. }
  152. GM_setValue(name, JSON.stringify(value));
  153. },
  154. erasePreferences: function (name) {
  155. GM_setValue(name, JSON.stringify({}));
  156. },
  157. prettyPrint: function (jsonString) {
  158. try {
  159. var obj = JSON.parse(jsonString);
  160. var pretty = JSON.stringify(obj, undefined, 4);
  161. return(pretty);
  162. } catch (e) {
  163. return jsonString;
  164. }
  165. },
  166. setTamperIcon: function (global) {
  167. var scriptName = global.ids != null ? global.ids.scriptName : global.scriptName,
  168. prefsName = global.ids != null ? global.ids.prefsName : global.prefsName,
  169. memsName = global.ids != null ? global.ids.memsName : global.memsName,
  170. mems = global.mems,
  171. prefs = global.prefs,
  172. notes = global.notes;
  173. if (!scriptName || !prefsName || !prefs) {
  174. tm.log('setTamperIcon not properly configured; please send entire global object');
  175. return;
  176. }
  177. // Add Tampermonkey Icon with label to identify this script
  178. if($('.tamperlabel').length > 0) {
  179. if ($('.tamperlabel').prop('title').indexOf(scriptName) === -1) {
  180. $('.tamperlabel').prop('title', $('.tamperlabel').prop('title') + ' | ' + scriptName);
  181. }
  182. } else {
  183. $('body').append('<span class="tamperlabel" title="Tampermonkey scripts: ' + scriptName + '"></span>');
  184. }
  185. if (prefsName != null && prefs != null && !global.handlePrefsLocally) {
  186. var tamperAction = function () {
  187. var modalId = scriptName.replace(/\s/g, '') + 'Options',
  188. modalBody = '',
  189. notesInsert = '';
  190. modalBody += '<div class="popupDetailTitle">' + modalId + '</div><div class="popupDetailContent">&nbsp;</div>';
  191. _.each(prefs, function (value, key) {
  192. if (Array.isArray(value) || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
  193. var thisVal = typeof value === 'object' ? JSON.stringify(value) : value;
  194. modalBody +=
  195. '<div class="popupDetailTitle">' + key + '</div>' +
  196. '<div class="popupDetailContent">';
  197. if (typeof (value) === 'boolean') {
  198. modalBody += ' <button id="toogle' + key + '" class="btn btn-secondary" value="' + value + '">' + value + '</button>';
  199. } else {
  200. modalBody += ' <textarea style="width:100%" id="' + key + '" type="text">' + tm.prettyPrint(thisVal) + '</textarea>';
  201. }
  202. modalBody += '</div>';
  203. } else {
  204. _.each(value, function (value2, key2) {
  205. var thisVal2 = typeof value2 === 'object' ? JSON.stringify(value2) : value2;
  206. modalBody +=
  207. '<div class="popupDetailTitle">' + key2 + '</div>' +
  208. '<div class="popupDetailContent">' +
  209. ' <textarea style="width:100%" id="' + key2 + '" type="text">' + thisVal2 + '</textarea>' +
  210. '</div>';
  211. });
  212. }
  213. });
  214. if (notes != null) {
  215. modalBody += ' <div class="popupDetailTitle">&nbsp;</div><div class="popupDetailContent" style="margin-top:20px;">&nbsp;</div>';
  216. _.each(notes.messages, function (note) {
  217. modalBody += ' <div class="popupDetailTitle tmNote">NOTE:</div><div class="popupDetailContent tmNote">' + note + '</div>';
  218. });
  219. notesInsert = ' <button aria-label="Erase Tampermonkey Session Notes" class="notery tBtn">Erase Notes</button>';
  220. }
  221. modalBody += '<div class="popupDetailTitle">&nbsp;</div><div class="popupDetailContent" style="text-align:right;">' +
  222. notesInsert +
  223. ' <button aria-label="Reset Plugin Memory" class="memery tBtn">Reset Memory</button>' +
  224. ' <button aria-label="Copy Your Favorites to Clipboard" class="copyify tBtn">Copy Preferences</button>' +
  225. ' <button aria-label="Reset Plugin Preferences" class="resetery tBtn tBtnMain">Reset Preferences</button>' +
  226. ' <button aria-label="Save Plugin Preferences" class="savery tBtn tBtnMain">Save</button>' +
  227. ' <button aria-label="Close Preference Window" class="uiClosify tBtn">Close</button>' +
  228. '</div>';
  229.  
  230. tm.showModal(modalId, modalBody);
  231. _.each(prefs, function (value, key) {
  232. if (typeof value === 'boolean') {
  233. $('#toogle' + key).on('click', function (e) {
  234. prefs[key] = !($('#toogle' + key).val() === 'true');
  235. $('#toogle' + key).val(prefs[key]).text(prefs[key]);
  236. tm.savePreferences(prefsName, prefs);
  237. });
  238. }
  239. });
  240.  
  241. // hide the default popup Close because for some weird reason it's not working
  242. $('.popupDetailContent.fingery').hide();
  243.  
  244. $('.savery').on('click', function () {
  245. _.each(prefs, function (value, key) {
  246. if (typeof (value) === 'boolean') {
  247. prefs[key] = $('#toogle' + key).val();
  248. } else {
  249. prefs[key] = $('#' + key).val();
  250. }
  251. });
  252. tm.savePreferences(prefsName, prefs);
  253. alert('Prefernces saved. You may need to refresh.');
  254. });
  255. $('.resetery').on('click', function () {
  256. tm.erasePreferences(prefsName);
  257. alert('Preferences erased. You may need to refresh.');
  258. });
  259. $('.memery').on('click', function () {
  260. tm.erasePreferences(memsName);
  261. alert('Page memory erased.');
  262. });
  263. $('.copyify').on('click', function (e) {
  264. tm.copyPreferences(prefs);
  265. });
  266. $('.uiClosify').on('click', function () {
  267. $('#' + modalId).remove();
  268. });
  269. $('.notery').on('click', function () {
  270. $('.tmNote').remove();
  271. global.notes = null;
  272. tm.initNotes(global);
  273. });
  274.  
  275. return false;
  276. };
  277. if (!isTamperClickAdded) {
  278. $('.tamperlabel').unbind('click').click(tamperAction);
  279. isTamperClickAdded = true;
  280. }
  281. }
  282. },
  283. initNotes: function (global) {
  284. if (global.notes == null) {
  285. global.notes = {
  286. messages: [],
  287. notifiedCount: 0
  288. };
  289. }
  290. },
  291. checkNotes: function (global) {
  292. tm.initNotes(global);
  293. if (global.notes.messages.length !== global.notes.notifiedCount) {
  294. global.notes.notifiedCount = global.notes.messages.length;
  295. var blinkNotify = function () {
  296. if ($('.tamperlabel').css('background-color') === 'rgb(255, 0, 0)') {
  297. $('.tamperlabel').css('background-color', 'transparent');
  298. } else {
  299. $('.tamperlabel').css('background-color', 'rgb(255, 0, 0)');
  300. }
  301. }
  302. setTimeout(function () {
  303. for (var intI = 0; intI < 4; intI ++) {
  304. setTimeout(blinkNotify, 1000 * intI);
  305. };
  306. }, 3000);
  307. }
  308. },
  309. addNote: function (global, theNote) {
  310. var theType,
  311. typeAddedIndex = -1,
  312. compiledNote = function () {
  313. var returnNote = global.scriptName + ': ';
  314. returnNote += (theType != null && theType.length) > 0 ? theType + ': ' : '';
  315. returnNote += theNote;
  316. return returnNote;
  317. };
  318. tm.initNotes(global);
  319. if (typeof theNote === 'object') {
  320. theType = theNote.type;
  321. theNote = theNote.note;
  322. for (var intI = 0; intI < global.notes.messages.length; intI++) {
  323. if (global.notes.messages[intI].indexOf(theType) > -1) {
  324. typeAddedIndex = intI;
  325. }
  326. }
  327. if (typeAddedIndex > -1 && global.notes.messages[typeAddedIndex] !== compiledNote()) {
  328. global.notes.messages.splice(typeAddedIndex, 1);
  329. global.notes.notifiedCount--;
  330. }
  331. }
  332. if (global.notes.messages.indexOf(compiledNote()) === -1) {
  333. global.notes.messages.push(compiledNote());
  334. }
  335. },
  336. addClasses: function () {
  337. if (!areTmClassesAdded) {
  338. areTmClassesAdded = true;
  339.  
  340. // generic
  341. tm.addGlobalStyle('.fingery { margin:0px 13px; cursor:pointer; }');
  342.  
  343. // styles for modal popup
  344. tm.addGlobalStyle('.fingery { cursor: pointer; }');
  345. tm.addGlobalStyle('.popupDetailWindow { position:fixed; z-index: 999999999; top:50px; left:50px; width:75%; height:75%; background:white; border:1px solid black; border-radius: 10px; box-shadow: 10px 10px 5px 0px rgba(0,0,0,0.75); padding:10px; font-size:1.2em; overflow-y:scroll; }');
  346. tm.addGlobalStyle('.popupDetailTitle { float:left; margin-right:10px; width:15%; margin-bottom:5px; font-weight:bold; clear:both; margin-top:2px; }'); // width:6%; min-width:100px;
  347. tm.addGlobalStyle('.popupDetailContent { float:left; width:80%; line-height:0.9em; font-size:0.9em; margin-top:5px; }');
  348. tm.addGlobalStyle('.popupDetailContent .work-item-color { display:none; }');
  349.  
  350. // tamperlabel
  351. tm.addGlobalStyle('.tamperlabel { position:fixed; z-index:999999999; bottom:0px; right:20px; left:unset; cursor: pointer; width:16px; height:16px; background: ' + defaultTamperlabelBkgd + '}');
  352.  
  353. // tamperButtons
  354. tm.addGlobalStyle('.tBtn { background-color:#6c757d !important; height:30px; font-weight:400; color:white; vertical-align:middle; height:40px; border:0; cursor:pointer; }');
  355. tm.addGlobalStyle('.tBtnMain { background-color:#007bff !important; }');
  356.  
  357. //*-jQuery-Growl-*-Copyright-2015-Kevin-Sylvestre-*-1.3.5-*/-
  358. tm.addGlobalStyle('.ontop, #growls-default, #growls-tl, #growls-tr, #growls-bl, #growls-br, #growls-tc, #growls-bc, #growls-cc, #growls-cl, #growls-cr {z-index: 99999999; position: fixed; }');
  359. tm.addGlobalStyle('#growls-default {top: 10px;right: 10px; }');
  360. tm.addGlobalStyle('#growls-tl {top: 10px;left: 10px; }');
  361. tm.addGlobalStyle('#growls-tr {top: 10px;right: 10px; }');
  362. tm.addGlobalStyle('#growls-bl {bottom: 10px;left: 10px; }');
  363. tm.addGlobalStyle('#growls-br {bottom: 10px;right: 10px; }');
  364. tm.addGlobalStyle('#growls-tc {top: 10px;right: 10px;left: 10px; }');
  365. tm.addGlobalStyle('#growls-bc {bottom: 10px;right: 10px;left: 10px; }');
  366. tm.addGlobalStyle('#growls-cc {top: 50%;left: 50%;margin-left: -125px; }');
  367. tm.addGlobalStyle('#growls-cl {top: 50%;left: 10px; }');
  368. tm.addGlobalStyle('#growls-cr {top: 50%;right: 10px; }');
  369. tm.addGlobalStyle('#growls-tc .growl, #growls-bc .growl {margin-left: auto;margin-right: auto; }');
  370. tm.addGlobalStyle('.growl {opacity: 0.8;filter: alpha(opacity=80);position: relative;border-radius: 4px;-webkit-transition: all 0.4s ease-in-out;-moz-transition: all 0.4s ease-in-out;transition: all 0.4s ease-in-out; }');
  371. tm.addGlobalStyle('.growl.growl-incoming {opacity: 0;filter: alpha(opacity=0); }');
  372. tm.addGlobalStyle('.growl.growl-outgoing {opacity: 0;filter: alpha(opacity=0); }');
  373. tm.addGlobalStyle('.growl.growl-small {width: 200px;padding: 5px;margin: 5px; }');
  374. tm.addGlobalStyle('.growl.growl-medium {width: 250px;padding: 10px;margin: 10px; }');
  375. tm.addGlobalStyle('.growl.growl-large {width: 300px;padding: 15px;margin: 15px; }');
  376. tm.addGlobalStyle('.growl.growl-default {color: #FFF;background: #7f8c8d; }');
  377. tm.addGlobalStyle('.growl.growl-error {color: #FFF;background: #C0392B; }');
  378. tm.addGlobalStyle('.growl.growl-notice {color: #FFF;background: #2ECC71; }');
  379. tm.addGlobalStyle('.growl.growl-warning {color: #FFF;background: #F39C12; }');
  380. tm.addGlobalStyle('.growl .growl-close {cursor: pointer;float: right;font-size: 14px;line-height: 18px;font-weight: normal;font-family: helvetica, verdana, sans-serif; }');
  381. tm.addGlobalStyle('.growl .growl-title {font-size: 18px;line-height: 24px; }');
  382. tm.addGlobalStyle('.growl .growl-message {font-size: 12px;line-height: 16px; }');
  383.  
  384. }
  385. }
  386.  
  387. };