Greasy Fork Theme figuccio

Greasy Fork pagina colorata

当前为 2021-09-12 提交的版本,查看 最新版本

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

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

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey,才能安装此脚本。

您需要先安装用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name           Greasy Fork Theme figuccio
// @namespace      https://greasyfork.org/users/237458
// @description    Greasy Fork pagina colorata
// @include        https*://*greasyfork.org*
// @include        https*://sleazyfork.org*
// @version        1.2
// @noframes
// @author         figuccio
// @grant          GM_addStyle
// @grant          GM_setValue
// @grant          GM_getValue
// @grant          GM_registerMenuCommand
// @require        https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js
// @match          *://greasyfork.org/*/script_versions/new*
// @match          *://greasyfork.org/*/scripts/*/versions/new*
// @require        https://gitcdn.link/repo/fuzetsu/userscripts/b38eabf72c20fa3cf7da84ecd2cefe0d4a2116be/wait-for-elements/wait-for-elements.js
// @run-at         document-start
// @grant          GM_openInTab
// @grant          GM_xmlhttpRequest

// ==/UserScript==
window.onload = function() {
    var currentColor = 'violet';
    setInterval(function() {
        document.body.style.backgroundColor = currentColor;
        currentColor = currentColor === '#28768e75' ? '#008000ab' : '#28768e75';
    }, 15000);
};

//GM_addStyle(' body {background-color:#28768e75!important;}');//cambio colore pagina
GM_addStyle('.script-list{background-color:#d4c515d1!important;}');
//mostra risultato per tutte le lingue
if (document.URL == "https://greasyfork.org/it/scripts") window.location.href = "https://greasyfork.org/it/scripts?filter_locale=0";
if (document.URL == "https://sleazyfork.org/it/scripts" ) window.location.href = "https://sleazyfork.org/it/scripts?filter_locale=0";
/*
//autoclick pagina successiva
 $(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {
  var class_name = "next_page";
  var bt = document.getElementsByClassName(class_name)[0];
  bt.click();
  }
});
*/
/////////////autoclick casella editor checkbox
(() => {
  'use strict';
  waitForElems({
    sel: '#enable-source-editor-code',
    stop: true,
    onmatch(checkbox) {
      checkbox.click();
    }
  });
})();
//////////////////////////Change ordinamento script predefinito sui profili utente
(function() {
	'use strict';

	var Util = {
		getQueryParameter: function(name, url) {
			if (!url) url = window.location.href;
			name = name.replace(/[\[\]]/g, "\\$&");
			var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
				results = regex.exec(url);
			if (!results) return null;
			if (!results[2]) return '';
			return decodeURIComponent(results[2].replace(/\+/g, " "));
		},

		setQueryParameter: function(key, value, url) {
			if (!url) url = window.location.href;
			var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
				hash;

			if (re.test(url)) {
				if (typeof value !== 'undefined' && value !== null)
					return url.replace(re, '$1' + key + "=" + value + '$2$3');
				else {
					hash = url.split('#');
					url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
					if (typeof hash[1] !== 'undefined' && hash[1] !== null)
						url += '#' + hash[1];
					return url;
				}
			}
			else {
				if (typeof value !== 'undefined' && value !== null) {
					var separator = url.indexOf('?') !== -1 ? '&' : '?';
					hash = url.split('#');
					url = hash[0] + separator + key + '=' + value;
					if (typeof hash[1] !== 'undefined' && hash[1] !== null)
						url += '#' + hash[1];
					return url;
				}
				else
					return url;
			}
		}
	};

	var Config = {
		load: function() {
			var defaults = {
				sort: 'daily-installs'
			};

			var cfg = GM_getValue('cfg');
			if (!cfg) return defaults;

			return JSON.parse(cfg);
		},

		save: function (cfg) {
			GM_setValue('cfg', JSON.stringify(cfg));
		},

		setup: function() {
			var createSelect = function(label, options, value) {
				var select = document.createElement('select');
				select.style.margin = '2px';
				var optgroup = document.createElement('optgroup');
				if (label) {
					optgroup.setAttribute('label', label);
				}
				select.appendChild(optgroup);
				options.forEach(function(opt) {
					var option = document.createElement('option');
					option.setAttribute('value', opt.value);
					option.textContent = opt.text;
					optgroup.appendChild(option);
				});
				select.value = value;
				return select;
			};

			var createButton = function(text, onclick) {
				var button = document.createElement('button');
				button.style.margin = '2px';
				button.textContent = text;
				button.onclick = onclick;
				return button;
			};

			var init = function(cfg) {
				var div = document.createElement('div');
				div.style.backgroundColor = 'white';
				div.style.border = '1px solid black';
				div.style.position = 'absolute';
				div.style.top = '25px';
				div.style.right = '0';

				var sort = createSelect('Default Sort', [
					{ value: 'daily-installs', text: 'Daily installs' },
					{ value: 'total_installs', text: 'Total installs' },
					{ value: 'ratings', text: 'Ratings' },
					{ value: 'created', text: 'Created' },
					{ value: 'updated', text: 'Updated' },
					{ value: 'name', text: 'Name' }
				], cfg.sort);
				div.appendChild(sort);

				div.appendChild(document.createElement('br'));

				div.appendChild(createButton('Save', function(e) {
					var settings = {
						sort: sort.value
					};
					Config.save(settings);
					div.remove();
				}));

				div.appendChild(createButton('Cancel', function(e) {
					div.remove();
				}));

				document.body.appendChild(div);
			};
			init(Config.load());
		}
	};

	GM_registerMenuCommand('GreasyFork Sort Settings', Config.setup);

	document.addEventListener('DOMContentLoaded', function(e) {
		var dailyInstalls = document.querySelector('#script-list-sort > ul > li:nth-child(1) > a');
		if (dailyInstalls) {
			dailyInstalls.href = Util.setQueryParameter('sort', 'daily-installs', dailyInstalls.href);
		}
	});

	var sort = Util.getQueryParameter('sort');
	if (!sort) {
		var cfg = Config.load();
		window.location.replace(Util.setQueryParameter('sort', cfg.sort));
	}
})();

