Tampermonkey Support Library

to reduce repetition in creating scripts for Tampermonkey support

Από την 22/07/2019. Δείτε την τελευταία έκδοση.

Αυτός ο κώδικας δεν πρέπει να εγκατασταθεί άμεσα. Είναι μια βιβλιοθήκη για άλλους κώδικες που περιλαμβάνεται μέσω της οδηγίας meta // @require https://update.greatest.deepsurf.us/scripts/23115/719072/Tampermonkey%20Support%20Library.js

θα χρειαστεί να εγκαταστήσετε μια επέκταση όπως το Tampermonkey, το Greasemonkey ή το Violentmonkey για να εγκαταστήσετε αυτόν τον κώδικα.

θα χρειαστεί να εγκαταστήσετε μια επέκταση όπως το Tampermonkey ή το Violentmonkey για να εγκαταστήσετε αυτόν τον κώδικα.

θα χρειαστεί να εγκαταστήσετε μια επέκταση όπως το Tampermonkey ή το Violentmonkey για να εγκαταστήσετε αυτόν τον κώδικα.

θα χρειαστεί να εγκαταστήσετε μια επέκταση όπως το Tampermonkey ή το Userscripts για να εγκαταστήσετε αυτόν τον κώδικα.

You will need to install an extension such as Tampermonkey to install this script.

Θα χρειαστεί να εγκαταστήσετε μια επέκταση διαχείρισης κώδικα χρήστη για να εγκαταστήσετε αυτόν τον κώδικα.

