Tampermonkey Support Library

to reduce repetition in creating scripts for Tampermonkey support

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

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/23115/848784/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. GM_setValue(name, JSON.stringify(value));
  150. },
  151. erasePreferences: function (name) {
  152. GM_setValue(name, JSON.stringify({}));
  153. },
  154. prettyPrint: function (jsonString) {
  155. try {
  156. var obj = JSON.parse(jsonString);
  157. var pretty = JSON.stringify(obj, undefined, 4);
  158. return(pretty);
  159. } catch (e) {
  160. return jsonString;
  161. }
  162. },
  163. setTamperIcon: function (global) {
  164. var scriptName = global.ids != null ? global.ids.scriptName : global.scriptName,
  165. prefsName = global.ids != null ? global.ids.prefsName : global.prefsName,
  166. memsName = global.ids != null ? global.ids.memsName : global.memsName,
  167. mems = global.mems,
  168. prefs = global.prefs,
  169. notes = global.notes;
  170. if (!scriptName || !prefsName || !prefs) {
  171. tm.log('setTamperIcon not properly configured; please send entire global object');
  172. return;
  173. }
  174. // Add Tampermonkey Icon with label to identify this script
  175. if($('.tamperlabel').length > 0) {
  176. if ($('.tamperlabel').prop('title').indexOf(scriptName) === -1) {
  177. $('.tamperlabel').prop('title', $('.tamperlabel').prop('title') + ' | ' + scriptName);
  178. }
  179. } else {
  180. $('body').append('<span class="tamperlabel" title="Tampermonkey scripts: ' + scriptName + '"></span>');
  181. }
  182. if (prefsName != null && prefs != null && !global.handlePrefsLocally) {
  183. var tamperAction = function (whichCollection, collectionName) {
  184. var modalId = scriptName.replace(/\s/g, '') + 'Options',
  185. modalBody = '',
  186. notesInsert = '';
  187. modalBody += '<div class="popupDetailTitle">' + modalId + '</div><div class="popupDetailContent">&nbsp;</div>';
  188. _.each(whichCollection, function (value, key) {
  189. if (Array.isArray(value) || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
  190. var thisVal = typeof value === 'object' ? JSON.stringify(value) : value;
  191. modalBody +=
  192. '<div class="popupDetailTitle">' + key + '</div>' +
  193. '<div class="popupDetailContent">';
  194. if (typeof (value) === 'boolean') {
  195. modalBody += ' <button id="toogle' + key + '" class="btn btn-secondary" value="' + value + '">' + value + '</button>';
  196. } else {
  197. modalBody += ' <textarea style="width:100%" id="' + key + '" type="text">' + tm.prettyPrint(thisVal) + '</textarea>';
  198. }
  199. modalBody += '</div>';
  200. } else {
  201. _.each(value, function (value2, key2) {
  202. var thisVal2 = typeof value2 === 'object' ? JSON.stringify(value2) : value2;
  203. modalBody +=
  204. '<div class="popupDetailTitle">' + key2 + '</div>' +
  205. '<div class="popupDetailContent">' +
  206. ' <textarea style="width:100%" id="' + key2 + '" type="text">' + thisVal2 + '</textarea>' +
  207. '</div>';
  208. });
  209. }
  210. });
  211. if (notes != null) {
  212. modalBody += ' <div class="popupDetailTitle">&nbsp;</div><div class="popupDetailContent" style="margin-top:20px;">&nbsp;</div>';
  213. _.each(notes.messages, function (note) {
  214. modalBody += ' <div class="popupDetailTitle tmNote">NOTE:</div><div class="popupDetailContent tmNote">' + note + '</div>';
  215. });
  216. notesInsert = ' <button aria-label="Erase Tampermonkey Session Notes" class="notery tBtn">Erase Notes</button>';
  217. }
  218. modalBody += '<div class="popupDetailTitle">&nbsp;</div><div class="popupDetailContent" style="text-align:right;">' +
  219. notesInsert +
  220. ' <button aria-label="Reset Plugin Memory" class="memery tBtn">Reset Memory</button>' +
  221. ' <button aria-label="Copy ' + collectionName + ' to Clipboard" class="copyify tBtn">Copy ' + collectionName + '</button>' +
  222. ' <button aria-label="Reset Plugin Preferences" class="resetery tBtn tBtnMain">Reset Preferences</button>' +
  223. ' <button aria-label="Save Plugin ' + collectionName + '" class="savery tBtn tBtnMain">Save ' + collectionName + '</button>' +
  224. ' <button aria-label="Close Preference Window" class="uiClosify tBtn">Close</button>' +
  225. '</div>';
  226.  
  227. tm.showModal(modalId, modalBody);
  228. _.each(whichCollection, function (value, key) {
  229. if (typeof value === 'boolean') {
  230. $('#toogle' + key).on('click', function (e) {
  231. whichCollection[key] = !($('#toogle' + key).val() === 'true');
  232. $('#toogle' + key).val(whichCollection[key]).text(whichCollection[key]);
  233. tm.savePreferences(collectionName, whichCollection);
  234. });
  235. }
  236. });
  237.  
  238. // hide the default popup Close because for some weird reason it's not working
  239. $('.popupDetailContent.fingery').hide();
  240.  
  241. $('.savery').on('click', function () {
  242. _.each(whichCollection, function (value, key) {
  243. if (typeof (value) === 'boolean') {
  244. whichCollection[key] = $('#toogle' + key).val();
  245. } else {
  246. whichCollection[key] = $('#' + key).val();
  247. }
  248. });
  249. tm.savePreferences(collectionName, whichCollection);
  250. alert(collectionName + ' saved. You may need to refresh.');
  251. });
  252. $('.resetery').on('click', function () {
  253. tm.erasePreferences(prefsName);
  254. alert('Preferences erased. You may need to refresh.');
  255. });
  256. $('.memery').on('click', function () {
  257. tm.erasePreferences(memsName);
  258. alert('Page memory erased.');
  259. });
  260. $('.copyify').on('click', function (e) {
  261. tm.copyPreferences(whichCollection);
  262. });
  263. $('.uiClosify').on('click', function () {
  264. $('#' + modalId).remove();
  265. });
  266. $('.notery').on('click', function () {
  267. $('.tmNote').remove();
  268. global.notes = null;
  269. tm.initNotes(global);
  270. });
  271.  
  272. return false;
  273. };
  274. if (!isTamperClickAdded) {
  275. $('.tamperlabel').unbind('click').on('click', (e) => {
  276. tamperAction(prefs, prefsName);
  277. });
  278. $('.tamperLabel').unbind('contextmenu').on('contextmenu', (e) => {
  279. tamperAction(mems, memsName);
  280. });
  281. isTamperClickAdded = true;
  282. }
  283. }
  284. },
  285. initNotes: function (global) {
  286. if (global.notes == null) {
  287. global.notes = {
  288. messages: [],
  289. notifiedCount: 0
  290. };
  291. }
  292. },
  293. checkNotes: function (global) {
  294. tm.initNotes(global);
  295. if (global.notes.messages.length !== global.notes.notifiedCount) {
  296. global.notes.notifiedCount = global.notes.messages.length;
  297. var blinkNotify = function () {
  298. if ($('.tamperlabel').css('background-color') === 'rgb(255, 0, 0)') {
  299. $('.tamperlabel').css('background-color', 'transparent');
  300. } else {
  301. $('.tamperlabel').css('background-color', 'rgb(255, 0, 0)');
  302. }
  303. }
  304. setTimeout(function () {
  305. for (var intI = 0; intI < 4; intI ++) {
  306. setTimeout(blinkNotify, 1000 * intI);
  307. };
  308. }, 3000);
  309. }
  310. },
  311. addNote: function (global, theNote) {
  312. var theType,
  313. typeAddedIndex = -1,
  314. compiledNote = function () {
  315. var returnNote = global.scriptName + ': ';
  316. returnNote += (theType != null && theType.length) > 0 ? theType + ': ' : '';
  317. returnNote += theNote;
  318. return returnNote;
  319. };
  320. tm.initNotes(global);
  321. if (typeof theNote === 'object') {
  322. theType = theNote.type;
  323. theNote = theNote.note;
  324. for (var intI = 0; intI < global.notes.messages.length; intI++) {
  325. if (global.notes.messages[intI].indexOf(theType) > -1) {
  326. typeAddedIndex = intI;
  327. }
  328. }
  329. if (typeAddedIndex > -1 && global.notes.messages[typeAddedIndex] !== compiledNote()) {
  330. global.notes.messages.splice(typeAddedIndex, 1);
  331. global.notes.notifiedCount--;
  332. }
  333. }
  334. if (global.notes.messages.indexOf(compiledNote()) === -1) {
  335. global.notes.messages.push(compiledNote());
  336. }
  337. },
  338. addClasses: function () {
  339. if (!areTmClassesAdded) {
  340. areTmClassesAdded = true;
  341.  
  342. // generic
  343. tm.addGlobalStyle('.fingery { margin:0px 13px; cursor:pointer; }');
  344.  
  345. // styles for modal popup
  346. tm.addGlobalStyle('.fingery { cursor: pointer; }');
  347. 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; }');
  348. 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;
  349. tm.addGlobalStyle('.popupDetailContent { float:left; width:80%; line-height:0.9em; font-size:0.9em; margin-top:5px; }');
  350. tm.addGlobalStyle('.popupDetailContent .work-item-color { display:none; }');
  351.  
  352. // tamperlabel
  353. tm.addGlobalStyle('.tamperlabel { position:fixed; z-index:999999999; bottom:0px; right:20px; left:unset; cursor: pointer; width:16px; height:16px; background: ' + defaultTamperlabelBkgd + '}');
  354.  
  355. // tamperButtons
  356. tm.addGlobalStyle('.tBtn { background-color:#6c757d !important; height:30px; font-weight:400; color:white; vertical-align:middle; height:40px; border:0; cursor:pointer; }');
  357. tm.addGlobalStyle('.tBtnMain { background-color:#007bff !important; }');
  358.  
  359. //*-jQuery-Growl-*-Copyright-2015-Kevin-Sylvestre-*-1.3.5-*/-
  360. 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; }');
  361. tm.addGlobalStyle('#growls-default {top: 10px;right: 10px; }');
  362. tm.addGlobalStyle('#growls-tl {top: 10px;left: 10px; }');
  363. tm.addGlobalStyle('#growls-tr {top: 10px;right: 10px; }');
  364. tm.addGlobalStyle('#growls-bl {bottom: 10px;left: 10px; }');
  365. tm.addGlobalStyle('#growls-br {bottom: 10px;right: 10px; }');
  366. tm.addGlobalStyle('#growls-tc {top: 10px;right: 10px;left: 10px; }');
  367. tm.addGlobalStyle('#growls-bc {bottom: 10px;right: 10px;left: 10px; }');
  368. tm.addGlobalStyle('#growls-cc {top: 50%;left: 50%;margin-left: -125px; }');
  369. tm.addGlobalStyle('#growls-cl {top: 50%;left: 10px; }');
  370. tm.addGlobalStyle('#growls-cr {top: 50%;right: 10px; }');
  371. tm.addGlobalStyle('#growls-tc .growl, #growls-bc .growl {margin-left: auto;margin-right: auto; }');
  372. 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; }');
  373. tm.addGlobalStyle('.growl.growl-incoming {opacity: 0;filter: alpha(opacity=0); }');
  374. tm.addGlobalStyle('.growl.growl-outgoing {opacity: 0;filter: alpha(opacity=0); }');
  375. tm.addGlobalStyle('.growl.growl-small {width: 200px;padding: 5px;margin: 5px; }');
  376. tm.addGlobalStyle('.growl.growl-medium {width: 250px;padding: 10px;margin: 10px; }');
  377. tm.addGlobalStyle('.growl.growl-large {width: 300px;padding: 15px;margin: 15px; }');
  378. tm.addGlobalStyle('.growl.growl-default {color: #FFF;background: #7f8c8d; }');
  379. tm.addGlobalStyle('.growl.growl-error {color: #FFF;background: #C0392B; }');
  380. tm.addGlobalStyle('.growl.growl-notice {color: #FFF;background: #2ECC71; }');
  381. tm.addGlobalStyle('.growl.growl-warning {color: #FFF;background: #F39C12; }');
  382. tm.addGlobalStyle('.growl .growl-close {cursor: pointer;float: right;font-size: 14px;line-height: 18px;font-weight: normal;font-family: helvetica, verdana, sans-serif; }');
  383. tm.addGlobalStyle('.growl .growl-title {font-size: 18px;line-height: 24px; }');
  384. tm.addGlobalStyle('.growl .growl-message {font-size: 12px;line-height: 16px; }');
  385.  
  386. }
  387. }
  388.  
  389. };