Tampermonkey Support Library

to reduce repetition in creating scripts for Tampermonkey support

当前为 2020-08-22 提交的版本,查看 最新版本

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