(Έχω ήδη έναν διαχειριστή κώδικα χρήστη, επιτρέψτε μου να τον εγκαταστήσω!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(Έχω ήδη έναν διαχειριστή στυλ χρήστη, επιτρέψτε μου να τον εγκαταστήσω!)

var tm = {
    addGlobalStyle: function(css) {
        var head, style;
        head = document.getElementsByTagName('head')[0];
        if (!head) { return; }
        style = document.createElement('style');
        style.type = 'text/css';
        style.innerHTML = css;
        head.appendChild(style);
    },
    log: function(msg) {
        console.log('Tampermonkey: ' + msg);
    },
    selectText: function (targetClass) {
        var textToCopy, range;
        try {
            if (document.selection) {
                range = document.body.createTextRange();
                range.moveToElementText(document.getElementsByClassName(targetClass)[0]);
                range.select();
            } else if (window.getSelection) {
				var selection = window.getSelection();
                range = document.createRange();
                range.selectNode(document.getElementsByClassName(targetClass)[0]);
				selection.removeAllRanges();
                selection.addRange(range);
            }
        } catch (err) {
            tm.log('Failed to select text');
        }
    },
    sysFriendly: function(el) {
        var text = $(el).text();
        $(el).text(text.replace(/\/|\:|\<|\>|\\|\||\*|\?/g, '-'));
    },
    ping: function (ip, callback) { // via http://jsfiddle.net/GSSCD/203/
        if (!this.inUse) {
            this.status = 'unchecked';
            this.inUse = true;
            this.callback = callback;
            this.ip = ip;
            var _that = this;
            this.img = new Image();

            this.img.onload = function () {
                _that.inUse = false;
                _that.callback('responded');
            };

            this.img.onerror = function (e) {
                if (_that.inUse) {
                    _that.inUse = false;
                    _that.callback('error', e);
                }
            };

            this.start = new Date().getTime();
            this.img.src = "http://" + this.ip;
            this.timer = setTimeout(function () {
                if (_that.inUse) {
                    _that.inUse = false;
                    _that.callback('timeout');
                }
            }, 1500);
        }
    },
    isTagIn: function (targetString, tags) {
        var isFound = false;
        _.each(tags, function scanTarget (tag) {
            if (targetString.toLowerCase().indexOf(tag.toLowerCase()) > -1) {
                isFound = true;
            }
        });
        return isFound;
    },
    copyTextToClipboard: function (text) {
        var copyFrom = document.createElement("textarea");
        copyFrom.textContent = text;
        var body = document.getElementsByTagName('body')[0];
        body.appendChild(copyFrom);
        copyFrom.select();
        document.execCommand('copy');
        body.removeChild(copyFrom);
    },
    showModal: function(modalId, modalBody) {
        if ($('#' + modalId).is(":visible")) {
            $('#' + modalId).remove();
        } else {
            $('body').append('<div class="popupDetailWindow" id="' + modalId + '">' +
                             '    <div class="popupDetailTitle">&nbsp;</div>' +
                             '    <div class="popupDetailContent fingery" style="text-align:right;" onclick="$(this).parent().remove()">[CLOSE]</div>' +
                             '    ' + modalBody +
                             '</div>');
        }
    },
    waitTimers: [],
    getContainer: function (opts) {
        var options = {
            id: opts.id ? opts.id : opts.el.replace(/[ (:)]/g, ''),
            el: opts.el,
            try: 0,
            max: opts.max ? opts.max : 20,
            spd: opts.spd ? opts.spd : 500
        };
        clearTimeout(tm.waitTimers[options.id]);
        return new Promise(function (resolve, reject) {
            tm.waitForContainerElement(resolve, options);
        });
    },
    waitForContainerElement: function (resolve, options) {
        var $configElement = $(options.el);
        if ($configElement.length === 0) {
            options.try++;
            if (options.try < options.max) {
                tm.waitTimers[options.id] = setTimeout(tm.waitForContainerElement.bind(this, resolve, options), options.spd);
            } else {
                $('#output').val($('#output').val() + 'Maximum searches reached\n');
            }
        } else {
            resolve($configElement);
        }
    },
    savePreferences: function (name, value) {
        GM_setValue(name, JSON.stringify(value));
    },
    erasePreferences: function(name) {
        GM_setValue(name, JSON.stringify({}));
    },
    setTamperIcon: function (global) {
		var scriptName = global.scriptName || global.ids.scriptName,
			prefsName = global.prefsName || global.ids.prefsName,
			memsName = global.memsName || global.ids.memsName,
			mems = global.mems,
			prefs = global.prefs,
			notes = global.notes;
		if (!scriptName || !prefsName || !prefs) {
			tm.log('setTamperIcon not properly configured; please send entire global object');
			return;
		}
        // Add Tampermonkey Icon with label to identify this script
        if($('.tamperlabel').length > 0) {
            if ($('.tamperlabel').prop('title').indexOf(scriptName) === -1) {
                $('.tamperlabel').prop('title', $('.tamperlabel').prop('title') + ' | ' + scriptName);
            }
        } else {
            $('body').append('<span class="tamperlabel" title="Tampermonkey scripts: ' + scriptName + '"></span>');
        }
        if (prefsName != null && prefs != null) {
            var tamperAction = function () {
                var modalId = scriptName.replace(/\s/g, '') + 'Options',
                    modalBody = '',
					notesInsert = '';
                _.each(prefs, function (value, key) {
                    if (Array.isArray(value) || typeof value === 'string' || typeof value === 'number') {
                        modalBody += '    <div class="popupDetailTitle">' + key + '</div><div class="popupDetailContent"><input style="width:100%" id="' + key + '" type="text" value="' + value + '"></input></div>';
                    } else {
                        _.each(value, function (value2, key2) {
                            modalBody += '    <div class="popupDetailTitle">' + key2 + '</div><div class="popupDetailContent"><input style="width:100%" id="' + key2 + '" type="text" value="' + value2 + '"></input></div>';
                        });
                    }
                });
				if (notes != null) {
					modalBody += '    <div class="popupDetailTitle">&nbsp;</div><div class="popupDetailContent" style="margin-top:20px;">&nbsp;</div>';
					_.each(notes.messages, function(note) {
						modalBody += '    <div class="popupDetailTitle tmNote">NOTE:</div><div class="popupDetailContent tmNote">' + note + '</div>';
					});
					notesInsert = '    <button aria-label="Erase Tampermonkey Session Notes" class="notery">Erase Notes</button>';
				}
                modalBody += '<div class="popupDetailTitle">&nbsp;</div><div class="popupDetailContent" style="text-align:right;">' +
					notesInsert +
                    '    <button aria-label="Reset Plugin Preferences" class="resetery">Reset Preferences</button>' +
					'    <button aria-label="Reset Plugin Memory" class="memery">Reset Memory</button>' +
                    '    <button aria-label="Save Plugin Preferences" class="savery">Save</button>' +
                    '    <button aria-label="Close Preference Window" class="uiClosify">Close</button>' +
                    '</div>';
                tm.showModal(modalId, modalBody);

                // hide the default popup Close because for some weird reason it's not working
                $('.popupDetailContent.fingery').hide();

                $('.savery').on('click', function() {
                    _.each(prefs, function(value, key) {
                        prefs[key] = $('#' + key).val();
                    });
                    tm.savePreferences(prefsName, prefs);
					alert('Prefernces saved. You may need to refresh.');
                });
                $('.resetery').on('click', function() {
                    tm.erasePreferences(prefsName);
					alert('Preferences erased. You may need to refresh.');
                });
                $('.memery').on('click', function() {
                    tm.erasePreferences(memsName);
                    alert('Page memory erased.');
                });
                $('.uiClosify').on('click', function() {
                    $('#' + modalId).remove();
                });
                $('.notery').on('click', function() {
					$('.tmNote').remove();
                    global.notes = null;
					tm.initNotes(global);
                });

                return false;
            };
            $('.tamperlabel').unbind('click').click(tamperAction);
        }
    },
	initNotes: function(global) {
		if (global.notes == null) {
			global.notes = {
				messages: [],
				notifiedCount: 0
			};
		}	
	},
	checkNotes: function(global) {
		tm.initNotes(global);
		if (global.notes.messages.length !== global.notes.notifiedCount) {
			global.notes.notifiedCount = global.notes.messages.length;
			var blinkNotify = function() {
				if ($('.tamperlabel').css('background-color') === 'rgb(255, 0, 0)') {
					$('.tamperlabel').css('background-color', 'transparent');
				} else {
					$('.tamperlabel').css('background-color', 'rgb(255, 0, 0)');
				}
			}
			setTimeout(function() {
				for (var intI = 0; intI < 4; intI ++) {
					setTimeout(blinkNotify, 1000 * intI);
				};
			}, 3000);
		}
	},
	addNote: function(global, notify) {
		tm.initNotes(global);
		notify = global.scriptName + ': ' + notify;
		if (global.notes.messages.indexOf(notify) === -1) {
			global.notes.messages.push(notify);
		}
	}
};