////////////////scorrimento pagine senza ricarica///////////

(function() {
    'use strict';
    var webType, curSite = {SiteTypeID: 0};
    // Siti web attualmente supportati
    const websiteList = ['greasyfork.org' ];

    if (GM_getValue('menu_disable') == null){GM_setValue('menu_disable', [])};
    if (GM_getValue('menu_discuz_thread_page') == null){GM_setValue('menu_discuz_thread_page', true)};
    // 注册脚本菜单
    if (menu_disable('check')) { // Se il sito web attuale esiste già nell'elenco vietato
        GM_registerMenuCommand('❎ Disabilitato (fare clic per abilitare il sito Web corrente)', function(){menu_disable('del')});
        return
    } else {
        if (websiteList.indexOf(location.host) > -1) {
            webType = 1 // 其他网站
        } else if (document.querySelector('meta[name="author"][content*="Discuz!"], meta[name="generator"][content*="Discuz!"]') || document.getElementById('ft') && document.getElementById('ft').textContent.indexOf('Discuz!') > -1) {
            webType = 2 // 所有 Discuz! 论坛
        } else if (document.getElementById('flarum-loading')) {
            webType = 3 // 所有 Flarum 论坛
        } else {
            GM_registerMenuCommand('❌Il sito web attuale non supporta temporaneamente [clicca per richiedere supporto]', function () {window.GM_openInTab('https://github.com/XIU2/UserScript#xiu2userscript', {active: true,insert: true,setParent: true});window.GM_openInTab('https://greasyfork.org/zh-CN/scripts/419215/feedback', {active: true,insert: true,setParent: true});});
            return
        }
        GM_registerMenuCommand('✅ Abilitato (fare clic per disabilitare il sito Web corrente)', function(){menu_disable('add')});
        if (webType === 2) {
            GM_registerMenuCommand(`${GM_getValue('menu_discuz_thread_page')?'✅':'❎'} 帖子内自动翻页 (仅 Discuz! 论坛)`, function(){menu_switch(GM_getValue('menu_discuz_thread_page'), 'menu_discuz_thread_page', 'Discuz! 论坛帖子内翻页')});
        }
    }

    let DBSite = {

gamersky_ent: {
            SiteTypeID: 0,
            pager: {
                type: 3,
                nextLink: '//div[@class="page_css"]/a[text()="下一页"][@href]',
                pageElement: 'css;.Mid2L_con > *:not(.gs_nc_editor):not(.pagecss):not(.page_css):not(.gs_ccs_solve):not(.post_ding)',
                HT_insert: ['css;.page_css', 1],
                replaceE: 'css;.page_css',
                scrollElement: '.page_css',
                scrollDelta: 100
            }
        },
        gamersky_gl: {
            SiteTypeID: 0,
            pager: {
                type: 3,
                nextLink: '//div[@class="page_css"]/a[text()="下一页"][@href]',
                pageElement: 'css;.Mid2L_con > *:not(.gs_nc_editor):not(.pagecss):not(.gs_ccs_solve):not(.post_ding)',
                HT_insert: ['css;.gs_nc_editor', 1],
                replaceE: 'css;.page_css',
                scrollElement: '.pagecss',
                scrollDelta: -1000
            },
            function: {
                before: gamersky_gl_beforeFunction
            }
        },


        greasyfork: {
            SiteTypeID: 0,
            pager: {
                type: 1,
                nextLink: '//a[@class="next_page"][@href]',
                pageElement: 'css;ol#browse-script-list > li',
                HT_insert: ['css;ol#browse-script-list', 3],
                replaceE: 'css;.pagination',
                scrollDelta: 1000
            }
        },
        greasyfork_feedback: {
            SiteTypeID: 0,
            pager: {
                type: 1,
                nextLink: '//a[@class="next_page"][@href]',
                pageElement: 'css;.script-discussion-list > div',
                HT_insert: ['css;.script-discussion-list', 3],
                replaceE: 'css;.pagination',
                scrollDelta: 1500
            }
        },
        greasyfork_discussions: {
            SiteTypeID: 0,
            pager: {
                type: 1,
                nextLink: '//a[@class="next_page"][@href]',
                pageElement: 'css;.discussion-list > div',
                HT_insert: ['css;.discussion-list', 3],
                replaceE: 'css;.pagination',
                scrollDelta: 1000
            }
        },
        alphacoders_art: {
            SiteTypeID: 0,
            pager: {
                type: 1,
                nextLink: '//a[@id="next_page"][@href]',
                pageElement: 'css;.container-masonry > div',
                HT_insert: ['css;.container-masonry', 3],
                replaceE: '//div[@class="hidden-xs hidden-sm"]/..',
                scrollDelta: 1000
            },
            function: {
                before: alphacoders_art_beforeFunction
            }
        },
        alphacoders_wall: {
            SiteTypeID: 0,
            pager: {
                type: 1,
                nextLink: '//a[@id="next_page"][@href]',
                pageElement: 'css;.thumb-container-big, .avatar-thumb, .thumb-element',
                HT_insert: ['css;.thumb-container-big:nth-last-child(1), .avatar-thumb:nth-last-child(1), .thumb-element:nth-last-child(1)', 4],
                replaceE: '//div[@class="hidden-xs hidden-sm"]/..',
                scrollDelta: 1000
            }
        },
        fitgirl: {
            SiteTypeID: 0,
            pager: {
                type: 1,
                nextLink: '//a[@class="next page-numbers"][@href]',
                pageElement: 'css;article[id^="post-"]',
                HT_insert: ['css;nav.navigation.paging-navigation', 1],
                replaceE: 'css;nav.navigation.paging-navigation',
                scrollDelta: 2000
            }
        }
    };
    // Genera SiteTypeID
    generateID();

    // Utilizzato per il giudizio di script (per alcuni siti Web speciali)
    const SiteType = {
        GAMERSKY_GL: DBSite.gamersky_gl.SiteTypeID
    };


    // <Altri siti>
    if (webType === 1) {
        switch (location.host) {
            case 'apphot.cc': //                  < APPHOT >
            case 'www.ypojie.com': //             < 亿破姐 >
            case 'www.luochenzhimu.com': //       < 落尘之木 >
                if (location.pathname.indexOf('.html') === -1) curSite = DBSite.dux;
                if (location.host === 'apphot.cc') curSite.pager.scrollDelta = 1600; // 对于速度慢的网站,需要增加翻页敏感度
                break;
                // 以上几个都是 WordPress 的 DUX 主题
            case 'www.baidu.com': //              < 百度搜索 >
                if (location.pathname === '/s') curSite = DBSite.baidu;
                break;
            case 'movie.douban.com': //           < 豆瓣评论 >
                if (location.pathname.indexOf('/subject') > -1 && location.pathname.indexOf('/comments') > -1) { //        短评列表
                    curSite = DBSite.douban_subject_comments;
                } else if (location.pathname.indexOf('/subject') > -1 && location.pathname.indexOf('/reviews') > -1) { //  影评列表
                    curSite = DBSite.douban_subject_reviews;
                } else if(location.pathname.indexOf('/subject') > -1 && location.pathname.indexOf('/episode') > -1) { //   电视剧每集评论
                    curSite = DBSite.douban_subject_episode;
                }
                break;
            case 'weibo.com': //                  < 微博评论 >
                curSite = DBSite.weibo_comment;
                break;
            case 'www.58pic.com': //              < 千图网 >
                if (location.pathname.indexOf('/tupian/') > -1) {
                    curSite = DBSite._58pic;
                } else if (location.pathname.indexOf('/c/') > -1) {
                    curSite = DBSite._58pic_c;
                }
                break;
            case 'www.3dmgame.com': //            < 3DM >
                curSite = DBSite._3dmgame;
                break;
            case 'www.ali213.net': //             < 游侠网 >
                curSite = DBSite.ali213_www;
                break;
            case 'gl.ali213.net': //              < 游侠网 - 攻略页 >
                curSite = DBSite.ali213_gl;
                document.lastElementChild.appendChild(document.createElement('style')).textContent = `.n_show_b {display: none !important;}` // 隐藏部分碍事元素
                break;
            case 'www.gamersky.com': //           < 游民星空 >
                if (location.pathname.indexOf('/ent/') > -1) {
                    curSite = DBSite.gamersky_ent;
                } else {
                    curSite = DBSite.gamersky_gl;
                }
                break;
            case 'www.423down.com': //            < 423down >
                if (location.pathname.indexOf('.html') === -1) curSite = DBSite._423down;
                break;
            case 'iao.su': //                     < 不死鸟 >
                curSite = DBSite.iao_su;
                break;
            case 'www.appinn.com': //             < 小众软件 >
                curSite = DBSite.appinn;
                break;
            case 'www.weidown.com': //            < 微当下载 >
                if (location.pathname.indexOf('/search/') > -1) {
                    curSite = DBSite.weidown_search;
                } else if (location.pathname.indexOf('/special/') > -1) {
                    curSite = DBSite.weidown_special;
                } else {
                    curSite = DBSite.weidown;
                }
                break;
            case 'www.iplaysoft.com': //          < 异次元软件 >
                if (location.pathname.indexOf('.html') > -1 || location.pathname.indexOf('/p/') > -1) { // 文章内
                    curSite = DBSite.iplaysoft_postcomments;
                } else { // 其他页面
                    curSite = DBSite.iplaysoft_postslist;
                }
                break;
            case 'www.mpyit.com': //              < 老殁殁漂遥 >
                if (location.pathname === '/' && !location.search) {
                    curSite = DBSite.mpyit;
                } else if (location.pathname.indexOf('/category/') > -1 || location.search.indexOf('?s=') > -1) {
                    curSite = DBSite.mpyit_category;
                }
                break;
            case 'www.yxssp.com': //              < 异星软件空间 >
                curSite = DBSite.yxssp;
                break;
            case 'www.gufengmh8.com': //          < 古风漫画网 >
                curSite = DBSite.gufengmh8;
                break;
            case 'rarbgprx.org': //               < RARBG >
                curSite = DBSite.rarbgprx;
                break;
            case 'pubmed.ncbi.nlm.nih.gov': //    < 国外学术网站 >
                curSite = DBSite.pubmed_postslist;
                break;
            case 'www.afreecatv.com': //          < 直播网站 >
                curSite = DBSite.afreecatv;
                break;
            case 'greasyfork.org': //             < GreasyFork >
                if (location.pathname.indexOf('/scripts') + 8 === location.pathname.length) {
                    curSite = DBSite.greasyfork;
                } else if (location.pathname.lastIndexOf('/feedback') + 9 === location.pathname.length) {
                    curSite = DBSite.greasyfork_feedback;
                } else if (location.pathname.lastIndexOf('/discussions') + 12 === location.pathname.length) {
                    curSite = DBSite.greasyfork_discussions;
                }
                break;
            case 'art.alphacoders.com': //        < 壁纸网站 >
                curSite = DBSite.alphacoders_art;
                setTimeout(alphacoders_art_beforeFunction_0, 1000);
                break;
            case 'wall.alphacoders.com':
            case 'avatars.alphacoders.com':
            case 'mobile.alphacoders.com':
                curSite = DBSite.alphacoders_wall;
                break;
            case 'fitgirl-repacks.site': //       < 游戏下载网站 >
                curSite = DBSite.fitgirl;
                break;
        }
        // < 所有 Discuz!论坛 >
    } else if (webType === 2) {
        if (location.pathname.indexOf('.html') > -1) { //                   判断是不是静态网页(.html 结尾)
            if (location.pathname.indexOf('forum') > -1) { //               各版块帖子列表
                if (document.getElementById('autopbn')) { //                判断是否有 [下一页] 按钮
                    curSite = DBSite.discuz_forum;
                } else {
                    curSite = DBSite.discuz_guide;
                }
            } else if (location.pathname.indexOf('thread') > -1) { //       帖子内
                if (GM_getValue('menu_discuz_thread_page')) {
                    curSite = DBSite.discuz_thread;
                    hidePgbtn(); //                                         隐藏帖子内的 [下一页] 按钮
                }
            } else if(location.pathname.indexOf('search') > -1) { //        搜索结果
                curSite = DBSite.discuz_search;
            }
        } else {
            if (location.search.indexOf('mod=forumdisplay') > -1) { //      各版块帖子列表
                if (document.getElementById('autopbn')) { //                判断是否有 [下一页] 按钮
                    curSite = DBSite.discuz_forum;
                } else {
                    curSite = DBSite.discuz_guide;
                }
            } else if (location.search.indexOf('mod=viewthread') > -1) { // 帖子内
                if (GM_getValue('menu_discuz_thread_page')) {
                    curSite = DBSite.discuz_thread;
                    hidePgbtn(); //                                         隐藏帖子内的 [下一页] 按钮
                }
            } else if (location.search.indexOf('mod=guide') > -1) { //      导读帖子列表
                curSite = DBSite.discuz_guide;
            } else if(location.search.indexOf('mod=space') > -1 && location.search.indexOf('&view=me') > -1) { // 别人的主题/回复
                curSite = DBSite.discuz_youspace;
            } else if (location.search.indexOf('mod=collection') > -1) { // 淘贴列表
                curSite = DBSite.discuz_collection;
            } else if (location.pathname.indexOf('search') > -1) { //       搜索结果
                curSite = DBSite.discuz_search;
            } else { //                                                     考虑到部分论坛的部分板块帖子列表 URL 是自定义的
                curSite = DBSite.discuz_forum;
            }
        }
        // < 所有 Flarum 论坛 >
    } else if (webType === 3) {
        curSite = DBSite.flarum;
    }
    curSite.pageUrl = ''; // 下一页URL
    pageLoading(); // 自动无缝翻页


    //Nascondi il pulsante [Pagina successiva] nel post (Forum Discuz!)
    function hidePgbtn() {
        document.lastChild.appendChild(document.createElement('style')).textContent = '.pgbtn {display: none;}';
    }


    // dux 的插入前函数(加载图片)
    function dux_beforeFunction(pageElems) {
        pageElems.forEach(function (one) {
            let now = one.querySelector('img.thumb[data-src]')
            if (now) {
                now.setAttribute('src', now.dataset.src)
            }
        });
        return pageElems
    }


    // 58pic 的插入前函数(加载图片)
    function _58pic_beforeFunction(pageElems) {
        let is_one = document.querySelector('.qtw-card.place-box.is-one');
        if (is_one && is_one.style.display != 'none') {
            is_one.setAttribute('style', 'display: none;')
        }
        pageElems.forEach(function (one) {
            let now = one.querySelector('img.lazy')
            if (now && now.getAttribute('src') != now.dataset.original) {
                now.setAttribute('src', now.dataset.original)
                now.setAttribute('style', 'display: block;')
            }
        });
        return pageElems
    }

  //La funzione di pre-inserimento di 游民星空攻略 (rimuovi il testo in fondo alla pagina successiva "per altri contenuti correlati: xxx")
    function gamersky_gl_beforeFunction(pageElems) {
        pageElems.forEach(function (one) {
            if (one.tagName === 'P' && one.textContent.indexOf('更多相关内容请关注') > -1) {
                one.style.display = 'none';
            }
        });
        return pageElems
    }

    // iao.su 的插入前函数(加载图片)
    function iao_su_beforeFunction(pageElems) {
        pageElems.forEach(function (one) {
            let now = one.getElementsByClassName('post-card')[0]
            if (now) {
                now.getElementsByClassName('blog-background')[0].style.backgroundImage = 'url("' + now.getElementsByTagName('script')[0].textContent.split("'")[1] + '")';
                //now.getElementsByClassName('blog-background')[0].style.backgroundImage = 'url("' + RegExp("(?<=loadBannerDirect\\(').*(?=', '',)").exec(now.getElementsByTagName('script')[0].textContent)[0]; + '")';
            }
        });
        return pageElems
    }


    // iplaysoft 的插入前函数(加载图片)
    function iplaysoft_postslist_beforeFunction(pageElems) {
        pageElems.forEach(function (one) {
            let now = one.querySelector('img.lazyload')
            if (now && !now.src) {
                now.setAttribute('src', now.dataset.src)
                now.setAttribute('srcset', now.dataset.src)
                now.setAttribute('class', 'lazyloaded')
            }
        });
        return pageElems
    }


    // alphacoders_art 的插入前函数(图片结构调整)
    function alphacoders_art_beforeFunction(pageElems) {
        pageElems.forEach(function (one) {
            one.setAttribute('style','float: left');
        });
        return pageElems
    }
    // alphacoders_art(图片结构调整)
    function alphacoders_art_beforeFunction_0() {
        let pageElems1 = document.querySelectorAll('.container-masonry > div')
        document.querySelector('.container-masonry').style.height = 'auto'
        pageElems1.forEach(function (one) {
            one.setAttribute('style','float: left');
        });
    }


    // gufengmh8
    function gufengmh8_functionNext() {
        if (curSite.pageUrl) { // 如果已经有下一页的 URL 则直接获取
            getPageElems(curSite.pageUrl)
        } else {
            let pageElems = document.querySelector(curSite.pager.pageElement.replace('css;', '')); // 寻找数据所在元素
            if (pageElems) {
                let comicUrl, nextId;
                pageElems.textContent.split(';').forEach(function (one){ // 分号 ; 分割为数组并遍历
                    //console.log(one)
                    if (one.indexOf('comicUrl') > -1) { // 下一页 URL 前半部分
                        comicUrl = one.split('"')[1];
                    } else if (one.indexOf('nextChapterData') > -1) { // 下一页 URL 的后半部分 ID
                        nextId = one.split('"id":')[1].split(',')[0];
                    }
                })
                if (comicUrl && nextId && nextId != 'null') { // 组合到一起就是下一页 URL
                    curSite.pageUrl = comicUrl + nextId + '.html'
                    //console.log(curSite.pageUrl)
                    getPageElems(curSite.pageUrl); // 访问下一页 URL 获取
                }
            }
        }
    }

    // gufengmh8
    function gufengmh8_functionAdd(pageElems) {
        if (pageElems) {
            curSite.pageUrl = ''; // 留空后,下一页 URL 依然交给 gufengmh8_function 函数获取(方便点)
            pageElems = pageElems[0];
            //console.log(pageElems)
            let chapterImages, chapterPath;
            //console.log(pageElems.textContent)
            document.querySelector(curSite.pager.pageElement.replace('css;', '')).innerText = pageElems.textContent; // 将当前网页内的数据所在元素内容改为刚刚获取的下一页数据内容,以便循环获取下一页 URL(gufengmh8_function 函数)
            pageElems.textContent.split(';').forEach(function (one){ // 分号 ; 分割为数组并遍历
                //console.log(one)
                if (one.indexOf('chapterImages') > -1) { // 图片文件名数组
                    chapterImages = one.replace(/^.+\[/, '').replace(']', '').replaceAll('"', '').split(',')
                } else if (one.indexOf('chapterPath') > -1) { // 图片文件路径
                    chapterPath = one.split('"')[1];
                } else if (one.indexOf('pageTitle') > -1) { // 网页标题
                    window.document.title = one.split('"')[1]; // 修改当前网页标题为下一页的标题
                }
            })
            if (chapterImages && chapterPath) {
                let _img = '';
                chapterImages.forEach(function (one2){ // 遍历图片文件名数组,组合为 img 标签
                    _img += '<img src="https://res.xiaoqinre.com/' + chapterPath + one2 + '" data-index="0" style="display: inline-block;">'
                    //console.log('https://res.xiaoqinre.com/' + chapterPath + one2)
                })
                document.querySelector(curSite.pager.HT_insert[0].replace('css;', '')).insertAdjacentHTML(addTo(curSite.pager.HT_insert[1]), _img); // 将 img 标签插入到网页中

            }
        }
    }


    // Volta pagina automatica e senza interruzioni
    function pageLoading() {
        if (curSite.SiteTypeID > 0) {
            windowScroll(function (direction, e) {
                if (direction === 'down') { // 下滑才准备翻页
                    let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop,
                        scrollHeight = window.innerHeight || document.documentElement.clientHeight,
                        scrollDelta = curSite.pager.scrollDelta;
                    if (curSite.pager.type === 3) { // 翻页类型 3
                        let scrollElement = document.querySelector(curSite.pager.scrollElement);
                        //console.log(scrollElement.offsetTop - (scrollTop + scrollHeight), scrollDelta, curSite.SiteTypeID)
                        if (scrollElement.offsetTop - (scrollTop + scrollHeight) <= scrollDelta) {
                            if (curSite.SiteTypeID === SiteType.GAMERSKY_GL) curSite.pager.scrollDelta -= 800 // 游民星空 gl 的比较奇葩,需要特殊处理下
                            ShowPager.loadMorePage();
                        }
                    } else {
                        if (document.documentElement.scrollHeight <= scrollHeight + scrollTop + scrollDelta) {
                            if (curSite.pager.type === 2) { // 翻页类型 2
                                if (curSite.SiteTypeID > 0) { // 如果指定了间隔时间,那么就依靠这个判断时间到了没有~
                                    let autopbn = document.querySelector(curSite.pager.nextLink);
                                    if (autopbn) { // 寻找下一页链接
                                        if (!curSite.pager.nextText) { // 如果没有指定 nextText 就直接点击
                                            autopbn.click();
                                        } else if (autopbn.textContent.indexOf(curSite.pager.nextText) > -1){ // 如果指定了 nextText 就需要判断后再点击(避免已经在加载了,还重复点击)
                                            autopbn.click();
                                        }
                                        // 对于没有按钮文字变化的按钮,可以手动指定间隔时间
                                        if (curSite.pager.intervals) {
                                            let _SiteTypeID = curSite.SiteTypeID;
                                            curSite.SiteTypeID = 0;
                                            setTimeout(function(){curSite.SiteTypeID = _SiteTypeID;}, curSite.pager.intervals)
                                        }
                                    }
                                }
                            } else if (curSite.pager.type === 1) { // 翻页类型 1
                                ShowPager.loadMorePage();
                            } else if (curSite.pager.type === 4) { // 翻页类型 4
                                if (curSite.SiteTypeID > 0) {
                                    curSite.pager.functionNext();
                                    if (curSite.pager.intervals) {
                                        let _SiteTypeID = curSite.SiteTypeID;
                                        curSite.SiteTypeID = 0;
                                        setTimeout(function(){curSite.SiteTypeID = _SiteTypeID;}, curSite.pager.intervals)
                                    }
                                }
                            }
                        }
                    }
                }
            });
        }
    }



    // Abilita/disabilita (sito web attuale)
    function menu_disable(type) {
        switch(type) {
            case 'check':
                if(check()) return true
                return false
                break;
            case 'add':
                add();
                break;
            case 'del':
                del();
                break;
        }

        function check() { // Restituisce vero se c'è, falso se non c'è
            let list = GM_getValue('menu_disable'); // 读取网站列表
            if (list.indexOf(location.host) === -1) return false // 不存在返回假
            return true
        }

        function add() {
            if (check()) return
            let list = GM_getValue('menu_disable'); // 读取网站列表
            list.push(location.host); // 追加网站域名
            GM_setValue('menu_disable', list); // 写入配置
            location.reload(); // 刷新网页
        }

        function del() {
            if (!check()) return
            let list = GM_getValue('menu_disable'), // 读取网站列表
            index = list.indexOf(location.host);
            list.splice(index, 1); // 删除网站域名
            GM_setValue('menu_disable', list); // 写入配置
            location.reload(); // 刷新网页
        }
    }


    // Interruttore del menu
    function menu_switch(menu_status, Name, Tips) {
        if (menu_status === true){
            GM_setValue(`${Name}`, false);
        }else{
            GM_setValue(`${Name}`, true);
        }
        location.reload();
    };


    // 生成 ID
    function generateID() {
        let num = 0
        for (let val in DBSite) {
            DBSite[val].SiteTypeID = num = num + 1;
        }
    }


    // 类型 4 专用
    function getPageElems(url) {
        GM_xmlhttpRequest({
                    url: url,
                    method: 'GET',
                    timeout: 5000,
                    onload: function (response) {
                        try {

                            var newBody = ShowPager.createDocumentByString(response.responseText);
                            let pageElems = getAllElements(curSite.pager.pageElement, newBody, newBody);
                            if (pageElems.length >= 0) {
                                curSite.pager.functionAdd(pageElems)
                            }
                        } catch (e) {
                            console.log(e);
                        }
                    }
                });
    }


    // Inserisci posizione
    function addTo(num) {
        switch (num) {
            case 1:
                return 'beforebegin'
                break;
            case 2:
                return 'afterbegin'
                break;
            case 3:
                return 'beforeend'
                break;
            case 4:
                return 'afterend'
                break;
        }
    }


    // Evento barra di scorrimento
    function windowScroll(fn1) {
        var beforeScrollTop = document.documentElement.scrollTop,
            fn = fn1 || function () {};
        setTimeout(function () { // 延时执行,避免刚载入到页面就触发翻页事件
            window.addEventListener('scroll', function (e) {
                var afterScrollTop = document.documentElement.scrollTop,
                    delta = afterScrollTop - beforeScrollTop;
                if (delta == 0) return false;
                fn(delta > 0 ? 'down' : 'up', e);
                beforeScrollTop = afterScrollTop;
            }, false);
        }, 1000)
    }


    //Modificato da https://greasyfork.org/scripts/14178, https://github.com/machsix/Super-preloader
    var ShowPager = {
        getFullHref: function (e) {
            if(e == null) return '';
            'string' != typeof e && (e = e.getAttribute('href'));
            var t = this.getFullHref.a;
            return t || (this.getFullHref.a = t = document.createElement('a')), (t.href = e), t.href;
        },
        createDocumentByString: function (e) {
            if (e) {
                if ('HTML' !== document.documentElement.nodeName) return (new DOMParser).parseFromString(e, 'application/xhtml+xml');
                var t;
                try { t = (new DOMParser).parseFromString(e, 'text/html');} catch (e) {}
                if (t) return t;
                if (document.implementation.createHTMLDocument) {
                    t = document.implementation.createHTMLDocument('ADocument');
                } else {
                    try {((t = document.cloneNode(!1)).appendChild(t.importNode(document.documentElement, !1)), t.documentElement.appendChild(t.createElement('head')), t.documentElement.appendChild(t.createElement('body')));} catch (e) {}
                }
                if (t) {
                    var r = document.createRange(),
                        n = r.createContextualFragment(e);
                    r.selectNodeContents(document.body);
                    t.body.appendChild(n);
                    for (var a, o = { TITLE: !0, META: !0, LINK: !0, STYLE: !0, BASE: !0}, i = t.body, s = i.childNodes, c = s.length - 1; c >= 0; c--) o[(a = s[c]).nodeName] && i.removeChild(a);
                    return t;
                }
            } else console.error('没有找到要转成 DOM 的字符串');
        },
        loadMorePage: function () {
            if (curSite.pager) {
                let curPageEle = getElementByXpath(curSite.pager.nextLink);
                var url = this.getFullHref(curPageEle);
                //console.log(`${url} ${curPageEle} ${curSite.pageUrl}`);
                if (url === '') return;
                if (curSite.pageUrl === url) return;// 避免重复加载相同的页面
                curSite.pageUrl = url;
                // 读取下一页的数据
                curSite.pager.startFilter && curSite.pager.startFilter();
                GM_xmlhttpRequest({
                    url: url,
                    method: 'GET',
                    timeout: 5000,
                    onload: function (response) {
                        try {
                            console.log('最终 URL:' + response.finalUrl, '返回内容:' + newBody)
                            var newBody = ShowPager.createDocumentByString(response.responseText);
                            let pageElems = getAllElements(curSite.pager.pageElement, newBody, newBody),
                                toElement = getAllElements(curSite.pager.HT_insert[0])[0];
                            //console.log(curSite.pager.pageElement, pageElems)

                            if (pageElems.length >= 0) {
                                // 如果有插入前函数就执行函数
                                if (curSite.function && curSite.function.before) {
                                    if (curSite.function.parameter) { // 如果指定了参数
                                        pageElems = curSite.function.before(curSite.function.parameter);
                                    } else {
                                        pageElems = curSite.function.before(pageElems);
                                    }
                                }

                                // 插入位置
                                let addTo1 = addTo(curSite.pager.HT_insert[1]);
                                // 插入新页面元素
                                pageElems.forEach(function (one) {
                                    toElement.insertAdjacentElement(addTo1, one);
                                });

                                // 替换待替换元素
                                try {
                                    let oriE = getAllElements(curSite.pager.replaceE);
                                    let repE = getAllElements(curSite.pager.replaceE, newBody, newBody);
                                    if (oriE.length === repE.length) {
                                        for (var i = 0; i < oriE.length; i++) {
                                            oriE[i].outerHTML = repE[i].outerHTML;
                                        }
                                    }
                                } catch (e) {
                                    console.log(e);
                                }
                                // 如果有插入后函数就执行函数
                                if (curSite.function && curSite.function.after) {
                                    if (curSite.function.parameter) { // 如果指定了参数
                                        curSite.function.after(curSite.function.parameter);
                                    }else{
                                        curSite.function.after();
                                    }
                                }
                            }
                        } catch (e) {
                            console.log(e);
                        }
                    }
                });
            }
        },
    };

    function getElementByCSS(css, contextNode = document) {
        return contextNode.querySelector(css);
    }
    function getAllElementsByCSS(css, contextNode = document) {
        return [].slice.call(contextNode.querySelectorAll(css));
    }
    function getElementByXpath(xpath, contextNode, doc = document) {
        contextNode = contextNode || doc;
        try {
            const result = doc.evaluate(xpath, contextNode, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
            // 应该总是返回一个元素节点
            return result.singleNodeValue && result.singleNodeValue.nodeType === 1 && result.singleNodeValue;
        } catch (err) {
            throw new Error(`Invalid xpath: ${xpath}`);
        }
    }
    function getAllElementsByXpath(xpath, contextNode, doc = document) {
        contextNode = contextNode || doc;
        const result = [];
        try {
            const query = doc.evaluate(xpath, contextNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
            for (let i = 0; i < query.snapshotLength; i++) {
                const node = query.snapshotItem(i);
                // 如果是 Element 节点
                if (node.nodeType === 1) result.push(node);
            }
        } catch (err) {
            throw new Error(`无效 Xpath: ${xpath}`);
        }
        return result;
    }
    function getAllElements(selector, contextNode = undefined, doc = document, win = window, _cplink = undefined) {
        if (!selector) return [];
        contextNode = contextNode || doc;
        if (typeof selector === 'string') {
            if (selector.search(/^css;/i) === 0) {
                return getAllElementsByCSS(selector.slice(4), contextNode);
            } else {
                return getAllElementsByXpath(selector, contextNode, doc);
            }
        } else {
            const query = selector(doc, win, _cplink);
            if (!Array.isArray(query)) {
                throw new Error('getAllElements 返回错误类型');
            } else {
                return query;
            }
        }
    }
})();