东方永页机

终极自动翻页 - 加载并拼接下一分页内容至当前页尾,智能适配任意网页

当前为 2024-07-11 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Pagetual
  3. // @name:zh-CN 东方永页机
  4. // @name:zh-TW 東方永頁機
  5. // @name:ja 東方永頁機
  6. // @name:ko 東方永頁機
  7. // @name:ru Pagetual
  8. // @name:de Pagetual
  9. // @name:es Pagetual
  10. // @name:fr Pagetual
  11. // @name:it Pagetual
  12. // @namespace hoothin
  13. // @version 1.9.37.76
  14. // @description Perpetual pages - powerful auto-pager script. Auto fetching next paginated web pages and inserting into current page for infinite scroll. Support thousands of web sites without any rule.
  15. // @description:zh-CN 终极自动翻页 - 加载并拼接下一分页内容至当前页尾,智能适配任意网页
  16. // @description:zh-TW 終極自動翻頁 - 加載並拼接下一分頁內容至當前頁尾,智能適配任意網頁
  17. // @description:ja Webページを自動で読み込み継ぎ足し表示を行うブラウザ拡張です、次のページ付けされた Web ページの自動読み込みと現在のページへの挿入 ルールなしで何千もの Web サイトをサポートします。
  18. // @description:ko 페이지가 매겨진 다음 웹 페이지를 자동으로 로드하고 현재 페이지에 삽입합니다. 규칙 없이 수천 개의 웹 사이트를 지원합니다.
  19. // @description:ru Автоматическая подгрузка следующих страниц и вставка их содержимого в текущую страницу. Поддерживает тысячи сайтов даже с настройками по умолчанию.
  20. // @description:de Automatisches Laden der nächsten paginierten Webseiten und Einfügen in die aktuelle Seite. Unterstützen Sie Tausende von Websites ohne Regeln.
  21. // @description:es Carga automática de las siguientes páginas web paginadas e inserción en la página actual. Admite miles de sitios web sin ninguna regla.
  22. // @description:fr Chargement automatique des pages Web paginées suivantes et insertion dans la page en cours. Prend en charge des milliers de sites Web sans aucune règle.
  23. // @description:it Caricamento automatico delle pagine Web impaginate successive e inserimento nella pagina corrente. Supporta migliaia di siti web senza alcuna regola.
  24. // @author hoothin
  25. // @license MPL-2.0
  26. // @match *://*/*
  27. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAdVBMVEUAAAD3VU33VU32VEz8U073VU32VU33VU32VUz0Uk/3VE32VU32VUz2VU32VU32VU32VU33VU33U0z2VU34Wkv3VE32VUz/mpj/nJj2VUz2VU32VE33VEz2VU32VU32VUz3VE32VEz3VE3/mZf2Vkz2VU3/mpilFFolAAAAJXRSTlMA3Lp/GvTBT5YQLuawZ/DOyZwlPQeKc21N04+FX1bqpm9DNoB4T68ePwAAAitJREFUWMPt1tuasiAUBuCFCG5Rs3QybTPV1/1f4v/3PDkyIojn8x5qBrI+ltAfh32/yysmBKvyXb+njb6bDL9kzTd5SzjDAsYT8nFoGSxYe6BVqoNDp2jFDit25BRgVUAODB4YWcETWVTwVNGiGN5iWtBgg4YMCpsoI38dNunmmWyxUTvbPwwbsYR0fIzZLQ0pTG8eieRmBLMmpdH9uimQEf6TNRnXXKLZHixpJtywLzOgMHtFCqdM64DahHRnOE1dsrekm9wr2WtLcAlpdHwcp1pAJySXYnERclzp4+v19jXdmcTvQUJtz+ZaI4i05/V/UGYrCxbaAsOYoNfIKEQxpqQuzCgJJJ/3f42O8ywEZuMVWi/8hODxGj3GW2b0udkbGULLDOjimAG0S3fLGlBnXQM9irG1CiQdVQi0dqQsOSDlyEEz7Vy9OxxfR71VCXsSB23jMrKJYZXSjw57sqgLn5Z0wolsOCz0RyJkyeYjgz7pwwVq20eboZwtVUl2EnN5gJ50dQZFdryATvABRTr/tJXkUMdaAK5pwtCapwtFLskguwuyMh/Sd9WChQ4sIvIUYSk3PYqQvCQlOC04IfN7PkdjOyRKWhdKXMmiAFt9i3sJ5jxoRuR0vqAghxxwHuqfQE5OHGDKOrwEnqs1DgAZ2e4Eev1d45TN7JfhrQLKgfwMFYAsvp33dXII073aVQLI2gN5S58lfmGnKKFtah7nkgnBZB7zlP7Y/QNiTM6sYNzawwAAAABJRU5ErkJggg==
  28. // @grant GM_xmlhttpRequest
  29. // @grant GM_registerMenuCommand
  30. // @grant GM_notification
  31. // @grant GM_getValue
  32. // @grant GM_setValue
  33. // @grant GM_addStyle
  34. // @grant GM_openInTab
  35. // @grant GM_deleteValue
  36. // @grant GM_info
  37. // @grant GM_setClipboard
  38. // @grant GM.xmlHttpRequest
  39. // @grant GM.registerMenuCommand
  40. // @grant GM.notification
  41. // @grant GM.getValue
  42. // @grant GM.setValue
  43. // @grant GM.addStyle
  44. // @grant GM.openInTab
  45. // @grant GM.deleteValue
  46. // @grant GM.info
  47. // @grant GM.setClipboard
  48. // @homepage https://github.com/hoothin/UserScripts/tree/master/Pagetual
  49. // @supportURL https://github.com/hoothin/UserScripts/issues
  50. // @connect wedata.net
  51. // @connect githubusercontent.com
  52. // @connect ghproxy.com
  53. // @connect hoothin.github.io
  54. // @run-at document-idle
  55. // @connect *
  56. // @contributionURL https://ko-fi.com/hoothin
  57. // @contributionAmount 1
  58. // ==/UserScript==
  59.  
  60. (function() {
  61. 'use strict';
  62. const pauseVideo = () => {
  63. setTimeout(() => {
  64. [].forEach.call(document.querySelectorAll("video"), video => {
  65. video.removeAttribute && video.removeAttribute("autoplay");
  66. video.pause && video.pause();
  67. });
  68. }, 1000);
  69. };
  70. if (window.name === 'pagetual-iframe' || (window.frameElement && window.frameElement.name === 'pagetual-iframe')) {
  71. [].forEach.call(document.querySelectorAll("iframe"), iframe => {
  72. iframe.name = 'pagetual-iframe';
  73. });
  74. var domloaded = function() {
  75. window.parent.postMessage('pagetual-iframe:DOMLoaded', '*');
  76. };
  77. if (window.opera) {
  78. document.addEventListener('DOMContentLoaded', domloaded, false);
  79. pauseVideo();
  80. } else {
  81. domloaded();
  82. if (document.readystate === 'complete') {
  83. pauseVideo();
  84. } else {
  85. window.addEventListener('load', () => {
  86. pauseVideo();
  87. }, false);
  88. }
  89. }
  90. if (getComputedStyle(document.documentElement).display === 'none') {
  91. document.documentElement.style.display = 'block';
  92. }
  93. if (document.body && getComputedStyle(document.body).display === 'none') {
  94. document.body.style.display = 'block';
  95. }
  96. return;
  97. }
  98.  
  99. if (window.top !== window.self) {
  100. try {
  101. if (window.self.innerWidth < 300 || window.self.innerHeight < 300) {
  102. return;
  103. }
  104. } catch(e) {
  105. return;
  106. }
  107. }
  108.  
  109. const noRuleTest = false;
  110. const lang = navigator.appName === "Netscape" ? navigator.language : navigator.userLanguage;
  111. const langData = [
  112. {
  113. // English translation update by github.com/https433, admin@abby0666.xyz.
  114. name: "English",
  115. match: ["en"],
  116. lang: {
  117. enableDebug: "Enable debug output",
  118. updateNotification: "Notification after rules updated",
  119. disable: "Disable",
  120. disableSite: "Toggle disabled state",
  121. disableSiteTips: "Disabled on this site",
  122. enableSiteTips: "Enabled on this site",
  123. enable: "Enable",
  124. toTop: "To Top",
  125. toBottom: "To Bottom",
  126. current: "Current Page",
  127. forceIframe: "Force to join next page",
  128. cancelForceIframe: "Cancel Force join",
  129. configure: "Configure",
  130. firstUpdate: "Click here to initialize the default rule list",
  131. update: "Update online rules",
  132. click2update: "Click to update rules from url now",
  133. loadNow: "Load next automatically",
  134. loadConfirm: "How many pages do you want to load? (0 means infinite)",
  135. noNext: "No next link found, please create a new rule",
  136. passSec: "Updated #t# seconds ago",
  137. passMin: "Updated #t# minutes ago",
  138. passHour: "Updated #t# hours ago",
  139. passDay: "Updated #t# days ago",
  140. cantDel: "Can't delete builtin rules",
  141. confirmDel: "Are you sure you want to delete this rule?",
  142. updateSucc: "Update succeeded",
  143. beginUpdate: "Begin update, wait a moment please",
  144. customUrls: "Import Pagetual or AutoPagerize rule url, one url per line.",
  145. customRules: "Input custom rules. <a href='#t#'>✍️Contribute rules</a>",
  146. save: "Save",
  147. loadingText: "Shojo Now Loading...",
  148. opacity: "Opacity",
  149. opacityPlaceholder: "0: hide spacer",
  150. hideBar: "Hide the pagnation spacer",
  151. hideBarButNoStop: "Hide but not stop",
  152. dbClick2Stop: "Double-click on the blank space to pause",
  153. sortTitle: "Sorting takes effect after the next rule update",
  154. autoRun: "Auto enable (blacklist mode)",
  155. autoLoadNum: "Amount for preload pages",
  156. turnRate: "Turn the next page when it's less than 【X】 times page height from the footer",
  157. inputPageNum: "Enter page number to jump",
  158. enableHistory: "Write browsing history after page turning",
  159. enableHistoryAfterInsert: "Write browsing history immediately after splicing, otherwise write after browsing",
  160. contentVisibility: "Automatically switch contentVisibility to improve rendering performance",
  161. initRun: "Turn pages immediately after opening",
  162. preload: "Preload next page for speeding up",
  163. click2ImportRule: "Click to import base rules link, and then wait until the update is complete: ",
  164. forceAllBody: "Join full body of page?",
  165. openInNewTab: "Open urls of additions in new tab",
  166. importSucc: "Import complete",
  167. import: "Import",
  168. editCurrent: "Edit rule for current",
  169. editBlacklist: "Edit the url blacklist, one entry per line, Support ? * for wildcard",
  170. upBtnImg: "Icon of back to top",
  171. downBtnImg: "Icon of go to footer",
  172. sideControllerIcon: "Icon of sidebar",
  173. loadingTextTitle: "Loading text",
  174. dbClick2StopCtrl: "Ctrl key",
  175. dbClick2StopAlt: "Alt key",
  176. dbClick2StopShift: "Shift key",
  177. dbClick2StopMeta: "Meta key",
  178. dbClick2StopKey: "Shortcut key",
  179. pageElementCss: "Custom style for main page elements",
  180. customCss: "Custom complete css",
  181. firstAlert: "You have not imported the base rule, please select the appropriate rule to import",
  182. picker: "Pagetual page element picker",
  183. closePicker: "Close Pagetual picker",
  184. pickerPlaceholder: "Element selector, (Advanced users only, leave blank otherwise)",
  185. pickerCheck: "Check selector and copy",
  186. switchSelector: "Click to switch element",
  187. gotoEdit: "Go to edit rule with current selector",
  188. manualMode: "Disable splicing, manually advance next page using the right arrow key (or dispatch event 'pagetual.next')",
  189. clickMode: "Disable splicing, automatically click the next page when scrolling to the end of the page",
  190. pageBarMenu: "Click the center of the page bar to open the picker menu",
  191. nextSwitch: "Switch next link",
  192. arrowToScroll: "Press left arrow to scroll back and right arrow to advance page",
  193. sideController: "Display the paging control bar in the sidebar",
  194. sideControllerScroll: "Scroll toggle",
  195. sideControllerAlways: "Always show",
  196. hideLoadingIcon: "Hide loading animation",
  197. hideBarArrow: "Hide arrow for page bar",
  198. duplicate: "Duplicate Pagetual have been installed, check your script manager!",
  199. forceStateIframe: "Embed full page as iframe",
  200. forceStateDynamic: "Load dynamic content via iframe",
  201. forceStateDisable: "Disable page turning on this site",
  202. autoScrollRate: "Scroll speed (1~1000)",
  203. disableAutoScroll: "Stop Auto Scroll",
  204. enableAutoScroll: "Enable Auto Scroll",
  205. toggleAutoScroll: "Toggle Auto Scroll",
  206. ruleRequest: "Rule Request",
  207. page: "Page ",
  208. prevPage: "Prev page",
  209. nextPage: "Next page",
  210. errorRulesMustBeArray: "Rules must be a Array!",
  211. errorJson: "JSON error, Check again!",
  212. editSuccess: "Edit successfully",
  213. errorWrongUrl: "Wrong url, Check again!",
  214. errorAlreadyExists: "A rule already exists!",
  215. settingsSaved: "The settings are saved, refresh to view",
  216. iframe: "Iframe",
  217. dynamic: "Dynamic",
  218. reloadPage: "Edit completed, reload now?",
  219. copied: "Copied",
  220. noValidContent: "No valid content detected, a Captcha may be present",
  221. outOfDate: "The script is outdated, update to the latest version please.",
  222. hideBarTips: "Hide the pagination bar, toggle immersive experience",
  223. setConfigPage: "Set current page as the default configuration page",
  224. wedata2github: "Change the wedata address to the mirror address in the github repository",
  225. addOtherProp: "Add rule property",
  226. addNextSelector: "Add selector content as nextLink",
  227. addPageSelector: "Add selector content as pageElement",
  228. propName: "Enter rule property name",
  229. propValue: "Enter rule property value",
  230. customFirst: "Ignore cache for local custom rules",
  231. rulesExample: "Rules Example",
  232. lastPage: "Reached the last page",
  233. lastPageTips: "Show tips when reaching the last page"
  234. }
  235. },
  236. {
  237. // Translated by SrKalopsia (srkalopsia@gmail.com).
  238. name: "Español",
  239. match: ["es", "es-ES"],
  240. lang: {
  241. enableDebug: "Habilitar salida de depuración",
  242. updateNotification: "Notificación después de actualizar las reglas",
  243. disable: "Desactivar",
  244. disableSite: "Alternar estado desactivado",
  245. disableSiteTips: "Desactivado en este sitio",
  246. enableSiteTips: "Activado en este sitio",
  247. enable: "Habilitar",
  248. toTop: "Ir al inicio",
  249. toBottom: "Ir al final",
  250. current: "Página actual",
  251. forceIframe: "Forzar para unirse a la siguiente página",
  252. cancelForceIframe: "Cancelar unión forzada",
  253. configure: "Configurar",
  254. firstUpdate: "Haga clic aquí para inicializar las reglas",
  255. update: "Actualizar reglas en línea",
  256. click2update: "Haga clic para actualizar las reglas desde la URL ahora",
  257. loadNow: "Cargar el siguiente automáticamente",
  258. loadConfirm: "¿Cuántas páginas desea cargar? (0 significa infinito)",
  259. noNext: "No se encontró el enlace siguiente, por favor cree una nueva regla",
  260. passSec: "Actualizado hace #t# segundos",
  261. passMin: "Actualizado hace #t# minutos",
  262. passHour: "Actualizado hace #t# horas",
  263. passDay: "Actualizado hace #t# días",
  264. cantDel: "No se pueden eliminar las reglas incorporadas",
  265. confirmDel: "¿Está seguro de que desea eliminar esta regla?",
  266. updateSucc: "Actualización exitosa",
  267. beginUpdate: "Comenzar actualización, espere un momento por favor",
  268. customUrls: "Importar URL de reglas de Pagetual o AutoPagerize, una URL por línea",
  269. customRules: "Introduzca reglas personalizadas. <a href='#t#'>✍️Contribuir reglas</a>",
  270. save: "Guardar",
  271. loadingText: "Shojo Cargando...",
  272. opacity: "Opacidad",
  273. opacityPlaceholder: "0: ocultar espaciador",
  274. hideBar: "Ocultar el espaciador de paginación",
  275. hideBarButNoStop: "Ocultar pero no detener",
  276. dbClick2Stop: "Haga doble clic en el espacio en blanco para pausar",
  277. sortTitle: "La ordenación surtirá efecto después de la próxima actualización de reglas",
  278. autoRun: "Habilitar automáticamente (modo lista negra)",
  279. autoLoadNum: "Cantidad de páginas para precargar",
  280. turnRate: "Pasar a la siguiente página cuando esté a menos de 【X】 veces la altura de la página desde el pie de página",
  281. inputPageNum: "Ingrese el número de página para saltar",
  282. enableHistory: "Escribir historial de navegación después de pasar la página",
  283. enableHistoryAfterInsert: "Escribir historial de navegación inmediatamente después de unir, de lo contrario escribir después de navegar",
  284. contentVisibility: "Cambiar automáticamente la visibilidad del contenido para mejorar el rendimiento de renderización",
  285. initRun: "Pasar páginas inmediatamente después de abrir",
  286. preload: "Precargar la siguiente página para acelerar",
  287. click2ImportRule: "Haga clic para importar el enlace de reglas base, luego espere hasta que la actualización esté completa: ",
  288. forceAllBody: "¿Unir el cuerpo completo de la página?",
  289. openInNewTab: "Abrir URLs de adiciones en una nueva pestaña",
  290. importSucc: "Importación completada",
  291. import: "Importar",
  292. editCurrent: "Editar regla para la actual",
  293. editBlacklist: "Editar URLs de la lista negra, una por línea, admite ? * para comodín",
  294. upBtnImg: "Icono de volver al inicio",
  295. downBtnImg: "Icono de ir al pie de página",
  296. sideControllerIcon: "Icono de la barra lateral",
  297. loadingTextTitle: "Texto de carga",
  298. dbClick2StopCtrl: "Tecla Ctrl",
  299. dbClick2StopAlt: "Tecla Alt",
  300. dbClick2StopShift: "Tecla Shift",
  301. dbClick2StopMeta: "Tecla Meta",
  302. dbClick2StopKey: "Tecla de acceso rápido",
  303. pageElementCss: "Estilo personalizado para los elementos principales de la página",
  304. customCss: "CSS completo personalizado",
  305. firstAlert: "No ha importado la regla base, por favor seleccione la regla adecuada para importar",
  306. picker: "Selector de elementos de página de Pagetual",
  307. closePicker: "Cerrar selector de Pagetual",
  308. pickerPlaceholder: "Selector de elementos, déjelo vacío si no tiene idea",
  309. pickerCheck: "Comprobar selector y copiar",
  310. switchSelector: "Haga clic para cambiar el elemento",
  311. gotoEdit: "Ir a editar la regla con el selector actual",
  312. manualMode: "Deshabilitar unión, pasar páginas manualmente con las teclas de flecha derecha (o despachar evento 'pagetual.next')",
  313. clickMode: "Deshabilitar unión, hacer clic automáticamente en la siguiente página al desplazarse al final de la página",
  314. pageBarMenu: "Haga clic en el centro de la barra de página para abrir el menú del selector",
  315. nextSwitch: "Cambiar al siguiente enlace",
  316. arrowToScroll: "Presione la tecla de flecha izquierda para desplazarse anterior y la tecla de flecha derecha para desplazarse siguiente",
  317. sideController: "Mostrar la barra de control de paginación en la barra lateral",
  318. sideControllerScroll: "Alternar desplazamiento",
  319. sideControllerAlways: "Mostrar siempre",
  320. hideLoadingIcon: "Ocultar animación de carga",
  321. hideBarArrow: "Ocultar flecha para la barra de página",
  322. duplicate: "Pagetual duplicado ha sido instalado, ¡revise su gestor de scripts!",
  323. forceStateIframe: "Incrustar página completa como iframe",
  324. forceStateDynamic: "Cargar contenido dinámico a través de iframe",
  325. forceStateDisable: "Deshabilitar pasar páginas en este sitio",
  326. autoScrollRate: "Velocidad de desplazamiento (1~1000)",
  327. disableAutoScroll: "Detener desplazamiento automático",
  328. enableAutoScroll: "Habilitar desplazamiento automático",
  329. toggleAutoScroll: "Alternar desplazamiento automático",
  330. ruleRequest: "Solicitud de regla",
  331. page: "Página ",
  332. prevPage: "Página anterior",
  333. nextPage: "Página siguiente",
  334. errorRulesMustBeArray: "¡Las reglas deben ser un array!",
  335. errorJson: "Error JSON, ¡verifique de nuevo!",
  336. editSuccess: "Editado exitosamente",
  337. errorWrongUrl: "URL incorrecta, ¡verifique de nuevo!",
  338. errorAlreadyExists: "¡Ya existe!",
  339. settingsSaved: "La configuración se ha guardado, actualice para ver",
  340. iframe: "Iframe",
  341. dynamic: "Dinámico",
  342. reloadPage: "Edición completada, ¿recargar página ahora?",
  343. copied: "Copiado",
  344. noValidContent: "No se detectó contenido válido, puede ser necesario realizar una acción de Captcha, haga clic para ver",
  345. outOfDate: "El script está desactualizado, ¡actualice a la última versión a tiempo!",
  346. hideBarTips: "Ocultar la barra de paginación, alternar experiencia inmersiva",
  347. setConfigPage: "Establecer la página actual como la página de configuración predeterminada",
  348. wedata2github: "Cambiar la dirección de wedata a la dirección espejo en el repositorio de GitHub",
  349. addOtherProp: "Agregar propiedad de regla",
  350. addNextSelector: "Agregar contenido del selector como nextLink",
  351. addPageSelector: "Agregar contenido del selector como pageElement",
  352. propName: "Ingrese el nombre de la propiedad de la regla",
  353. propValue: "Ingrese el valor de la propiedad de la regla",
  354. customFirst: "Ignorar caché para reglas personalizadas locales",
  355. rulesExample: "Ejemplo de reglas",
  356. lastPage: "Llegó a la última página",
  357. lastPageTips: "Mostrar consejos al llegar a la última página"
  358. }
  359. },
  360. {
  361. // Translated by Prankster 199 (vfggf95565).
  362. name: "Arabic",
  363. match: ["ar", "ar-AE", "ar-BH", "ar-DZ", "ar-EG", "ar-IQ", "ar-JO", "ar-KW", "ar-LB", "ar-LY", "ar-MA", "ar-OM", "ar-QA", "ar-SA", "ar-SY", "ar-TN", "ar-YE"],
  364. lang: {
  365. enableDebug: "تمكين تصحيح الأخطاء",
  366. updateNotification: "إشعار بعد تحديث القواعد",
  367. disable: "معطل",
  368. disableSite: "تبديل حالة التعطيل/التفعيل للموقع",
  369. disableSiteTips: "معطل على هذا الموقع",
  370. enableSiteTips: "مفعل على هذا الموقع",
  371. enable: "مفعل",
  372. toTop: "إلى الأعلى",
  373. toBottom: "إلى الأسفل",
  374. current: "الصفحة الحالية",
  375. forceIframe: "إجبار على الانضمام للصفحة التالية",
  376. cancelForceIframe: "إلغاء الانضمام القسري",
  377. configure: "إعداد",
  378. firstUpdate: "انقر هنا لتفعيل القواعد لأول مرة",
  379. update: "تحديث القواعد عبر الإنترنت",
  380. click2update: "انقر لتحديث القواعد من الرابط الآن",
  381. loadNow: "تحميل التالي تلقائيًا",
  382. loadConfirm: "كم عدد الصفحات التي ترغب تحميلها؟ (0 يعني لانهائي)",
  383. noNext: "لم يتم العثور على رابط الصفحة التالية، يرجى إنشاء قاعدة جديدة",
  384. passSec: "تم التحديث منذ #t# ثانية",
  385. passMin: "تم التحديث منذ #t# دقيقة",
  386. passHour: "تم التحديث منذ #t# ساعة",
  387. passDay: "تم التحديث منذ #t# يوم",
  388. cantDel: "لا يمكن حذف القواعد المدمجة",
  389. confirmDel: "هل أنت متأكد من حذف هذه القاعدة؟",
  390. updateSucc: "تم التحديث بنجاح",
  391. beginUpdate: "بدأ التحديث، يرجى الانتظار لحظة",
  392. customUrls: "استيراد رابط قاعدة Pagetual أو AutoPagerize، رابط واحد لكل سطر",
  393. customRules: "إدخال القواعد المخصصة. <a href='#t#'>✍️ساهم بالقواعد</a>",
  394. save: "حفظ",
  395. /* From the creator hoothin :
  396. "Shojo Now Loading..." is a meme that refers to the game loading text in the Japanese Touhou (東方) game series. */
  397. loadingText: "جارٍ التحميل...",
  398. opacity: "الشفافية",
  399. opacityPlaceholder: "0: إخفاء الفاصل",
  400. hideBar: "إخفاء الفاصل التصفحي",
  401. hideBarButNoStop: "إخفاء، لكن لا تتوقف",
  402. dbClick2Stop: "انقر مزدوج على المساحة الفارغة للإيقاف",
  403. sortTitle: "يتم تفعيل الفرز بعد التحديث التالي للقواعد",
  404. autoRun: "تمكين تلقائي (وضع القائمة السوداء)",
  405. autoLoadNum: "عدد صفحات التحميل المسبق",
  406. turnRate: "الانتقال للصفحة التالية عندما تكون المسافة أقل من 【X】 مرات ارتفاع الصفحة من التذييل",
  407. inputPageNum: "أدخل رقم الصفحة للانتقال",
  408. enableHistory: "كتابة سجل التصفح بعد تحويل الصفحة",
  409. enableHistoryAfterInsert: "كتابة سجل التصفح فورًا بعد الدمج، أو بعد التصفح",
  410. contentVisibility: "التنقل التلقائي لرؤية المحتوى, لتحسين أداء العرض",
  411. initRun: "الانتقال بين الصفحات فور الفتح",
  412. preload: "تحميل الصفحة التالية مسبقًا لتسريع الأداء",
  413. click2ImportRule: "انقر لاستيراد رابط القواعد الأساسية، ثم انتظر حتى يكتمل التحديث",
  414. forceAllBody: "دمج كامل الصفحة كإطار؟",
  415. openInNewTab: "فتح الروابط الإضافية في علامة تبويب جديدة",
  416. importSucc: "تم الاستيراد بنجاح",
  417. import: "استيراد",
  418. editCurrent: "تحرير القاعدة للحالية",
  419. editBlacklist: "تحرير عناوين القائمة السوداء، سطر بسطر، دعم؟ * للرموز المتحركة",
  420. upBtnImg: "أيقونة العودة إلى الأعلى",
  421. downBtnImg: "أيقونة الانتقال إلى الأسفل",
  422. sideControllerIcon: "أيقونة الشريط الجانبي",
  423. loadingTextTitle: "تحميل النص",
  424. dbClick2StopCtrl: "مفتاح Ctrl",
  425. dbClick2StopAlt: "مفتاح Alt",
  426. dbClick2StopShift: "مفتاح Shift",
  427. dbClick2StopMeta: "مفتاح Meta",
  428. dbClick2StopKey: "مفاتيح الاختصار",
  429. pageElementCss: "نمط مخصص لعناصر الصفحة الرئيسية",
  430. customCss: "مخصص بالكامل CSS نمط",
  431. firstAlert: "لم تستورد القاعدة الأساسية بعد، يرجى اختيار القاعدة المناسبة للاستيراد",
  432. picker: "محدد عناصر الصفحة Pagetual",
  433. closePicker: "إغلاق محدد Pagetual",
  434. pickerPlaceholder: "محدد العناصر، اتركه فارغًا إذا كنت لا تعرف",
  435. pickerCheck: "تحقق من المحدد ونسخ",
  436. switchSelector: "انقر للتبديل بين العناصر",
  437. gotoEdit: "اذهب لتحرير القاعدة بالمحدد الحالي",
  438. manualMode: "تعطيل الدمج/الربط، واستخدام مفتاح الاتجاه الأيمن يدويًا للتمرير، واستخدام مفتاح السهم الأيسر للرجوع",
  439. clickMode: "تعطيل الدمج/الربط، عند التمرير إلى نهاية الصفحة، سيتم النقر تلقائيًا على الصفحة التالية",
  440. pageBarMenu: "انقر على مركز شريط الصفحة لفتح قائمة التحديد",
  441. nextSwitch: "تبديل الرابط التالي",
  442. arrowToScroll: "انقر على مفتاح السهم الأيمن للتمرير التالي ومفتاح السهم الأيسر للتمرير السابق",
  443. sideController: "عرض شريط التحكم في التصفح الترقيم في الشريط الجانبي",
  444. sideControllerScroll: "تبديل التمرير",
  445. sideControllerAlways: "عرض دائمًا",
  446. hideLoadingIcon: "إخفاء رمز التحميل",
  447. hideBarArrow: "إخفاء سهم شريط الصفحة",
  448. duplicate: "تم تثبيت Pagetual مكرر، تحقق من مدير النصوص البرمجية الخاص بك!",
  449. forceStateIframe: "تضمين الصفحة بالكامل كإطار",
  450. forceStateDynamic: "تحميل المحتوى الديناميكي عبر الإطار",
  451. forceStateDisable: "تعطيل تحويل الصفحات على هذا الموقع",
  452. autoScrollRate: "سرعة التمرير (1~1000)",
  453. disableAutoScroll: "إيقاف التمرير التلقائي",
  454. enableAutoScroll: "تمكين التمرير التلقائي",
  455. toggleAutoScroll: "تبديل التمرير التلقائي",
  456. ruleRequest: "طلب قاعدة",
  457. page: "صفحة ",
  458. prevPage: "الصفحة السابقة",
  459. nextPage: "الصفحة التالية",
  460. errorRulesMustBeArray: "يجب أن تكون القواعد مصفوفة!",
  461. errorJson: "خطأ في JSON، تحقق مرة أخرى!",
  462. editSuccess: "تم التحرير بنجاح",
  463. errorWrongUrl: "عنوان URL خاطئ، تحقق مرة أخرى!",
  464. errorAlreadyExists: "موجود بالفعل!",
  465. settingsSaved: "تم حفظ الإعدادات، قم بالتحديث لعرض",
  466. iframe: "إطار",
  467. dynamic: "ديناميكي",
  468. reloadPage: "اكتمل التحرير، إعادة تحميل الصفحة الآن؟",
  469. copied: "تم النسخ",
  470. noValidContent: "لم يتم الكشف عن محتوى صالح، قد يكون الإجراء Captcha مطلوبًا، انقر لعرض",
  471. outOfDate: "النص البرمجي قديم، قم بالتحديث إلى الإصدار الأحدث في الوقت المناسب!",
  472. hideBarTips: "إخفاء شريط التحكم في التصفح الترقيم ، والتبديل لوضع كامل الصفحة",
  473. setConfigPage: "تعيين الصفحة الحالية كصفحة الإعداد الافتراضية",
  474. wedata2github: "تغيير عنوان الويب داتا إلى العنوان البديل المرآة, في مستودع جيت هاب",
  475. addOtherProp: "إضافة خاصية قاعدة",
  476. addNextSelector: "إضافة محتوى المحدد كـ nextLink",
  477. addPageSelector: "إضافة محتوى المحدد كـ pageElement",
  478. propName: "أدخل اسم خاصية القاعدة",
  479. propValue: "أدخل قيمة خاصية القاعدة",
  480. customFirst: "تجاهل ذاكرة التخزين المؤقت للقواعد المخصصة المحلية",
  481. rulesExample: "مثال على القواعد",
  482. lastPage: "تم الوصول إلى الصفحة الأخيرة",
  483. lastPageTips: "عرض تلميحات عند الوصول إلى الصفحة الأخيرة"
  484. }
  485. },
  486. {
  487. name: "简体中文",
  488. match: ["zh-CN", "zh-SG"],
  489. lang: {
  490. enableDebug: "调试模式,输出信息至控制台",
  491. updateNotification: "规则更新后提示",
  492. disable: "暂时禁用",
  493. disableSite: "站点禁用开关",
  494. disableSiteTips: "已在此站禁用",
  495. enableSiteTips: "已在此站启用",
  496. enable: "启用自动翻页",
  497. toTop: "回到顶部",
  498. toBottom: "前往页尾",
  499. current: "当前页",
  500. forceIframe: "强制拼接",
  501. cancelForceIframe: "取消强制拼接",
  502. configure: "打开配置页面",
  503. firstUpdate: "点击此处初始化规则",
  504. update: "更新在线规则",
  505. click2update: "点击立即更新规则",
  506. loadNow: "立即翻页",
  507. loadConfirm: "要翻几页?(0为不间断)",
  508. noNext: "没有找到下一页,请新建规则",
  509. passSec: "更新于 #t# 秒前",
  510. passMin: "更新于 #t# 分钟前",
  511. passHour: "更新于 #t# 小时前",
  512. passDay: "更新于 #t# 天前",
  513. cantDel: "无法删除内置规则",
  514. confirmDel: "是否确认要删除此规则?",
  515. updateSucc: "更新成功",
  516. beginUpdate: "正在更新,请耐心等待,不要关闭页面",
  517. customUrls: "导入 Pagetual 或 AutoPagerize 规则 url,一行一条",
  518. customRules: "输入【东方永页机】格式的自定义规则 <a href='#t#'>✍️贡献规则</a>",
  519. save: "保存设置",
  520. loadingText: "少女祈祷中...",
  521. opacity: "不透明值",
  522. opacityPlaceholder: "0: 隐藏分隔条",
  523. hideBar: "隐藏分页隔条",
  524. hideBarButNoStop: "隐藏但不停止",
  525. dbClick2Stop: "空白处双击暂停翻页",
  526. sortTitle: "排序在下次更新规则后生效",
  527. autoRun: "自动启用,否则为白名单模式",
  528. autoLoadNum: "自动加载指定页数",
  529. turnRate: "距离页尾【X】倍页面高度时就开始翻页",
  530. inputPageNum: "输入页码跳转",
  531. enableHistory: "翻页后写入历史记录",
  532. enableHistoryAfterInsert: "拼接后立即写入历史记录,否则浏览完毕后再行写入",
  533. contentVisibility: "自动切换 contentVisibility,提升渲染性能",
  534. initRun: "打开页面后立即尝试翻页,否则滚动至页尾再翻页",
  535. preload: "翻页前预读下一页,加速浏览",
  536. click2ImportRule: "点击下方任意一条添加规则库,并静待更新成功,请预先打开链接确认能正常访问再行导入:",
  537. forceAllBody: "是否拼接整个页面?",
  538. openInNewTab: "使拼接页面的内容在新页面打开",
  539. importSucc: "导入成功",
  540. import: "导入",
  541. editCurrent: "编辑此站规则",
  542. editBlacklist: "编辑黑名单网址,一行一条,支持? *通配符与正则",
  543. upBtnImg: "回到页首图标",
  544. downBtnImg: "前往页尾图标",
  545. sideControllerIcon: "侧边栏图标",
  546. loadingTextTitle: "加载中文字",
  547. dbClick2StopCtrl: "Ctrl",
  548. dbClick2StopAlt: "Alt",
  549. dbClick2StopShift: "Shift",
  550. dbClick2StopMeta: "Meta",
  551. dbClick2StopKey: "快捷键",
  552. pageElementCss: "页面主体框架的样式",
  553. customCss: "自定义 css",
  554. firstAlert: "你还未导入规则库,请选择合适的规则库导入哦",
  555. picker: "东方永页机主体元素抓取器",
  556. closePicker: "关闭东方永页机抓取器",
  557. pickerPlaceholder: "元素选择器,没想法建议留空",
  558. pickerCheck: "检查你编辑的选择器并复制",
  559. switchSelector: "点击切换元素",
  560. gotoEdit: "使用当前的选择器前往编辑规则",
  561. manualMode: "禁用拼接,手动用右方向键翻页,可使用左方向键返回",
  562. clickMode: "禁用拼接,滚动至页尾时自动点击下一页",
  563. pageBarMenu: "点击分隔条中间弹出菜单",
  564. nextSwitch: "切换其他页码",
  565. arrowToScroll: "左方向键滚动至上一页,右方向键滚动至下一页",
  566. sideController: "在侧边显示翻页控制栏",
  567. sideControllerScroll: "滚动开关",
  568. sideControllerAlways: "始终显示",
  569. hideLoadingIcon: "隐藏加载动画",
  570. hideBarArrow: "隐藏分隔条定位箭头",
  571. duplicate: "检测到永页机重复安装,请删除其他脚本管理器中的永页机!",
  572. forceStateIframe: "以 iframe 嵌入整页",
  573. forceStateDynamic: "通过 iframe 加载动态内容后取出",
  574. forceStateDisable: "在此站禁用",
  575. autoScrollRate: "滚动速度(1~1000)",
  576. disableAutoScroll: "停止自动滚动",
  577. enableAutoScroll: "开启自动滚动",
  578. toggleAutoScroll: "自动滚动开关",
  579. ruleRequest: "适配请求",
  580. page: "Page ",
  581. prevPage: "上一页",
  582. nextPage: "下一页",
  583. errorRulesMustBeArray: "规则必须为数组形式!",
  584. errorJson: "JSON 格式有错,请重新检查!",
  585. editSuccess: "编辑成功",
  586. errorWrongUrl: "URL 错误, 请重新检查!",
  587. errorAlreadyExists: "已经存在!",
  588. settingsSaved: "设置已保存,刷新后生效",
  589. iframe: "强制拼接",
  590. dynamic: "动态加载",
  591. reloadPage: "编辑完成,是否立即刷新页面?",
  592. copied: "已复制",
  593. noValidContent: "没有检测到有效内容,可能需要人机校验,点击查看",
  594. outOfDate: "脚本已过时,请及时更新到最新版本!",
  595. hideBarTips: "隐藏分页隔条,沉浸式体验",
  596. setConfigPage: "将当前页面设为默认配置页",
  597. wedata2github: "将 wedata 地址更改为 github 仓库内的镜像地址",
  598. addOtherProp: "添加规则属性",
  599. addNextSelector: "添加选择器内容为 nextLink",
  600. addPageSelector: "添加选择器内容为 pageElement",
  601. propName: "输入规则属性名",
  602. propValue: "输入规则属性值",
  603. customFirst: "为本地自定义规则忽略缓存",
  604. rulesExample: "自定义规则详解",
  605. lastPage: "已到达最后一页",
  606. lastPageTips: "到达最后一页时进行提示"
  607. }
  608. },
  609. {
  610. name: "正體中文",
  611. match: ["zh", "zh-TW", "zh-HK"],
  612. lang: {
  613. enableDebug: "調試模式,輸出信息至控制台",
  614. updateNotification: "規則更新后提示",
  615. disable: "暫時禁用",
  616. disableSite: "站點禁用開關",
  617. disableSiteTips: "已在此站禁用",
  618. enableSiteTips: "已在此站啟用",
  619. enable: "啟用自動翻頁",
  620. toTop: "回到頂部",
  621. toBottom: "前往頁尾",
  622. current: "當前頁",
  623. forceIframe: "強制拼接",
  624. cancelForceIframe: "取消强制拼接",
  625. configure: "打開配置頁面",
  626. firstUpdate: "點擊此處初始化規則",
  627. update: "更新在綫規則",
  628. click2update: "點擊立即更新規則",
  629. loadNow: "立即翻頁",
  630. loadConfirm: "要翻几頁?(0為不間斷)",
  631. noNext: "沒有找到下一頁,請新建規則",
  632. passSec: "更新于 #t# 秒前",
  633. passMin: "更新于 #t# 分鐘前",
  634. passHour: "更新于 #t# 小時前",
  635. passDay: "更新于 #t# 天前",
  636. cantDel: "無法刪除内置規則",
  637. confirmDel: "是否確認要刪除此規則?",
  638. updateSucc: "更新成功",
  639. beginUpdate: "正在更新,請稍候",
  640. customUrls: "導入 Pagetual 或 AutoPagerize 規則 url,一行一條",
  641. customRules: "輸入【東方永頁機】格式的自定義規則 <a href='#t#'>✍️貢獻規則</a>",
  642. save: "存儲設置",
  643. loadingText: "少女祈禱中...",
  644. opacity: "不透明值",
  645. opacityPlaceholder: "0: 隱藏分隔條",
  646. hideBar: "隱藏分頁隔條",
  647. hideBarButNoStop: "隱藏但不停止",
  648. dbClick2Stop: "空白處雙擊暫停翻頁",
  649. sortTitle: "排序在下次更新規則後生效",
  650. autoRun: "自動啓用,否則為白名單模式",
  651. autoLoadNum: "自動加載指定頁數",
  652. turnRate: "距離頁尾【X】倍頁面高度時就開始翻頁",
  653. inputPageNum: "輸入頁碼跳轉",
  654. enableHistory: "翻頁后寫入歷史記錄",
  655. enableHistoryAfterInsert: "拼接後立即寫入歷史記錄,否則瀏覽完畢後再行寫入",
  656. contentVisibility: "自動切換 contentVisibility,提升渲染性能",
  657. initRun: "打開頁面后立即嘗試翻頁,否則滾動至頁尾再翻頁",
  658. preload: "翻頁前預讀下一頁,加速瀏覽",
  659. click2ImportRule: "點擊下方添加特殊規則庫,并靜待更新成功:",
  660. forceAllBody: "是否拼接整個頁面?",
  661. openInNewTab: "使拼接頁面的内容在新頁面打開",
  662. importSucc: "導入成功",
  663. import: "導入",
  664. editCurrent: "編輯此站規則",
  665. editBlacklist: "編輯黑名單網址,一行一條,支持? *通配符與正則",
  666. upBtnImg: "回到頁首圖標",
  667. downBtnImg: "前往頁尾圖標",
  668. sideControllerIcon: "側邊欄圖標",
  669. loadingTextTitle: "加載中文字",
  670. dbClick2StopCtrl: "Ctrl",
  671. dbClick2StopAlt: "Alt",
  672. dbClick2StopShift: "Shift",
  673. dbClick2StopMeta: "Meta",
  674. dbClick2StopKey: "快捷鍵",
  675. pageElementCss: "頁面主體框架的樣式",
  676. customCss: "自定義 css",
  677. firstAlert: "你還未導入規則庫,請選擇合適的規則庫導入哦",
  678. picker: "東方永頁機主體元素抓取器",
  679. closePicker: "關閉東方永頁機抓取器",
  680. pickerPlaceholder: "元素選擇器,沒想法建議留空",
  681. pickerCheck: "檢查你編輯的選擇器並複製",
  682. switchSelector: "點擊切換元素",
  683. gotoEdit: "使用當前的選擇器前往編輯規則",
  684. manualMode: "禁用拼接,手動用右方向鍵翻頁,左方向鍵返回",
  685. clickMode: "禁用拼接,滾動至頁尾時自動點擊下一頁",
  686. pageBarMenu: "點擊分隔條中間彈出菜單",
  687. nextSwitch: "切換其他頁碼",
  688. arrowToScroll: "左方向鍵滾動至上一頁,右方向鍵滾動至下一頁",
  689. sideController: "在側邊顯示翻頁控制欄",
  690. sideControllerScroll: "滾燈開關",
  691. sideControllerAlways: "始終顯示",
  692. hideLoadingIcon: "隱藏加載動畫",
  693. hideBarArrow: "隱藏分隔條定位箭頭",
  694. duplicate: "檢測到永頁機重複安裝,請刪除其他腳本管理器中的永頁機!",
  695. forceStateIframe: "以 iframe 嵌入整頁",
  696. forceStateDynamic: "通過 iframe 加載動態內容後取出",
  697. forceStateDisable: "在此站禁用",
  698. autoScrollRate: "滾動速度(1~1000)",
  699. disableAutoScroll: "停止自動滾動",
  700. enableAutoScroll: "開啟自動滾動",
  701. toggleAutoScroll: "自動滾動開關",
  702. ruleRequest: "適配請求",
  703. page: "Page ",
  704. prevPage: "上一頁",
  705. nextPage: "下一頁",
  706. errorRulesMustBeArray: "規則必須為陣列形式!",
  707. errorJson: "JSON 格式有錯,請重新檢查!",
  708. editSuccess: "編輯成功",
  709. errorWrongUrl: "URL 錯誤, 請重新檢查!",
  710. errorAlreadyExists: "已經存在!",
  711. settingsSaved: "設置已保存,刷新後生效",
  712. iframe: "強制拼接",
  713. dynamic: "動態加載",
  714. reloadPage: "編輯完成,是否立即刷新頁面?",
  715. copied: "已復制",
  716. noValidContent: "沒有檢測到有效内容,可能需要人機校驗,點擊查看",
  717. outOfDate: "脚本已過時,請及時更新到最新版本!",
  718. hideBarTips: "隱藏分頁隔條,沉浸式體驗",
  719. setConfigPage: "將當前頁面設為默認配置頁",
  720. wedata2github: "將 wedata 地址更改為 github 倉庫內的鏡像地址",
  721. addOtherProp: "添加規則屬性",
  722. addNextSelector: "添加選擇器內容為 nextLink",
  723. addPageSelector: "添加選擇器內容為 pageElement",
  724. propName: "輸入規則屬性名",
  725. propValue: "輸入規則屬性值",
  726. customFirst: "為本地自定義規則忽略緩存",
  727. rulesExample: "自定義規則詳解",
  728. lastPage: "已到達最後一頁",
  729. lastPageTips: "到達最後一頁時進行提示"
  730. }
  731. },
  732. {
  733. name: "日本語",
  734. match: ["ja"],
  735. lang: {
  736. enableDebug: "デバッグモード",
  737. updateNotification: "ルール更新後の通知",
  738. disable: "一時的に無効",
  739. disableSite: "無効状態の切り替え",
  740. disableSiteTips: "このサイトで既に無効になっています",
  741. enableSiteTips: "このサイトで既に有効になっています",
  742. enable: "ページめくりを有効にする",
  743. toTop: "トップに戻る",
  744. toBottom: "ページの下部に移動",
  745. current: "現在のページ",
  746. forceIframe: "強制ステッチ",
  747. cancelForceIframe: "強制ステッチをキャンセル",
  748. configure: "設定ページを開く",
  749. firstUpdate: "ここをクリックしてルールを初期化します",
  750. update: "更新ルール",
  751. click2update: "今すぐルールを更新してください",
  752. loadNow: "今すぐページをめくる",
  753. loadConfirm: "数ページめくりたいですか?(0は途切れない)",
  754. noNext: "次のページが見つかりません、新しいルールを作成してください",
  755. passSec: "#t#秒前に更新",
  756. passMin: "#t#分前に更新",
  757. passHour: "#t#時間前に更新",
  758. passDay: "#t#日前に更新",
  759. cantDel: "組み込みルールを削除できません",
  760. confirmDel: "このルールを削除してもよろしいですか?",
  761. updateSucc: "更新に成功しました",
  762. beginUpdate: "更新中、お待ちください",
  763. customUrls: "インポートルールのURL、1行に1つ",
  764. customRules: "【東方永頁機】の形式でカスタムルールを入力してください <a href='#t#'>✍️寄稿ルール</a>",
  765. save: "設定を保存",
  766. loadingText: "少女祈祷中...",
  767. opacity: "不透明値",
  768. opacityPlaceholder: "0: 隠す",
  769. hideBar: "ページ区切り文字を非表示にします",
  770. hideBarButNoStop: "非表示にするが停止しない",
  771. dbClick2Stop: "空白部分をダブルクリックしてページめくりを一時停止します",
  772. sortTitle: "並べ替えは、次のルールの更新後に有効になります",
  773. autoRun: "自動的に有効",
  774. autoLoadNum: "指定したページ数を自動的に読み込みます",
  775. turnRate: "ページの端からページの高さの【X】倍になったらページをめくる",
  776. inputPageNum: "ジャンプするページ番号を入力",
  777. enableHistory: "ページめくり後の履歴を書く",
  778. enableHistoryAfterInsert: "スプライシングの直後に履歴レコードを書き込みます。それ以外の場合は、閲覧後に書き込みます",
  779. contentVisibility: "contentVisibility を自動的に切り替えてレンダリング パフォーマンスを向上させる",
  780. initRun: "Webページを開いた直後にページをめくる",
  781. preload: "事前に次のページを読む",
  782. click2ImportRule: "以下をクリックして、ルールベースを追加します:",
  783. forceAllBody: "フルページ埋め込み?",
  784. openInNewTab: "スプライスされたページのコンテンツを新しいページで開きます",
  785. importSucc: "インポート完了",
  786. import: "インポート",
  787. editCurrent: "現在のルールの編集",
  788. editBlacklist: "ブラックリストのURLを編集し、1行ずつ、サポート? *ワイルドカード",
  789. upBtnImg: "トップアイコンに戻る",
  790. downBtnImg: "フッターアイコンに移動",
  791. sideControllerIcon: "サイドバー アイコン",
  792. loadingTextTitle: "テキストをロード",
  793. dbClick2StopCtrl: "Ctrlキー",
  794. dbClick2StopAlt: "Altキー",
  795. dbClick2StopShift: "Shiftキー",
  796. dbClick2StopMeta: "Metaキー",
  797. dbClick2StopKey: "Shortcutキー",
  798. pageElementCss: "ページ本文フレームの STYLE",
  799. customCss: "カスタム css",
  800. firstAlert: "ルールベースをインポートしていないため、インポートする適切なルールベースを選択してください",
  801. picker: "Pagetualページ要素ピッカー",
  802. closePicker: "Pagetualピッカーを閉じる",
  803. pickerPlaceholder: "わからない場合は空のままにしてください",
  804. pickerCheck: "セレクターをチェックしてコピー",
  805. switchSelector: "クリックして要素を切り替えます",
  806. gotoEdit: "現在のセレクターでルールを編集する",
  807. manualMode: "スプライシングを無効にします。手動で右の矢印キーを使用してページをめくります",
  808. clickMode: "スティッチングを無効にします。ページの最後までスクロールすると、次のページが自動的にクリックされます",
  809. pageBarMenu: "ページバーの中央をクリックしてメニューをポップアップ表示",
  810. nextSwitch: "次のページに切り替え",
  811. arrowToScroll: "左矢印キーで前へ、右矢印キーで次へ",
  812. sideController: "サイドバーにページング コントロール バーを表示する",
  813. sideControllerScroll: "スクロール スイッチ",
  814. sideControllerAlways: "常に表示",
  815. hideLoadingIcon: "読み込み中のアニメーションを隠す",
  816. hideBarArrow: "分割線の位置矢印を隠す",
  817. duplicate: "Pagetual の重複インストールが検出されました。他のスクリプト マネージャで永続的なページ マシンを削除してください!",
  818. forceStateIframe: "iframe にページ全体を埋め込む",
  819. forceStateDynamic: "iframe 経由で動的コンテンツを読み込む",
  820. forceStateDisable: "このステーションでのページめくりを無効にする",
  821. autoScrollRate: "スクロール速度 (1~1000)",
  822. disableAutoScroll: "自動スクロールを停止します",
  823. enableAutoScroll: "自動スクロールを有効にする",
  824. toggleAutoScroll: "自動スクロールの切り替え",
  825. ruleRequest: "ルール要求",
  826. page: "Page ",
  827. prevPage: "Prev page",
  828. nextPage: "Next page",
  829. errorRulesMustBeArray: "Rules must be a Array!",
  830. errorJson: "JSON error, check again!",
  831. editSuccess: "Edit successfully",
  832. errorWrongUrl: "Wrong url, check again!",
  833. errorAlreadyExists: "Already exists!",
  834. settingsSaved: "The settings are saved, refresh to view",
  835. iframe: "Iframe",
  836. dynamic: "Dynamic",
  837. reloadPage: "Edit completed, reload page now?",
  838. copied: "Copied",
  839. noValidContent: "有効なコンテンツが検出されませんでした。クリックして表示",
  840. outOfDate: "スクリプトが古くなっています。最新バージョンに更新してください。",
  841. hideBarTips: "ページネーション バーを非表示にします。没入型エクスペリエンス",
  842. setConfigPage: "現在のページをデフォルト設定ページとして設定",
  843. wedata2github: "wedata アドレスを github ウェアハウスのミラー アドレスに変更",
  844. addOtherProp: "ルールプロパティを追加",
  845. addNextSelector: "セレクターのコンテンツを nextLink として追加",
  846. addPageSelector: "セレクタ コンテンツを pageElement として追加",
  847. propName: "ルールのプロパティ名を入力してください",
  848. propValue: "ルールのプロパティ値を入力してください",
  849. customFirst: "ローカルカスタムルールのキャッシュを無視する",
  850. rulesExample: "カスタムルールの詳しい説明",
  851. lastPage: "最後のページに到達しました",
  852. lastPageTips: "最後のページに到達した時にヒントを表示する"
  853. }
  854. },
  855. {
  856. name: "Русский",
  857. match: ["ru", "ru-RU"],
  858. lang: {
  859. enableDebug: "Включить отладку",
  860. updateNotification: "Уведомление после обновления правила",
  861. disable: "Выключить",
  862. disableSite: "Включить/выключить на сайте",
  863. disableSiteTips: "Выключено для этого сайта",
  864. enableSiteTips: "Включено для этого сайта",
  865. enable: "Включить",
  866. toTop: "Наверх",
  867. toBottom: "Вниз",
  868. current: "Текущая страница",
  869. forceIframe: "Подгрузить ещё страницу",
  870. cancelForceIframe: "Отменить подгрузку",
  871. configure: "Настройки",
  872. firstUpdate: "Нажмите здесь, чтобы инициализировать правила",
  873. update: "Обновить правила",
  874. click2update: "Нажмите, чтобы обновить правила",
  875. loadNow: "Загрузить следующую страницу",
  876. loadConfirm: "Сколько страниц вы хотите загрузить? (0 означает бесконечность)",
  877. noNext: "Ссылка на следующую страницу не найдена. Пожалуйста, создайте новое правило",
  878. passSec: "Обновлено #t# секунд назад",
  879. passMin: "Обновлено #t# минут назад",
  880. passHour: "Обновлено #t# часов назад",
  881. passDay: "Обновлено #t# дней назад",
  882. cantDel: "Нельзя удалить правила по умолчанию",
  883. confirmDel: "Вы уверены, что хотите удалить эту ссылку?",
  884. updateSucc: "Правила обновлены",
  885. beginUpdate: "Обновление. Пожалуйста, немного подождите",
  886. customUrls: "Ссылки с правилами для импорта. Одна ссылка на строку",
  887. customRules: "Введите пользовательские правила в формате Pagetual. <a href='#t#'>✍️Улучшить встроенные правила</a>",
  888. save: "Сохранить настройки",
  889. loadingText: "Следующая страница подгружается…",
  890. opacity: "Прозрачность",
  891. opacityPlaceholder: "0 - скрыть",
  892. hideBar: "Скрыть разделитель страниц",
  893. hideBarButNoStop: "Скрыть, но не останавливать",
  894. dbClick2Stop: "Двойной клик на странице для выключения",
  895. sortTitle: "Правило сортировки применится после следующего обновления правил",
  896. autoRun: "Автозапуск (режим черного списка)",
  897. autoLoadNum: "Количество страниц для предзагрузки",
  898. turnRate: "Подгрузить страницу, когда она будет в 【X】 раз больше высоты страницы от конца страницы",
  899. inputPageNum: "Введите номер страницы для перехода",
  900. enableHistory: "Записать историю после переключения страниц",
  901. enableHistoryAfterInsert: "Записать запись истории сразу после вставки, иначе записать после просмотра",
  902. contentVisibility: "Автоматически переключать contentVisibility для повышения производительности рендеринга",
  903. initRun: "Подгружать страницы сразу после открытия",
  904. preload: "Предзагрузка следующей страницы",
  905. click2ImportRule: "Нажмите, чтобы импортировать базовые правила: ",
  906. forceAllBody: "Присоединить страницу целиком?",
  907. openInNewTab: "Открыть дополнительные ссылки в новой вкладке",
  908. importSucc: "Импорт завершен",
  909. import: "Импорт",
  910. editCurrent: "Изменить правило для текущего сайта",
  911. editBlacklist: "Изменить черный список. Одна ссылка на строку. Поддерживаются метасимволы: ? и *",
  912. upBtnImg: "Иконка перехода к началу",
  913. downBtnImg: "Иконка перехода к концу",
  914. sideControllerIcon: "Значок боковой панели",
  915. loadingTextTitle: "Текст во время загрузки",
  916. dbClick2StopCtrl: "Ctrl",
  917. dbClick2StopAlt: "Alt",
  918. dbClick2StopShift: "Shift",
  919. dbClick2StopMeta: "Meta",
  920. dbClick2StopKey: "Клавиша",
  921. pageElementCss: "Пользовательский стиль для основных элементов страницы",
  922. customCss: "Полный пользовательский CSS",
  923. firstAlert: "Вы не импортировали базовое правило. Пожалуйста, выберите соответствующее правило для импорта",
  924. picker: "Pagetual: выбор элемента страницы",
  925. closePicker: "Закрыть окно Pagetual",
  926. pickerPlaceholder: "Если не знаете, что тут писать — оставьте поле пустым",
  927. pickerCheck: "Проверить и скопировать селектор",
  928. switchSelector: "Нажмите для выбора элемента",
  929. gotoEdit: "Перейти к редактированию правила с текущим селектором",
  930. manualMode: "Отключить автоматическую загрузку страниц. Загружать вручную с помощью стрелки вправо (или вызова события 'pagetual.next')",
  931. clickMode: "Отключить \"сшивание\" страниц. При прокрутке до конца автоматически переходить на следующую страницу",
  932. pageBarMenu: "Открывать меню кликом на середину панели страниц",
  933. nextSwitch: "Переключить ссылку на следующую страницу",
  934. arrowToScroll: "Листать страницы клавишами со стрелками влево и вправо",
  935. sideController: "Показать справа панель перемещения по вкладке",
  936. sideControllerScroll: "Переключатель прокрутки",
  937. sideControllerAlways: "Всегда показывать",
  938. hideLoadingIcon: "Скрыть анимацию загрузки",
  939. hideBarArrow: "Скрыть кнопки перемещения на разделителе",
  940. duplicate: "Похоже, Pagetual установлен несколько раз. Пожалуйста, удалите Pagetual из других менеджеров скриптов!",
  941. forceStateIframe: "Вставить полную страницу как iframe",
  942. forceStateDynamic: "Загружать динамический контент через iframe",
  943. forceStateDisable: "Отключить перелистывание страниц на этой станции",
  944. autoScrollRate: "Скорость прокрутки (1~1000)",
  945. disableAutoScroll: "Остановить автоматическую прокрутку",
  946. enableAutoScroll: "Включить автопрокрутку",
  947. toggleAutoScroll: "Переключить автопрокрутку",
  948. ruleRequest: "Запрос правил",
  949. page: "Страница ",
  950. prevPage: "Предыдущая страница",
  951. nextPage: "Следующая страница",
  952. errorRulesMustBeArray: "Правила должны быть массивом!",
  953. errorJson: "Ошибка разбора JSON. Пожалуйста, исправьте его",
  954. editSuccess: "Редактирование успешно",
  955. errorWrongUrl: "Ссылка некорректна. Пожалуйста, исправьте её",
  956. errorAlreadyExists: "Уже существует!",
  957. settingsSaved: "Настройки сохранены. Обновите страницы",
  958. iframe: "iframe",
  959. dynamic: "Динамически",
  960. reloadPage: "Редактирование завершено. Обновить страницу?",
  961. copied: "Скопировано",
  962. noValidContent: "Действительный контент не обнаружен, нажмите для просмотра",
  963. outOfDate: "Скрипт устарел, своевременно обновляйте до последней версии!",
  964. hideBarTips: "Скрыть панель разбиения на страницы, иммерсивный опыт",
  965. setConfigPage: "Установить текущую страницу в качестве страницы конфигурации по умолчанию",
  966. wedata2github: "Изменить адрес wedata на зеркальный адрес на складе github",
  967. addOtherProp: "Добавить свойство правила",
  968. addNextSelector: "Добавить содержимое селектора как nextLink",
  969. addPageSelector: "Добавить содержимое селектора как pageElement",
  970. propName: "Введите имя свойства правила",
  971. propValue: "Введите значение свойства правила",
  972. customFirst: "Игнорировать кеш для локальных пользовательских правил",
  973. rulesExample: "Подробное объяснение настраиваемых правил",
  974. lastPage: "Достигнута последняя страница",
  975. lastPageTips: "Показывать подсказки при достижении последней страницы"
  976. }
  977. }
  978. ];
  979. var langList = {};
  980. langData.forEach(lang => {
  981. langList[lang.match[0]] = lang.name;
  982. });
  983. var i18nData = langData[0].lang;
  984. function setLang(la) {
  985. for (let i = 0; i < langData.length; i++) {
  986. let lang = langData[i];
  987. if (lang && lang.match.indexOf(la) !== -1) {
  988. i18nData = lang.lang;
  989. break;
  990. }
  991. }
  992. }
  993. setLang(lang);
  994. var enableDebug = true;
  995. var _GM_xmlhttpRequest, _GM_registerMenuCommand, _GM_notification, _GM_addStyle, _GM_openInTab, _GM_info, _GM_setClipboard;
  996. function i18n(name, param) {
  997. return i18nData[name] ? i18nData[name].replace("#t#", param) : name;
  998. }
  999.  
  1000. function debug(str, title) {
  1001. if (enableDebug) {
  1002. console.log(
  1003. `%cPagetual v.${_GM_info.script.version}】 ${title ? title : 'debug'}:`,
  1004. 'color: yellow;font-size: large;font-weight: bold;background-color: darkblue;',
  1005. str
  1006. );
  1007. }
  1008. }
  1009.  
  1010. if (typeof GM_xmlhttpRequest !== 'undefined') {
  1011. _GM_xmlhttpRequest = GM_xmlhttpRequest;
  1012. } else if (typeof GM !== 'undefined' && typeof GM.xmlHttpRequest !== 'undefined') {
  1013. _GM_xmlhttpRequest = GM.xmlHttpRequest;
  1014. } else {
  1015. _GM_xmlhttpRequest = (f) => {fetch(f.url, {method: f.method || 'GET', body: f.data, headers: f.headers}).then(response => response.text()).then(data => {f.onload && f.onload({response: data})}).catch(f.onerror && f.onerror())};
  1016. }
  1017. if (typeof GM_registerMenuCommand !== 'undefined') {
  1018. _GM_registerMenuCommand = GM_registerMenuCommand;
  1019. } else if (typeof GM !== 'undefined' && typeof GM.registerMenuCommand !== 'undefined') {
  1020. _GM_registerMenuCommand = GM.registerMenuCommand;
  1021. } else {
  1022. _GM_registerMenuCommand = (s, f) => {debug(s); debug(f);};
  1023. }
  1024. if (typeof GM_info !== 'undefined') {
  1025. _GM_info = GM_info;
  1026. } else if (typeof GM !== 'undefined' && typeof GM.info !== 'undefined') {
  1027. _GM_info = GM.info;
  1028. } else {
  1029. _GM_info = {script: {}};
  1030. }
  1031. if (typeof GM_notification !== 'undefined') {
  1032. _GM_notification = GM_notification;
  1033. } else if (typeof GM !== 'undefined' && typeof GM.notification !== 'undefined') {
  1034. _GM_notification = GM.notification;
  1035. } else {
  1036. _GM_notification = (s) => {showTips(String(s.text || s));};
  1037. }
  1038. if (typeof GM_openInTab !== 'undefined') {
  1039. _GM_openInTab = GM_openInTab;
  1040. } else if (typeof GM !== 'undefined' && typeof GM.openInTab !== 'undefined') {
  1041. _GM_openInTab = GM.openInTab;
  1042. } else {
  1043. _GM_openInTab = (s,t) => {window.open(s); debug(t);};
  1044. }
  1045. if (typeof GM_addStyle !== 'undefined') {
  1046. _GM_addStyle = GM_addStyle;
  1047. } else if (typeof GM !== 'undefined' && typeof GM.addStyle !== 'undefined') {
  1048. _GM_addStyle = GM.addStyle;
  1049. } else {
  1050. _GM_addStyle = cssStr => {
  1051. let styleEle = document.createElement("style");
  1052. styleEle.innerHTML = cssStr;
  1053. document.head.appendChild(styleEle);
  1054. return styleEle;
  1055. };
  1056. }
  1057. if (typeof GM_setClipboard !== 'undefined') {
  1058. _GM_setClipboard = GM_setClipboard;
  1059. } else if (typeof GM !== 'undefined' && typeof GM.setClipboard !== 'undefined') {
  1060. _GM_setClipboard = GM.setClipboard;
  1061. } else {
  1062. _GM_setClipboard = (s, i) => {debug(s); debug(i);};
  1063. }
  1064. const _unsafeWindow = (typeof unsafeWindow === 'undefined') ? window : unsafeWindow;//兼容 ios userscripts 的寫法
  1065. const storage = {
  1066. supportGM: typeof GM_getValue === 'function' && typeof GM_getValue('a', 'b') !== 'undefined',
  1067. supportGMPromise: typeof GM !== 'undefined' && typeof GM.getValue === 'function' && typeof GM.getValue('a', 'b') !== 'undefined' && typeof GM.getValue('a', 'b').then === 'function',
  1068. supportCrossSave: function() {
  1069. return this.supportGM || this.supportGMPromise;
  1070. },
  1071. mxAppStorage: (function() {
  1072. try {
  1073. return window.external.mxGetRuntime().storage;
  1074. } catch(e) {
  1075. }
  1076. })(),
  1077. operaUJSStorage: (function() {
  1078. try {
  1079. return window.opera.scriptStorage;
  1080. } catch(e) {
  1081. }
  1082. })(),
  1083. setItem: function(key, value) {
  1084. if (this.supportGMPromise) {
  1085. GM.setValue(key, value);
  1086. if (value === "" && typeof GM !== 'undefined' && typeof GM.deleteValue !== 'undefined') {
  1087. GM.deleteValue(key);
  1088. }
  1089. } else if (this.supportGM) {
  1090. GM_setValue(key, value);
  1091. if (value === "" && typeof GM_deleteValue !== 'undefined') {
  1092. GM_deleteValue(key);
  1093. }
  1094. } else if (this.operaUJSStorage) {
  1095. this.operaUJSStorage.setItem(key, value);
  1096. } else if (this.mxAppStorage) {
  1097. this.mxAppStorage.setConfig(key, value);
  1098. } else if (window.localStorage) {
  1099. window.localStorage.setItem(key, value);
  1100. }
  1101. },
  1102. getItem: function(key, cb) {
  1103. var value;
  1104. if (this.supportGMPromise) {
  1105. value = GM.getValue(key).then(v => {cb(v);});
  1106. return;
  1107. } else if (this.supportGM) {
  1108. value = GM_getValue(key);
  1109. } else if (this.operaUJSStorage) {
  1110. value = this.operaUJSStorage.getItem(key);
  1111. } else if (this.mxAppStorage) {
  1112. value = this.mxAppStorage.getConfig(key);
  1113. } else if (window.localStorage) {
  1114. value = window.localStorage.getItem(key);
  1115. }
  1116. cb(value);
  1117. }
  1118. };
  1119. async function getData(key) {
  1120. return new Promise((resolve) => {
  1121. storage.getItem(key, value => {
  1122. resolve(value);
  1123. });
  1124. });
  1125. }
  1126. async function getListData(list, key) {
  1127. return new Promise((resolve) => {
  1128. storage.getItem(list, listData => {
  1129. let value;
  1130. if (listData) {
  1131. for(var i = 0; i < listData.length; i++) {
  1132. let data = listData[i];
  1133. if (data.k === key) {
  1134. value = data.v;
  1135. break;
  1136. }
  1137. }
  1138. }
  1139. resolve(value);
  1140. });
  1141. });
  1142. }
  1143. function setListData(list, key, value, length) {
  1144. storage.getItem(list, listData => {
  1145. if (!listData) {
  1146. listData = [];
  1147. }
  1148. listData = listData.filter(data => data && data.k !== key);
  1149. if (value !== "") {
  1150. listData.unshift({k: key, v: value});
  1151. if (listData.length > (length || 100)) {
  1152. listData.pop();
  1153. }
  1154. }
  1155. storage.setItem(list, listData);
  1156. });
  1157. }
  1158. const isMobile = ('ontouchstart' in document.documentElement);
  1159. const configPage = [`https://pagetual.hoothin.com/${lang === 'zh-CN' ? 'cn/' : ''}rule.html`,
  1160. "https://github.com/hoothin/UserScripts/tree/master/Pagetual",
  1161. "https://hoothin.github.io/UserScripts/Pagetual/"];
  1162. const firstRunPage = "https://pagetual.hoothin.com/firstRun";
  1163. const guidePage = /^https?:\/\/.*pagetual.*rule\.html/i;
  1164. const ruleImportUrlReg = /greasyfork\.org\/.*scripts\/438684(\-[^\/]*)?(\/discussions|\/?$|\/feedback)|github\.com\/hoothin\/UserScripts\/(tree\/master\/Pagetual|issues)|^https:\/\/pagetual\.hoothin\.com\/.*firstRun\.html/i;
  1165. const allOfBody = "body>*";
  1166. const mainSel = ["article,.article","[role=main],main,.main,#main","#results"];
  1167. const nextTextReg1 = new RegExp("\u005e\u7ffb\u003f\u005b\u4e0b\u540e\u5f8c\u6b21\u005d\u005b\u4e00\u30fc\u0031\u005d\u003f\u005b\u9875\u9801\u5f20\u5f35\u005d\u007c\u005e\u006e\u0065\u0078\u0074\u005b\u005c\u0073\u005f\u002d\u005d\u003f\u0070\u0061\u0067\u0065\u005c\u0073\u002a\u005b\u203a\u003e\u2192\u00bb\u005d\u003f\u0024\u007c\u6b21\u306e\u30da\u30fc\u30b8\u007c\u005e\u6b21\u3078\u003f\u0024\u007c\u0412\u043f\u0435\u0440\u0435\u0434", "i");
  1168. const nextTextReg2 = new RegExp("\u005e\u0028\u005b\u4e0b\u540e\u5f8c\u6b21\u005d\u005b\u4e00\u30fc\u0031\u005d\u003f\u005b\u7ae0\u8bdd\u8a71\u8282\u7bc0\u5e45\u005d\u007c\u006e\u0065\u0078\u0074\u002e\u003f\u0063\u0068\u0061\u0070\u0074\u0065\u0072\u007c\u00bb\u007c\u003e\u003e\u0029\u0028\u005b\u003a\uff1a\u005c\u002d\u005f\u2014\u005c\u0073\u005c\u002e\u3002\u003e\u0023\u00b7\u005c\u005b\u3010\u3001\uff08\u005c\u0028\u002f\u002c\uff0c\uff1b\u003b\u2192\u005d\u007c\u0024\u0029", "i");
  1169. const lazyImgAttr = ["data-lazy-src", "data-lazy", "data-isrc", "data-url", "data-orig-file", "zoomfile", "file", "original", "load-src", "imgsrc", "real_src", "src2", "origin-src", "data-lazyload", "data-lazyload-src", "data-lazy-load-src", "data-ks-lazyload", "data-ks-lazyload-custom", "data-src", "data-defer-src", "data-actualsrc", "data-cover", "data-original", "data-thumb", "data-imageurl", "data-placeholder", "lazysrc"];
  1170. var rulesData = {uninited: true, firstRun: true, sideController: !isMobile}, ruleUrls, updateDate, clickedSth = false, loadNowNum = 5, autoScrollRate = 50;
  1171. var isPause = false, manualPause = false, isHideBar = false, isLoading = false, curPage = 1, forceState = 0, autoScroll = 0, autoScrollInterval, bottomGap = 1000, autoLoadNum = -1, nextIndex = 0, stopScroll = false, clickMode = false, openInNewTab = 0, charset = "UTF-8", charsetValid = true, urlWillChange = false;
  1172. var tryTimes = 0, showedLastPageTips = false, rate = 1, author = '';
  1173.  
  1174. function getBody(doc) {
  1175. return doc.body || doc.querySelector('body') || doc;
  1176. }
  1177.  
  1178. function getElementByXpath(xpath, doc, contextNode) {
  1179. if (doc && doc.ownerDocument) doc = doc.ownerDocument;
  1180. doc = (doc && doc.evaluate) ? doc : document;
  1181. contextNode = contextNode || doc;
  1182. try {
  1183. let xpathNode = (s, d, n) => {
  1184. let result = d.evaluate(s, n, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null);
  1185. return result.singleNodeValue && result.singleNodeValue.nodeType === 1 && result.singleNodeValue;
  1186. };
  1187. let selSplit = xpath.split(" =>> ");
  1188. if (selSplit.length === 2) {
  1189. let ele = xpathNode(selSplit[0], doc, contextNode);
  1190. if (ele && ele.shadowRoot) {
  1191. return xpathNode(selSplit[1], ele.shadowRoot, ele.shadowRoot);
  1192. }
  1193. } else {
  1194. return xpathNode(xpath, doc, contextNode);
  1195. }
  1196. } catch (err) {
  1197. debug(`Invalid xpath: ${xpath}`);
  1198. }
  1199. return null;
  1200. }
  1201.  
  1202. function getAllElementsByXpath(xpath, contextNode, doc) {
  1203. if (doc && doc.ownerDocument) doc = doc.ownerDocument;
  1204. doc = (doc && doc.evaluate) ? doc : document;
  1205. contextNode = contextNode || doc;
  1206. var result = [];
  1207. try {
  1208. var query = doc.evaluate(xpath, contextNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  1209. for (var i = 0; i < query.snapshotLength; i++) {
  1210. var node = query.snapshotItem(i);
  1211. if (node.nodeType === 1) {
  1212. result.push(node);
  1213. }
  1214. }
  1215. } catch (err) {
  1216. debug(`Invalid xpath: ${xpath}`);
  1217. }
  1218. return result;
  1219. }
  1220.  
  1221. function isXPath(xpath) {
  1222. if (!xpath) {
  1223. return false;
  1224. }
  1225. return /^\(*(descendant::|\.\/|\/|id\()/.test(xpath);
  1226. }
  1227.  
  1228. function getAllElements(sel, doc, contextNode) {
  1229. try {
  1230. if (sel.indexOf(" =>> ") !== -1) {
  1231. let result = getElement(sel, doc, contextNode);
  1232. return result && [result];
  1233. }
  1234. if (!isXPath(sel)) {
  1235. return doc.querySelectorAll(sel);
  1236. }
  1237. } catch(e) {
  1238. debug(e, 'Error selector');
  1239. }
  1240. return getAllElementsByXpath(sel, contextNode, doc);
  1241. }
  1242.  
  1243. function getElement(sel, doc, contextNode, bySort) {
  1244. try {
  1245. if (!isXPath(sel)) {
  1246. let checkShadow = s => {
  1247. let selSplit = s.split(" =>> ");
  1248. if (selSplit.length === 2) {
  1249. let ele = doc.querySelector(selSplit[0]);
  1250. return ele && ele.shadowRoot && ele.shadowRoot.querySelector(selSplit[1]);
  1251. } else return doc.querySelector(s);
  1252. };
  1253. if (!bySort) {
  1254. return checkShadow(sel);
  1255. } else {
  1256. let selArr = sel.split(",");
  1257. try {
  1258. for (let i = 0; i < selArr.length; i++) {
  1259. let ele = checkShadow(selArr[i].trim());
  1260. if (ele) {
  1261. return ele;
  1262. }
  1263. }
  1264. } catch(e) {
  1265. return checkShadow(sel);
  1266. }
  1267. return null;
  1268. }
  1269. }
  1270. } catch(e) {
  1271. debug(e, 'Error selector');
  1272. }
  1273. return getElementByXpath(sel, doc, contextNode);
  1274. }
  1275.  
  1276. function compareNodeName(node, names) {
  1277. if (!node || !node.nodeName || !node.nodeName.toLowerCase) {
  1278. return false;
  1279. }
  1280. let nodeName = node.nodeName.toLowerCase();
  1281. for (let i = 0; i < names.length; i++) {
  1282. if (names[i] === nodeName) {
  1283. return true;
  1284. }
  1285. }
  1286. return false;
  1287. }
  1288.  
  1289. function geneSelector(ele, addID, exact) {
  1290. let selector = ele.nodeName.toLowerCase();
  1291. //Google id class都是隨機。百度更過分,style script順序都是隨機的
  1292. if (selector !== "html" && selector !== "body") {
  1293. let hasId = false;
  1294. if (addID && ele.id && /^[a-z_][\w\-_]*$/i.test(ele.id)) {
  1295. if (ele.ownerDocument && ele.ownerDocument.querySelectorAll("#" + ele.id).length === 1) {
  1296. hasId = true;
  1297. selector = '#' + ele.id;
  1298. }
  1299. }
  1300. if (!hasId) {
  1301. let className = "";
  1302. if (ele.className) {
  1303. let classList = ele.classList;
  1304. for (let i = 0; i < classList.length; i++) {
  1305. let c = classList[i];
  1306. if (c !== 'scrolling' && /^[a-z_][\w\-_]*$/.test(c) && !/\d{4,}/.test(c)) {
  1307. className += '.' + c;
  1308. }
  1309. }
  1310. selector += className;
  1311. }
  1312. let parent = ele.parentElement;
  1313. if (parent) {
  1314. if (exact) {
  1315. let i, nth = 0, all = 0;
  1316. for (i = 0; i < parent.children.length; i++) {
  1317. if (parent.children[i].nodeName === ele.nodeName) {
  1318. all++;
  1319. if (parent.children[i] === ele) {
  1320. nth = all;
  1321. }
  1322. if (nth > 0 && all > 1) {
  1323. break;
  1324. }
  1325. }
  1326. }
  1327. selector += (all === 1 ? "" : `:nth-of-type(${nth})`);
  1328. } else if (!className && !hasId && parent.children.length > 1 && !compareNodeName(parent, ["html"])) {
  1329. let prevE = ele.previousElementSibling;
  1330. if (prevE && prevE.className) {
  1331. let classList = prevE.classList;
  1332. for (let i = 0; i < classList.length; i++) {
  1333. let c = classList[i];
  1334. if (c !== 'scrolling' && /^[a-z_][\w\-_]*$/.test(c) && !/\d{4,}/.test(c)) {
  1335. className += '.' + c;
  1336. }
  1337. }
  1338. if (className) {
  1339. selector = prevE.nodeName.toLowerCase() + className + "+" + selector;
  1340. }
  1341. }
  1342. if (!className) {
  1343. let i, nth = 0, all = 0;
  1344. for (i = 0; i < parent.children.length; i++) {
  1345. if (parent.children[i].nodeName === ele.nodeName) {
  1346. all++;
  1347. if (parent.children[i] === ele) {
  1348. nth = all;
  1349. }
  1350. if (nth > 0 && all > 1) {
  1351. break;
  1352. }
  1353. }
  1354. }
  1355. selector += (all === 1 ? "" : `:nth-of-type(${nth})`);
  1356. }
  1357. }
  1358. selector = geneSelector(parent, addID, exact) + ' > ' + selector;
  1359. }
  1360. }
  1361. }
  1362. return selector;
  1363. }
  1364.  
  1365. function createXPathFromElement(elm) {
  1366. let allNodes = document.getElementsByTagName('*'), segs;
  1367. for (segs = []; elm && elm.nodeType === 1; elm = elm.parentNode) {
  1368. if (compareNodeName(elm, ["body", "html"])) {
  1369. segs.unshift(elm.localName.toLowerCase());
  1370. continue;
  1371. }
  1372. if (elm.hasAttribute && elm.hasAttribute('id')) {
  1373. var uniqueIdCount = 0;
  1374. for (var n = 0; n < allNodes.length; n++) {
  1375. if (allNodes[n].hasAttribute('id') && allNodes[n].id === elm.id) {
  1376. uniqueIdCount++;
  1377. }
  1378. if (uniqueIdCount > 1) {
  1379. break;
  1380. }
  1381. }
  1382. if ( uniqueIdCount === 1) {
  1383. segs.unshift('id("' + elm.getAttribute('id') + '")');
  1384. return segs.join('/');
  1385. } else {
  1386. segs.unshift(elm.localName.toLowerCase() + '[@id="' + elm.getAttribute('id') + '"]');
  1387. }
  1388. } else if (elm.hasAttribute && elm.hasAttribute('class')) {
  1389. segs.unshift(elm.localName.toLowerCase() + '[@class="' + elm.getAttribute('class') + '"]');
  1390. } else {
  1391. let i, sib;
  1392. for (i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling) {
  1393. if (sib.localName === elm.localName) {
  1394. i++;
  1395. }
  1396. }
  1397. segs.unshift(elm.localName.toLowerCase() + '[' + i + ']');
  1398. }
  1399. }
  1400. return segs.length ? '/' + segs.join('/') : null;
  1401. }
  1402.  
  1403. const escapeHTMLPolicy = (_unsafeWindow.trustedTypes && _unsafeWindow.trustedTypes.createPolicy) ? _unsafeWindow.trustedTypes.createPolicy('pagetual_default', {
  1404. createHTML: (string, sink) => string
  1405. }) : null;
  1406.  
  1407. function createHTML(html) {
  1408. return escapeHTMLPolicy ? escapeHTMLPolicy.createHTML(html) : html;
  1409. }
  1410.  
  1411. const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
  1412.  
  1413. async function sleep(time) {
  1414. await new Promise((resolve) => {
  1415. setTimeout(() => {
  1416. resolve();
  1417. }, time);
  1418. });
  1419. }
  1420.  
  1421. class RuleParser {
  1422. constructor() {
  1423. this.hpRules = [];
  1424. this.smartRules = [];
  1425. this.customRules = [];
  1426. this.rules = [];
  1427. this.pageDoc = document;
  1428. this.nextLinkHref = null;
  1429. this.nextTitle = "";
  1430. this.oldUrl = "";
  1431. this.curUrl = location.href;
  1432. this.curSiteRule = {};
  1433. }
  1434.  
  1435. async initSavedRules(callback) {
  1436. var self = this;
  1437. let smartRules = await getData("smartRules");
  1438. if (smartRules) self.smartRules = smartRules;
  1439. let hpRules = await getData("hpRules");
  1440. if (hpRules) self.hpRules = hpRules;
  1441. let customRules = await getData("customRules");
  1442. if (customRules) self.customRules = customRules;
  1443. if (_unsafeWindow.pagetualRules && _unsafeWindow.pagetualRules.length) {
  1444. _unsafeWindow.pagetualRules.forEach(rule => {
  1445. rule.isScript = true;
  1446. });
  1447. self.customRules = _unsafeWindow.pagetualRules.concat(self.customRules);
  1448. }
  1449. let rules = await getData("rules");
  1450. if (rules) self.rules = rules;
  1451. callback();
  1452. }
  1453.  
  1454. saveCurSiteRule() {
  1455. /*if(!this.curSiteRule || !this.curSiteRule.url || this.curSiteRule.smart || this.curSiteRule.url.length<13)return;
  1456. this.hpRules=this.hpRules.filter(item=>{return item&&item.url!=this.curSiteRule.url});
  1457. this.hpRules.unshift(this.curSiteRule);
  1458. if(this.hpRules.length>30){
  1459. this.hpRules.pop();
  1460. }
  1461. storage.setItem("hpRules", this.hpRules);*/
  1462. }
  1463.  
  1464. requestJSON(url, callback) {
  1465. _GM_xmlhttpRequest({
  1466. url: url,
  1467. method: 'GET',
  1468. timeout: 1000000,
  1469. headers: {
  1470. 'accept': 'application/json,text/html',
  1471. 'Referer': url,
  1472. },
  1473. onload: function(res) {
  1474. let json = null;
  1475. try {
  1476. json = JSON.parse(res.response || res.responseText);
  1477. } catch(e) {
  1478. debug(e, 'Error json');
  1479. }
  1480. callback(json);
  1481. },
  1482. onerror: function(e) {
  1483. callback(null, e);
  1484. },
  1485. ontimeout: function(e) {
  1486. callback(null, e);
  1487. }
  1488. });
  1489. }
  1490.  
  1491. formatRule(item, from) {
  1492. if (item.data && item.data.url) {
  1493. let result = {
  1494. name: item.name,
  1495. from: from,
  1496. action: item.data.forceIframe === "true" ? 1 : undefined,
  1497. url: item.data.url,
  1498. pageElement: item.data.pageElement,
  1499. nextLink: item.data.nextLink,
  1500. insert: item.data.insertBefore||undefined,
  1501. updatedAt: item.updated_at
  1502. };
  1503. let _css = (item.data.Stylus || '') + (item.data.CSS || '');
  1504. if (_css) result.css = _css;
  1505. if (item.data.bookmarklet) result.pageAction = item.data.bookmarklet;
  1506. return result;
  1507. } else {
  1508. item.from = from;
  1509. return item;
  1510. }
  1511. return null;
  1512. }
  1513.  
  1514. addRuleByUrl(url, from, callback) {
  1515. if (url.indexOf("?") === -1) {
  1516. url = url + "?" + Date.now();
  1517. } else {
  1518. url = url + "&" + Date.now();
  1519. }
  1520. this.requestJSON(url, (json,err) => {
  1521. if (!json) {
  1522. debug(err, "Failed to update " + url + " rules!");
  1523. }
  1524. this.addRules(json, from);
  1525. callback(json, err);
  1526. });
  1527. }
  1528.  
  1529. addRules(rules, from) {
  1530. if (rules && rules.length > 0) {
  1531. let first = -1;
  1532. this.rules = this.rules.filter((item, i) => {
  1533. if (item.from === from) {
  1534. if (first === -1) first = i;
  1535. return false;
  1536. } else return true;
  1537. });
  1538. if (first === -1) first = 0;
  1539. rules.forEach(item => {
  1540. let rule = this.formatRule(item, from);
  1541. if (rule) {
  1542. this.rules.splice(first, 0, rule)
  1543. }
  1544. });
  1545. }
  1546. }
  1547.  
  1548. ruleMatchPre(r) {
  1549. if (r.include) {
  1550. let include;
  1551. if (Array && Array.isArray && Array.isArray(r.include)) {
  1552. include = r.include.every((sel, i) => {
  1553. let ele = getElement(sel, document);
  1554. return !!ele;
  1555. });
  1556. } else include = getElement(r.include, document);
  1557. if (!include) return false;
  1558. }
  1559. if (r.exclude) {
  1560. let exclude;
  1561. if (Array && Array.isArray && Array.isArray(r.exclude)) {
  1562. exclude = !r.exclude.every((sel, i) => {
  1563. let ele = getElement(sel, document);
  1564. return !ele;
  1565. });
  1566. } else exclude = getElement(r.exclude, document);
  1567. if (exclude) return false;
  1568. }
  1569. return true;
  1570. }
  1571.  
  1572. ruleMatchReady(r) {
  1573. let findIndex = 0;
  1574. if (r.nextLink && r.nextLink !== 0) {
  1575. let nextLinkSel = r.nextLink, nextLink;
  1576. if (Array && Array.isArray && Array.isArray(nextLinkSel)) {
  1577. nextLink = !nextLinkSel.every((sel, i) => {
  1578. let ele = getElement(sel, document);
  1579. if (ele) findIndex = i;
  1580. return !ele;
  1581. });
  1582. } else nextLink = getElement(nextLinkSel, document);
  1583. if (!nextLink) return false;
  1584. }
  1585. if (r.pageElement) {
  1586. let pageElementSel = r.pageElement, pageElement;
  1587. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  1588. pageElementSel = pageElementSel[findIndex];
  1589. }
  1590. pageElement = getElement(pageElementSel, document);
  1591. if (!pageElement) return false;
  1592. }
  1593. if (r.insert) {
  1594. let insertSel = r.insert, insert;
  1595. if (Array && Array.isArray && Array.isArray(insertSel)) {
  1596. insertSel = insertSel[findIndex];
  1597. }
  1598. insert = getElement(insertSel, document);
  1599. if (!insert) return false;
  1600. }
  1601. //if (findIndex !== 0) nextIndex = findIndex;
  1602. return true;
  1603. }
  1604.  
  1605. ruleMatch(r) {
  1606. return this.ruleMatchPre(r) && this.ruleMatchReady(r);
  1607. }
  1608.  
  1609. scrollToShow(sel, doc) {
  1610. let exclude = getElement(sel, doc);
  1611. if (exclude) {
  1612. var actualTop = exclude.offsetTop;
  1613. var current = exclude.offsetParent;
  1614. while (current !== null) {
  1615. actualTop += current.offsetTop;
  1616. current = current.offsetParent;
  1617. }
  1618. getBody(doc).scrollTop = 0;
  1619. doc.documentElement.scrollTop = 0;
  1620. let maxHeight = Math.max(getBody(doc).scrollHeight, doc.documentElement.scrollHeight);
  1621. getBody(doc).scrollTop = actualTop - 10;
  1622. doc.documentElement.scrollTop = actualTop - 10;
  1623. setTimeout(() => {
  1624. while (actualTop < maxHeight) {
  1625. actualTop += 200;
  1626. getBody(doc).scrollTop = actualTop;
  1627. doc.documentElement.scrollTop = actualTop;
  1628. }
  1629. }, 0);
  1630. return false;
  1631. }
  1632. return true;
  1633. }
  1634.  
  1635. waitElement(doc, selArr) {
  1636. if (!selArr) selArr = this.curSiteRule.waitElement;
  1637. if (!Array.isArray(selArr)) {
  1638. selArr = [selArr];
  1639. }
  1640. let includeSel = selArr[0].trim(), excludeSel;
  1641. if (selArr.length === 2) {
  1642. excludeSel = selArr[1].trim().replace(/^!/, '');
  1643. } else if (includeSel.indexOf('!') === 0) {
  1644. excludeSel = includeSel.replace(/^!/, '');
  1645. includeSel = '';
  1646. }
  1647. if (includeSel) {
  1648. let include = getElement(includeSel, doc);
  1649. if (!include) {
  1650. if (doc !== document) {
  1651. getBody(doc).scrollTop = 9999999;
  1652. doc.documentElement.scrollTop = 9999999;
  1653. }
  1654. return false;
  1655. }
  1656. }
  1657. if (doc === document) return true;
  1658. if (excludeSel) {
  1659. if (!this.scrollToShow(excludeSel, doc)) {
  1660. if (!loadingDiv.offsetParent && this.insert.parentNode) {
  1661. this.insertElement(loadingDiv);
  1662. }
  1663. return false;
  1664. }
  1665. }
  1666. return true;
  1667. }
  1668.  
  1669. runPageBar(pageBar) {
  1670. if (this.curSiteRule.pageBar && this.curSiteRule.pageBar !== 0) {
  1671. try {
  1672. ((typeof this.curSiteRule.pageBar === 'function') ? this.curSiteRule.pageBar : Function("pageBar",'"use strict";' + this.curSiteRule.pageBar))(pageBar);
  1673. } catch(e) {
  1674. debug(e);
  1675. }
  1676. }
  1677. }
  1678.  
  1679. runWait(cb) {
  1680. let checkEval = null, waitTime = 0;
  1681. if (this.curSiteRule.waitElement) {
  1682. checkEval = async doc => {
  1683. return await this.waitElement(doc);
  1684. };
  1685. } else if(this.curSiteRule.wait) {
  1686. if (isNaN(this.curSiteRule.wait)) {
  1687. try {
  1688. checkEval = (typeof this.curSiteRule.wait === 'function') ? this.curSiteRule.wait : new AsyncFunction("doc", '"use strict";' + this.curSiteRule.wait);
  1689. } catch(e) {
  1690. debug(e);
  1691. }
  1692. } else {
  1693. waitTime = this.curSiteRule.wait;
  1694. }
  1695. }
  1696. cb(checkEval, waitTime);
  1697. }
  1698.  
  1699. findNoNext() {
  1700. if (!this.curSiteRule || !this.curSiteRule.smart || this.curSiteRule.nextLink === 0 || this.possibleRule) return;
  1701. let self = this;
  1702. self.curSiteRule.nextLink = 0;
  1703. self.smartRules = self.smartRules.filter(item => {return item && item.url !== self.curSiteRule.url;});
  1704. self.smartRules.unshift(self.curSiteRule);
  1705. storage.setItem("smartRules", self.smartRules);
  1706. }
  1707.  
  1708. async getRule(callback) {
  1709. var href = location.href.slice(0, 500);
  1710. if(noRuleTest) {
  1711. this.curSiteRule = {};
  1712. this.curSiteRule.url = href;
  1713. this.curSiteRule.smart = true;
  1714. callback();
  1715. return;
  1716. }
  1717. if (_unsafeWindow.pagetualRule) {
  1718. this.curSiteRule = _unsafeWindow.pagetualRule;
  1719. if (!this.curSiteRule.url) this.curSiteRule.url = ".";
  1720. this.curSiteRule.isScript = true;
  1721. }
  1722. if (this.curSiteRule && this.curSiteRule.url && !this.curSiteRule.smart) {
  1723. let urlReg = new RegExp(this.curSiteRule.url, "i");
  1724. if (urlReg.test(href) && this.ruleMatch(this.curSiteRule)) {
  1725. return callback();
  1726. }
  1727. }
  1728. if (this.possibleRule) {
  1729. let urlReg = new RegExp(this.possibleRule.url, "i");
  1730. if (urlReg.test(href) && this.ruleMatch(this.possibleRule)) {
  1731. this.curSiteRule = this.possibleRule;
  1732. debug(this.curSiteRule, 'Match');
  1733. return callback();
  1734. }
  1735. }
  1736. this.curSiteRule = {};
  1737. var self = this;
  1738.  
  1739. function setRule(r) {
  1740. if (self.preSiteRule) {
  1741. href = location.href.slice(0, 500);
  1742. let urlReg = new RegExp(self.preSiteRule.url, "i");
  1743. if (urlReg.test(href) && self.ruleMatch(self.preSiteRule)) {
  1744. self.curSiteRule = self.preSiteRule;
  1745. return callback();
  1746. }
  1747. }
  1748. if (r.from === 2) {
  1749. delete r.autoLoadNum;
  1750. delete r.history;
  1751. delete r.sideController;
  1752. if (r.pageBar === 0) delete r.pageBar;
  1753. }
  1754. if (!r.smart) {
  1755. self.insert = null;
  1756. self.curSiteRule = r;
  1757. self.preSiteRule = r;
  1758. if (r.enable !== 0) debug(r, 'Match');
  1759. } else if (!self.curSiteRule || !self.curSiteRule.smart) self.curSiteRule = r;
  1760. callback();
  1761. }
  1762.  
  1763. function checkRule(r) {
  1764. if (r.from === 1 && r.url.length <= 13) return false;
  1765. let urlReg = new RegExp(r.url, "i");
  1766. if (urlReg.test(href)) {
  1767. if (!self.ruleMatchPre(r)) return false;
  1768. if (r.url.length > 15 && r.from !== 1) {
  1769. self.possibleRule = r;
  1770. }
  1771. if (r.waitElement) {
  1772. let waitTime = 500;
  1773. let checkReady = () => {
  1774. setTimeout(() => {
  1775. if (!self.waitElement(document, r.waitElement) || !self.ruleMatchReady(r)) {
  1776. checkReady();
  1777. } else {
  1778. setRule(r);
  1779. }
  1780. }, parseInt(waitTime));
  1781. };
  1782. checkReady();
  1783. debug(r, 'Wait for');
  1784. return true;
  1785. } else if (r.wait) {
  1786. let waitTime = 500, checkEval, maxCheckTimes = 50;
  1787. if (isNaN(r.wait)) {
  1788. try {
  1789. checkEval = (typeof r.wait === 'function') ? r.wait : AsyncFunction("doc",'"use strict";' + r.wait);
  1790. } catch(e) {
  1791. debug(e, 'Error when checkeval');
  1792. }
  1793. } else {
  1794. waitTime = r.wait;
  1795. }
  1796. let checkReady = () => {
  1797. if (maxCheckTimes-- <= 0) {
  1798. debug("Wait for rule ready but failed");
  1799. setRule(r);
  1800. return;
  1801. }
  1802. setTimeout(async() => {
  1803. if (!self.ruleMatchReady(r) || (checkEval && !await checkEval(document))) {
  1804. checkReady();
  1805. } else {
  1806. setRule(r);
  1807. }
  1808. }, parseInt(waitTime));
  1809. };
  1810. checkReady();
  1811. debug(r, 'Wait for');
  1812. return true;
  1813. }
  1814. if (r.pinUrl) {
  1815. setRule(r);
  1816. return true;
  1817. }
  1818. if (!self.ruleMatchReady(r)) {
  1819. return false;
  1820. }
  1821. setRule(r);
  1822. return true;
  1823. }
  1824. return false;
  1825. }
  1826.  
  1827. function checkHpRules() {
  1828. for (let i in self.hpRules) {
  1829. let rule = self.hpRules[i];
  1830. if (!rule || !rule.url || rule.smart) continue;
  1831. if (checkRule(rule)) return true;
  1832. }
  1833. return false;
  1834. }
  1835.  
  1836. function checkCustomRules() {
  1837. for (let i in self.customRules) {
  1838. let rule = self.customRules[i];
  1839. if (!rule || !rule.url) continue;
  1840. if (checkRule(rule)) return true;
  1841. }
  1842. return false;
  1843. }
  1844.  
  1845. if (rulesData.customFirst) {
  1846. if (checkCustomRules()) return;
  1847. await sleep(1);
  1848. if (checkHpRules()) return;
  1849. } else {
  1850. if (checkHpRules()) return;
  1851. await sleep(1);
  1852. if (checkCustomRules()) return;
  1853. }
  1854. await sleep(1);
  1855.  
  1856. for (let i in this.smartRules) {
  1857. let rule = this.smartRules[i];
  1858. if (!rule || !rule.url || !rule.smart) continue;
  1859. if (href == rule.url) {
  1860. setRule(rule);
  1861. return;
  1862. }
  1863. }
  1864. let r = 0;
  1865. async function searchByTime() {
  1866. while (document.hidden) {
  1867. await sleep(1000);
  1868. }
  1869. setTimeout(() => {
  1870. let end = r + 20;
  1871. end = end > self.rules.length ? self.rules.length : end;
  1872. for (; r < end; r++) {
  1873. let rule = self.rules[r];
  1874. if (checkRule(rule)) return;
  1875. }
  1876. if (end >= self.rules.length) {
  1877. setRule({url: href, smart: true});
  1878. return;
  1879. } else {
  1880. searchByTime();
  1881. }
  1882. }, 1);
  1883. }
  1884. searchByTime();
  1885. }
  1886.  
  1887. addToHpRules(instead) {
  1888. try {
  1889. if (this.curSiteRule.isScript) return;
  1890. if (!this.hpRules) this.hpRules = [];
  1891. let url = this.curSiteRule && this.curSiteRule.url, self = this;
  1892. let href = location.href.slice(0, 500);
  1893. let matchedRules = this.hpRules.filter(rule => rule != self.curSiteRule && new RegExp(rule.url, "i").test(href) && self.ruleMatch(rule));
  1894. if (url) matchedRules.unshift(this.curSiteRule);
  1895. matchedRules.sort((a, b) => {
  1896. if ((a.include || a.exclude) && (!b.include && !b.exclude)) {
  1897. return -1;
  1898. } else if ((b.include || b.exclude) && (!a.include && !a.exclude)) {
  1899. return 1;
  1900. } else {
  1901. if ((a.nextLink || a.pageElement) && (!b.nextLink && !b.pageElement)) {
  1902. return -1;
  1903. } else if ((b.nextLink || b.pageElement) && (!a.nextLink && !a.pageElement)) {
  1904. return 1;
  1905. } else {
  1906. if (a.url.length > b.url.length) {
  1907. return -1;
  1908. } else if (a.url.length < b.url.length) {
  1909. return 1;
  1910. } else {
  1911. return 0;
  1912. }
  1913. }
  1914. }
  1915. });
  1916. this.hpRules = this.hpRules.filter(item => {
  1917. return item && !matchedRules.find(rule => item.url == rule.url && JSON.stringify(item) == JSON.stringify(rule));
  1918. });
  1919. if (instead) {
  1920. if (url) {
  1921. this.hpRules.unshift(this.curSiteRule);
  1922. matchedRules = [];
  1923. }
  1924. } else {
  1925. this.hpRules = matchedRules.concat(this.hpRules);
  1926. }
  1927. if (matchedRules && matchedRules.length) this.curSiteRule = matchedRules[0];
  1928. if (this.hpRules.length > 30) {
  1929. this.hpRules.pop();
  1930. }
  1931. if (!rulesData.sort) rulesData.sort = [1];
  1932. this.hpRules.sort((a, b) => {
  1933. let aSort = -1, bSort = -1;
  1934. for (let s = 0; s < rulesData.sort.length; s++) {
  1935. if (a.from == rulesData.sort[s]) aSort = s;
  1936. if (b.from == rulesData.sort[s]) bSort = s;
  1937. if (aSort > -1 && bSort > -1) break;
  1938. }
  1939. return aSort - bSort;
  1940. });
  1941. storage.setItem("hpRules", this.hpRules);
  1942. } catch (e) {
  1943. debug(e);
  1944. }
  1945. }
  1946.  
  1947. replaceElement(doc) {
  1948. if (!doc || doc === document) return;
  1949. let replaceElementSel = this.curSiteRule.replaceElement;
  1950. if (replaceElementSel) {
  1951. if (!Array.isArray(replaceElementSel)) {
  1952. replaceElementSel = [replaceElementSel];
  1953. }
  1954. replaceElementSel.forEach(sel => {
  1955. let pageEles = getAllElements(sel, document);
  1956. let replaceEles = getAllElements(sel, doc);
  1957. for (let i = 0; i < pageEles.length; i++) {
  1958. let replaceEle = replaceEles[i];
  1959. let pageEle = pageEles[i];
  1960. if (replaceEle) {
  1961. pageEle.parentNode.replaceChild(replaceEle.cloneNode(true), pageEle);
  1962. } else break;
  1963. }
  1964. });
  1965. }
  1966. }
  1967.  
  1968. refreshByClick() {
  1969. let refreshByClickSel = this.curSiteRule.refreshByClick;
  1970. if (refreshByClickSel) {
  1971. let self = this;
  1972. if (!this.refreshByClickHandler) {
  1973. this.refreshByClickHandler = e => {
  1974. if (!self.refreshing) {
  1975. self.refreshing = true;
  1976. setTimeout(() => {
  1977. self.refreshing = false;
  1978. let checkEles = getAllElements(refreshByClickSel, document);
  1979. for (let i = 0; i < checkEles.length; i++) {
  1980. let curEle = checkEles[i];
  1981. if (curEle === e.target || curEle.contains(e.target)) {
  1982. ruleParser.urlChanged();
  1983. isPause = true;
  1984. if (!ruleParser.nextLinkHref) isLoading = false;
  1985. break;
  1986. }
  1987. }
  1988. }, 300);
  1989. }
  1990. }
  1991. }
  1992. document.removeEventListener("click", this.refreshByClickHandler);
  1993. document.addEventListener("click", this.refreshByClickHandler);
  1994. }
  1995. }
  1996.  
  1997. getValidSize(ele, win) {
  1998. if (!win) return {h: 0, w: 0};
  1999. let eleStyle = win.getComputedStyle(ele);
  2000. if (!ele.offsetParent && (eleStyle.position !== "fixed" || eleStyle.opacity === 0)) {
  2001. return {h: 0, w: 0};
  2002. }
  2003. if (ele.children && ele.children.length === 1 && (ele.offsetWidth === 0 || ele.offsetHeight === 0)) {
  2004. ele = ele.children[0];
  2005. }
  2006. let h = ele.scrollHeight, w;
  2007. if (eleStyle.overflow === "hidden") {
  2008. h = ele.offsetHeight;
  2009. w = ele.offsetWidth;
  2010. } else w = parseInt(ele.offsetWidth || ele.scrollWidth);
  2011. if (h === 0 && ele.parentNode && ele.parentNode.children.length === 1) {
  2012. h = ele.parentNode.scrollHeight;
  2013. }
  2014. while (h === 0 && ele.children && ele.children.length === 1) {
  2015. ele = ele.children[0];
  2016. h = ele.scrollHeight;
  2017. }
  2018. if (h === 0 && ele.children && ele.children.length) {
  2019. let maxChildSize = {h: 0}, self = this;
  2020. [].forEach.call(ele.children, el => {
  2021. let childSize = self.getValidSize(el, win);
  2022. if (childSize.h > maxChildSize.h) maxChildSize = childSize;
  2023. });
  2024. if (maxChildSize.h !== 0) return maxChildSize;
  2025. }
  2026. const maxNum = 2147483647;
  2027. let moreChild = ele.children[0], minOffsetTop = maxNum;
  2028. while (moreChild) {
  2029. if ((moreChild.offsetParent === ele || moreChild.offsetParent === ele.offsetParent)) {
  2030. let curOffsetTop = moreChild.offsetParent === ele.offsetParent ? moreChild.offsetTop - ele.offsetTop : moreChild.offsetTop;
  2031. if (curOffsetTop < minOffsetTop) {
  2032. minOffsetTop = curOffsetTop;
  2033. }
  2034. }
  2035. moreChild = moreChild.nextElementSibling;
  2036. }
  2037. if (h && minOffsetTop !== maxNum && minOffsetTop > 0) {
  2038. h -= minOffsetTop;
  2039. }
  2040. return {h: h, w: w};
  2041. }
  2042.  
  2043. checkTargetChildren(ele, curWin, articleNum, curHeight) {
  2044. let pf = false;
  2045. if (ele.parentNode) {
  2046. let paStyle = curWin.getComputedStyle(ele.parentNode);
  2047. let paDisplay = paStyle.display;
  2048. let paOverflow = paStyle.overflow;
  2049. pf = (paDisplay.indexOf('flex') !== -1 && paStyle.flexDirection.indexOf("row") === 0 && paStyle.flexWrap !== "wrap") || compareNodeName(ele.parentNode, ["ul"]) || paDisplay.indexOf('grid') !== -1 || paOverflow === "hidden";
  2050. }
  2051. let curStyle = curWin.getComputedStyle(ele);
  2052. if (ele.children.length > 1) {
  2053. if (articleNum > 1) {
  2054. return ">article";
  2055. } else {
  2056. let hasText = false;
  2057. for (let i in ele.childNodes) {
  2058. let child = ele.childNodes[i];
  2059. if (child.nodeType === 3 && child.nodeValue.trim() !== '') {
  2060. hasText = true;
  2061. break;
  2062. }
  2063. }
  2064. let gridArea = curStyle.gridArea;
  2065. if (gridArea && gridArea !== "auto" && gridArea !== "auto / auto / auto / auto") {
  2066. return ">*";
  2067. } else {
  2068. let middleChild = ele.children[parseInt(ele.children.length / 2)];
  2069. if ((curStyle.display === 'flex' && curStyle.flexDirection.indexOf("row") === 0 && curStyle.flexWrap !== "wrap") || (curStyle.float === "none" && curStyle.display !== "table-cell" && (rulesData.opacity !== 0 || hasText) && !pf)) {
  2070. return "";
  2071. } else if ((middleChild.style && middleChild.style.position === "absolute" && middleChild.style.left && middleChild.style.top) || compareNodeName(ele, ["ul"]) || curHeight === 0) {
  2072. return "";
  2073. } else {
  2074. return ">*";
  2075. }
  2076. }
  2077. }
  2078. } else if (pf || curStyle.position === "absolute") {
  2079. return ">*";
  2080. }
  2081. return "";
  2082. }
  2083.  
  2084. getPageElement(doc, curWin, dontFind) {
  2085. if (doc === document && this.docElementValid()) {
  2086. return this.docPageElement;
  2087. }
  2088. let pageElement = null;
  2089. let self = this;
  2090. let body = getBody(doc);
  2091. if (this.curSiteRule.pageElement) {
  2092. let pageElementSel = this.curSiteRule.pageElement;
  2093. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  2094. pageElementSel = pageElementSel[nextIndex < pageElementSel.length ? nextIndex : 0];
  2095. }
  2096. pageElement = getAllElements(pageElementSel, doc);
  2097. if (this.curSiteRule.smart && (!pageElement || pageElement.length === 0)) {
  2098. const childSelMatch = />\s*\*$/;
  2099. const targetChild = childSelMatch.test(pageElementSel);
  2100. if (targetChild) pageElementSel = pageElementSel.replace(childSelMatch, "");
  2101. let pageElementSelSplit = pageElementSel.split(">");
  2102. while(pageElementSelSplit && pageElementSelSplit.length > 5) {
  2103. pageElementSelSplit.shift();
  2104. let tempSel = pageElementSelSplit.join(">");
  2105. pageElement = getAllElements(tempSel, doc);
  2106. if (pageElement && pageElement.length === 1) {
  2107. if (targetChild) {
  2108. pageElement = pageElement.children;
  2109. }
  2110. this.curSiteRule.pageElement = tempSel + (targetChild ? ">*" : "");
  2111. break;
  2112. }
  2113. }
  2114. if (!pageElement || pageElement.length === 0) {
  2115. pageElementSel = pageElementSel.replace(/:nth-of-type\(\d+\)/g, "");
  2116. pageElement = getAllElements(pageElementSel, doc);
  2117. if (pageElement && pageElement.length === 1) {
  2118. if (targetChild) {
  2119. pageElement = pageElement.children;
  2120. }
  2121. this.curSiteRule.pageElement = pageElementSel + (targetChild ? ">*" : "");
  2122. }
  2123. }
  2124. }
  2125. if (this.curSiteRule.smart && pageElement && pageElement.length && curWin && curWin !== _unsafeWindow) {
  2126. if (pageElement.length === 1 && !pageElement[0].src && pageElement[0].innerHTML.trim() === "") {
  2127. pageElement = null;
  2128. } else {
  2129. let parent = pageElement[0].parentNode;
  2130. let loading = parent.querySelector('[class*=loading]');
  2131. if (loading && loading.offsetParent && loading.offsetHeight > parent.offsetHeight>>2) {
  2132. pageElement = null;
  2133. }
  2134. }
  2135. }
  2136. }
  2137. if (pageElement && pageElement.length === 1 && pageElement[0].style.display === 'none') {
  2138. pageElement = [body];
  2139. }
  2140. if (this.curSiteRule.smart && pageElement && pageElement.length > 0 && compareNodeName(pageElement[0], ["tr"])) {
  2141. let mainTr = this.insert.parentNode.querySelectorAll('tr'), mainTdNum = 0, newTdNum = 0;
  2142. mainTr = mainTr[mainTr.length - 1];
  2143. [].forEach.call(mainTr.children, el => {
  2144. if (compareNodeName(el, ["td", "th"])) {
  2145. mainTdNum += el.colSpan || 1;
  2146. }
  2147. });
  2148. [].forEach.call(pageElement[0].children, el => {
  2149. if (compareNodeName(el, ["td", "th"])) {
  2150. newTdNum += el.colSpan || 1;
  2151. }
  2152. });
  2153. if (mainTdNum !== newTdNum) {
  2154. this.curSiteRule.pageElement = this.curSiteRule.pageElement.replace(/> *table.*/, ">table");
  2155. this.getInsert(true);
  2156. return this.getPageElement(doc, curWin, dontFind);
  2157. }
  2158. }
  2159. if ((this.curSiteRule.smart || !this.curSiteRule.pageElement) && (!pageElement || pageElement.length == 0) && curWin && !dontFind) {
  2160. if (!body) return null;
  2161. let bodyHeight = parseInt(body.offsetHeight || body.scrollHeight);
  2162. let curHeight = bodyHeight, curWidth = 0;
  2163. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  2164. let windowWidth = window.innerWidth || document.documentElement.clientWidth;
  2165. let needCheckNext = (doc == document && this.initNext), nextLeftPos = 0;
  2166. if (needCheckNext && this.initNext.getBoundingClientRect) {
  2167. nextLeftPos = this.initNext.getBoundingClientRect().left;
  2168. }
  2169. function checkElement(ele) {
  2170. if (compareNodeName(ele, ["pre", "code"])) {
  2171. self.curSiteRule.pageElement = geneSelector(ele.parentNode);
  2172. debug(self.curSiteRule.pageElement, 'Page element');
  2173. return [ele.parentNode];
  2174. }
  2175. if (ele.children && ele.children.length === 1) {
  2176. let hasText = false;
  2177. for (let i in ele.childNodes) {
  2178. let child = ele.childNodes[i];
  2179. if (child.nodeType === 3 && child.nodeValue.trim() !== '') {
  2180. hasText = true;
  2181. break;
  2182. }
  2183. }
  2184. if (!hasText) {
  2185. ele = ele.children[0];
  2186. let validSize = self.getValidSize(ele, curWin);
  2187. curHeight = validSize.h;
  2188. curWidth = validSize.w;
  2189. }
  2190. }
  2191. if (compareNodeName(ele, ["picture"]) || !ele.innerText || ele.innerText.trim() === '') {
  2192. self.curSiteRule.pageElement = geneSelector(ele.parentNode) + ">" + ele.nodeName.toLowerCase();
  2193. debug(self.curSiteRule.pageElement, 'Page element');
  2194. let eles = [];
  2195. for (let i = 0; i < ele.parentNode.children.length; i++) {
  2196. let curNode = ele.parentNode.children[i];
  2197. if (curNode.nodeName === ele.nodeName && curNode.id === ele.id && curNode.className === ele.className) {
  2198. eles.push(curNode);
  2199. }
  2200. }
  2201. return eles;
  2202. }
  2203. if (compareNodeName(ele, ["form"]) && ele.parentNode !== getBody(document)) {
  2204. self.curSiteRule.pageElement = geneSelector(ele) + ">*";
  2205. debug(self.curSiteRule.pageElement, 'Page element');
  2206. return ele.children;
  2207. }
  2208. if (ele.children.length === 0 && !self.curSiteRule.pageElement) {
  2209. if (compareNodeName(ele.parentNode, ["p"])) ele = ele.parentNode;
  2210. self.curSiteRule.pageElement = geneSelector(ele.parentNode) + ">" + ele.nodeName.toLowerCase();
  2211. debug(self.curSiteRule.pageElement, 'Page element');
  2212. return getAllElements(self.curSiteRule.pageElement, doc);
  2213. }
  2214. let i, minHeight = curHeight * 0.52, curMaxEle = null, curMaxArea = 0, minWidth = Math.min(curWidth * 0.38, 500);
  2215. let isHori, preOffsetTop = -1;
  2216. let articleNum = 0;
  2217. for (i = 0; i < ele.children.length; i++) {
  2218. let curNode = ele.children[i];
  2219. if (ele !== body && /^H\d$/i.test(curNode.nodeName) && curNode.offsetParent) {
  2220. curMaxEle = null;
  2221. break;
  2222. }
  2223. if (compareNodeName(curNode, ["canvas", "nav"])) continue;
  2224. let curStyle = curWin.getComputedStyle(curNode);
  2225. if (!curNode.offsetParent && (curStyle.position !== "fixed" || curStyle.opacity === 0)) {
  2226. continue;
  2227. }
  2228. if (!compareNodeName(curNode, ["img"]) && curNode.querySelector('img') === null && /^\s*$/.test(curNode.innerText)) continue;
  2229. if (needCheckNext && !curNode.contains(self.initNext) && getElementTop(curNode) > windowHeight) {
  2230. continue;
  2231. }
  2232. if (compareNodeName(curNode, ["article"])) articleNum++;
  2233. let validSize = self.getValidSize(curNode, curWin);
  2234. let h = validSize.h;
  2235. let w = validSize.w;
  2236. if (isNaN(h) || isNaN(w) || !h || !w) continue;
  2237. isHori = Math.abs(preOffsetTop - curNode.offsetTop) <= 20 ? true : (preOffsetTop === -1 && curNode.nextElementSibling && curNode.nextElementSibling.offsetTop === curNode.offsetTop);
  2238. if (isHori && h <= 50) continue;
  2239. /*if (isHori && nextLeftPos && curMaxEle && curWidth > 500 && curHeight > 500) {
  2240. let curRect = curNode.getBoundingClientRect();
  2241. if (curRect.left > windowWidth>>2 && curRect.left <= nextLeftPos && curRect.right > nextLeftPos) {
  2242. continue;
  2243. }
  2244. }*/
  2245. let a = h * w, moreChild = curNode.children[0];
  2246. while (moreChild) {
  2247. let validSize = self.getValidSize(moreChild, curWin);
  2248. let ch = validSize.h;
  2249. let cw = validSize.w;
  2250. if (h < ch) {
  2251. h = ch;
  2252. }
  2253. if (moreChild.innerText !== "" && ch && cw) {
  2254. a += ch * cw;
  2255. }
  2256. moreChild = moreChild.nextElementSibling;
  2257. }
  2258. let isMax = false;
  2259. if (isHori) {
  2260. if (curMaxEle) {
  2261. if (w > curWidth && (windowWidth>>1) > curWidth) {
  2262. isMax = true;
  2263. } else if (w + 300 > curWidth && a > curMaxArea) {
  2264. isMax = true;
  2265. }
  2266. }
  2267. } else {
  2268. if (curMaxEle && curMaxEle.offsetParent === curNode.offsetParent && curMaxEle.offsetTop === curNode.offsetTop) {
  2269. if (curMaxArea * 2 > a) continue;
  2270. }
  2271. isMax = curMaxArea < a;
  2272. }
  2273. if (curMaxEle === null || isMax) {
  2274. if (isHori) {
  2275. if (w < minWidth) {
  2276. continue;
  2277. }
  2278. }
  2279. if (h < minHeight) {
  2280. if (!needCheckNext || h < (windowHeight>>1)) {
  2281. continue;
  2282. }
  2283. if (!ele.contains(self.initNext)) {
  2284. continue;
  2285. } else if (!curNode.contains(self.initNext) && h < curHeight >> 1) {
  2286. continue;
  2287. }
  2288. }
  2289. curHeight = h;
  2290. curMaxArea = a;
  2291. curWidth = w;
  2292. curMaxEle = curNode;
  2293. preOffsetTop = curNode.offsetTop;
  2294. }
  2295. }
  2296. let curHeightPercent = curHeight / bodyHeight;
  2297. if (curMaxEle && curHeightPercent <= 0.18) {
  2298. let article;
  2299. for (let i = 0; i < mainSel.length; i++) {
  2300. article = doc.querySelectorAll(mainSel[i]);
  2301. if (article && article.length === 1) break;
  2302. }
  2303. if (article && article.length === 1) {
  2304. article = article[0];
  2305. let childrenEnd = self.checkTargetChildren(article, curWin, articleNum, curHeight);
  2306. self.curSiteRule.pageElement = article.nodeName.toLowerCase() + (article.id ? "#" + article.id : "") + (article.className ? "." + article.className.replace(/ /g, ".") : "") + childrenEnd;
  2307. debug(self.curSiteRule.pageElement, 'Page element');
  2308. return childrenEnd ? article.children : [article];
  2309. }
  2310. curMaxEle = null;
  2311. }
  2312. if (curMaxEle && (!compareNodeName(curMaxEle, ["ul"]) || curHeightPercent > 0.8)) {
  2313. let sameClassNum = 0, hasDifferent = false;
  2314. if (curMaxEle.className) {
  2315. for(i = 0; i < ele.children.length; i++) {
  2316. let curNode = ele.children[i];
  2317. if (curMaxEle !== curNode && curNode.style.display !== 'none' && curMaxEle.className === curNode.className && curMaxEle.nodeName === curNode.nodeName){
  2318. sameClassNum++;
  2319. } else if (curMaxEle.className !== curNode.className) {
  2320. hasDifferent = true;
  2321. }
  2322. }
  2323. }
  2324. if (sameClassNum < 2 || (sameClassNum < 5 && hasDifferent)) {
  2325. return checkElement(curMaxEle);
  2326. }
  2327. }
  2328. if (ele.nodeName === "APP-ROOT") {
  2329. isPause = true;
  2330. debug(ele, "Angular root");
  2331. return null;
  2332. }
  2333. while (compareNodeName(ele, ["p", "br", "td"])) {
  2334. ele = ele.parentNode;
  2335. }
  2336. if (compareNodeName(ele, ["tbody"])) {
  2337. self.curSiteRule.pageElement = geneSelector(ele) + ">*";
  2338. if (ele.children.length > 0 && ele.children[0].querySelector("th")) {
  2339. self.curSiteRule.pageElement += ":not(:first-child)";
  2340. }
  2341. debug(self.curSiteRule.pageElement, 'Page element');
  2342. return ele.children;
  2343. }
  2344. let imgs = ele.querySelectorAll('img');
  2345. if (imgs.length === 1) {
  2346. let img = imgs[0];
  2347. if (img.offsetWidth > ele.offsetWidth / 3 * 2 && img.offsetHeight > ele.offsetHeight / 2) {
  2348. ele = img;
  2349. }
  2350. }
  2351. let childrenEnd = self.checkTargetChildren(ele, curWin, articleNum, curHeight);
  2352. if (childrenEnd) {
  2353. self.curSiteRule.pageElement = geneSelector(ele) + childrenEnd;
  2354. ele = ele.children;
  2355. } else {
  2356. if (ele.scrollHeight === 0 && ele.parentNode.children.length === 1) {
  2357. ele = ele.parentNode;
  2358. }
  2359. self.curSiteRule.pageElement = geneSelector(ele);
  2360. ele = [ele];
  2361. }
  2362. debug(self.curSiteRule.pageElement, 'Page element');
  2363. return ele;
  2364. }
  2365. pageElement = checkElement(body);
  2366. if (doc === document && pageElement && pageElement.length > 0 && self.initNext) {
  2367. let posEle = pageElement[pageElement.length - 1];
  2368. while (posEle && !posEle.offsetParent) {
  2369. posEle = posEle.previousElementSibling || posEle.parentNode;
  2370. }
  2371. if (posEle && posEle.scrollHeight === 0 && posEle.lastElementChild) posEle = posEle.lastElementChild;
  2372. let lastBottom = forceState !== 2 && forceState !== 3 && posEle && getElementBottom(posEle);
  2373. if (lastBottom && getElementTop(self.initNext) - lastBottom > 1000) {
  2374. debug("Stop as too long between next & page element, try to enable Force-Join mode.");
  2375. isPause = true;
  2376. pageElement = [];
  2377. sideController.remove();
  2378. } else {
  2379. if (pageElement.length === 1 && compareNodeName(pageElement[0], ["img"])) {
  2380. self.curSiteRule.pageBar = 0;
  2381. }
  2382. }
  2383. }
  2384. //if(pageElement)this.saveCurSiteRule();
  2385. }
  2386.  
  2387. if (doc !== document) {
  2388. this.setPageElementCss(pageElement);
  2389. this.lazyImgAction(pageElement, doc);
  2390. this.filterEles(doc, pageElement);
  2391. } else if (!this.docPageElement) {
  2392. this.setPageElementCss(pageElement, true);
  2393. this.docPageElement = pageElement;
  2394. this.filterEles(doc, pageElement);
  2395. if (this.nextLinkHref) {
  2396. this.openInNewTab(pageElement);
  2397. }
  2398. }
  2399. return pageElement;
  2400. }
  2401.  
  2402. showAddedElements() {
  2403. if (!this.addedElementsIsHide) return;
  2404. if (this.addedElePool && this.addedElePool.length) {
  2405. this.addedElePool.forEach(ele => {
  2406. ele.classList && ele.classList.remove("pagetual-hide");
  2407. });
  2408. }
  2409. this.addedElementsIsHide = false;
  2410. }
  2411.  
  2412. hideAddedElements() {
  2413. if (this.addedElePool && this.addedElePool.length) {
  2414. this.addedElePool.forEach(ele => {
  2415. ele.classList && ele.classList.add("pagetual-hide");
  2416. });
  2417. }
  2418. this.addedElementsIsHide = true;
  2419. }
  2420.  
  2421. toggleAddedElements() {
  2422. if (this.addedElementsIsHide) {
  2423. this.showAddedElements();
  2424. } else {
  2425. this.hideAddedElements();
  2426. }
  2427. }
  2428.  
  2429. changeVisibility() {
  2430. let contentVisibility = this.curSiteRule.contentVisibility || rulesData.contentVisibility;
  2431. if (!contentVisibility) return;
  2432. if (!this.changingVisibility) {
  2433. clearTimeout(this.changeVisibilityTimer);
  2434. this.changeVisibilityTimer = setTimeout(() => {
  2435. this.changingVisibility = true;
  2436. this.changeVisibility();
  2437. }, 300);
  2438. return;
  2439. }
  2440. this.changingVisibility = false;
  2441. if (!this.visibilityItems || !this.visibilityItems.length || this.visibleIndex < 0) return;
  2442. let tempIndex = this.visibleIndex, findVisible = false, lastVisible = 0;
  2443. let viewPortHeight = window.innerHeight || document.documentElement.clientHeight || getBody(document).clientHeight;
  2444. let checkItem = this.visibilityItems[tempIndex];
  2445. while(checkItem) {
  2446. if (checkItem.offsetParent) {
  2447. if (!checkItem.style.containIntrinsicSize) return;
  2448. let clientRect = checkItem.getBoundingClientRect();
  2449. let top = clientRect && clientRect.top;
  2450. let bottom = clientRect && clientRect.bottom;
  2451. if (bottom > 0 && top < viewPortHeight) {
  2452. if (!findVisible) {
  2453. findVisible = true;
  2454. lastVisible = tempIndex;
  2455. }
  2456. checkItem.style.contentVisibility = "visible";
  2457. } else {
  2458. if (top < viewPortHeight && checkItem.style.contentVisibility === "auto") {
  2459. break;
  2460. } else checkItem.style.contentVisibility = "auto";
  2461. }
  2462. }
  2463. if (tempIndex === 0) break;
  2464. tempIndex--;
  2465. checkItem = this.visibilityItems[tempIndex];
  2466. }
  2467. tempIndex = this.visibleIndex + 1;
  2468. if (findVisible) {
  2469. this.visibleIndex = lastVisible;
  2470. }
  2471. checkItem = this.visibilityItems[tempIndex];
  2472. while(checkItem) {
  2473. if (checkItem.offsetParent) {
  2474. if (!checkItem.style.containIntrinsicSize) return;
  2475. let clientRect = checkItem.getBoundingClientRect();
  2476. let top = clientRect && clientRect.top;
  2477. let bottom = clientRect && clientRect.bottom;
  2478. if (bottom > 0 && top < viewPortHeight) {
  2479. findVisible = true;
  2480. lastVisible = tempIndex;
  2481. checkItem.style.contentVisibility = "visible";
  2482. } else {
  2483. if (findVisible && checkItem.style.contentVisibility === "auto") {
  2484. break;
  2485. } else checkItem.style.contentVisibility = "auto";
  2486. }
  2487. }
  2488. if (tempIndex === this.visibilityItems.length - 1) break;
  2489. tempIndex++;
  2490. checkItem = this.visibilityItems[tempIndex];
  2491. }
  2492. if (findVisible) {
  2493. this.visibleIndex = lastVisible;
  2494. }
  2495. }
  2496.  
  2497. setPageElementCss(pageElement, init) {
  2498. let self = this;
  2499. if (pageElement && pageElement.length > 0) {
  2500. let pageElementCss = this.curSiteRule.pageElementCss || rulesData.pageElementCss;
  2501. if (!pageElementCss && init && !this.nextLinkHref) return;
  2502. let contentVisibility = this.curSiteRule.contentVisibility || rulesData.contentVisibility;
  2503. if (!contentVisibility && !pageElementCss) return;
  2504. [].forEach.call(pageElement, (ele, i) => {
  2505. if (!compareNodeName(ele, ["link", "meta", "style", "script"])) {
  2506. if (pageElementCss) {
  2507. if (pageElementCss !== '0' && !ele.dataset.pagetualPageElement) {
  2508. ele.style.cssText = (ele.style.cssText || '') + pageElementCss;
  2509. ele.dataset.pagetualPageElement = 1;
  2510. }
  2511. }
  2512. if (contentVisibility) {
  2513. ele.style.containIntrinsicSize = `auto ${ele.offsetHeight || self.preVisibleHeight || 100}px`;
  2514. if (ele.style.containIntrinsicSize) {
  2515. if (ele.offsetHeight) self.preVisibleHeight = ele.offsetHeight;
  2516. if (init) {
  2517. ele.style.contentVisibility = "visible";
  2518. self.visibilityItems.push(ele);
  2519. self.visibleIndex++;
  2520. } else {
  2521. ele.style.contentVisibility = emuIframe ? "visible" : "auto";
  2522. }
  2523. }
  2524. }
  2525. }
  2526. });
  2527. }
  2528. }
  2529.  
  2530. clearAddedElements() {
  2531. if (this.addedElePool && this.addedElePool.length) {
  2532. this.addedElePool.forEach(ele => {
  2533. if (ele.parentNode) ele.parentNode.removeChild(ele);
  2534. });
  2535. }
  2536. this.addedElePool = [];
  2537. sideController.remove();
  2538. }
  2539.  
  2540. linkHasHref(link) {
  2541. return link.href && link.href.replace && !this.hrefIsJs(link.href);
  2542. }
  2543.  
  2544. hrefIsJs(href) {
  2545. return /^(javascript|#|$)/.test(href.trim().replace("#p{", "").replace(location.href, ""));
  2546. }
  2547.  
  2548. async querySelectorList(source, list, defaultView) {
  2549. for (let i = 0; i < list.length; i++) {
  2550. await sleep(1);
  2551. let sel = list[i];
  2552. let result = getAllElements(sel, source);
  2553. if (result.length > 0) {
  2554. if (defaultView) {
  2555. for (let i = result.length - 1; i >= 0; i--) {
  2556. let ele = result[i];
  2557. if (isVisible(ele, defaultView)) return ele;
  2558. }
  2559. }
  2560. return result[result.length - 1];
  2561. }
  2562. }
  2563. return null;
  2564. }
  2565.  
  2566. verifyElement(ele) {
  2567. let verifyHandler = e => {
  2568. if (e.nodeType == 9) return true;
  2569. if (e.style.display === "none" || e.getAttribute("aria-disabled") === "true") {
  2570. return false;
  2571. }
  2572. if (e.className) {
  2573. if (/slick|slide|gallery|disabled\s*$/i.test(e.className)) {
  2574. return false;
  2575. } else if (e.classList) {
  2576. if (e.classList.contains('disabled') || e.classList.contains('active')) {
  2577. return false;
  2578. }
  2579. }
  2580. }
  2581. let ariaLabel = e.getAttribute("aria-label");
  2582. if (ariaLabel && /slick|slide|gallery/i.test(ariaLabel)) return false;
  2583. return true;
  2584. };
  2585. if (!ele) return false;
  2586. let i = 0;
  2587. while (ele && i++ < 6) {
  2588. if (!verifyHandler(ele)) return false;
  2589. ele = ele.parentNode;
  2590. }
  2591. return true;
  2592. }
  2593.  
  2594. async getPage(doc, exist) {
  2595. if (document.documentElement.className.indexOf && document.documentElement.className.indexOf('discourse') !== -1) return {};
  2596. let body = getBody(doc);
  2597. let canSave = false;//發現頁碼選擇器在其他頁對不上,還是別保存了
  2598. let url = this.curUrl.slice(0, 250).replace("index.php?", "?");
  2599. let _url = url.replace(/\.s?html?$/i, "").toLowerCase();
  2600. let pageNum = 1, preStr = "", afterStr = "";
  2601. let pageTwoReg = /^[\/\?&]?[_-]?(p|page)?=?\/?2(\/[^\/]*$|\?|&|$)/i;
  2602. let pageMatch1 = url.match(/(.*[\?&]p(?:age)?=)(\d+)($|[#&].*)/i);
  2603. let doubtTextReg = /^\s*(»|>>)\s*$/;
  2604. if (pageMatch1) {
  2605. preStr = pageMatch1[1];
  2606. pageNum = parseInt(pageMatch1[2]);
  2607. afterStr = pageMatch1[3];
  2608. } else {
  2609. let pageMatch2 = url.match(/(.*[a-z\/\-_](?:p|page)?\/?)(\d+)(\.s?html?$|\/?$)/i);
  2610. if (pageMatch2) {
  2611. preStr = pageMatch2[1];
  2612. pageNum = parseInt(pageMatch2[2]);
  2613. afterStr = pageMatch2[3];
  2614. if (/^\/?$/.test(afterStr) && !/(p(age)?|_|\-|\/)$/.test(preStr)) {
  2615. preStr = "";
  2616. afterStr = "";
  2617. }
  2618. }
  2619. }
  2620. if (pageNum > 999) {
  2621. pageNum = 1;
  2622. preStr = "";
  2623. afterStr = "";
  2624. }
  2625. let curPage = doc, i, cur, jsNext;
  2626. let next1, next2, next3, next4, nextJs1, nextJs2;
  2627. let selectorList = [
  2628. ".page-next>a",
  2629. "a.next_page",
  2630. "#next_page",
  2631. ".curPage+a",
  2632. ".nextPage",
  2633. ".pagination-next>a",
  2634. "a[data-pagination=next]",
  2635. ".pageButtonsCurrent+a",
  2636. "a[class*=nextpage]",
  2637. "li.page-current+li>a",
  2638. "[class^=pag] a[rel=next]",
  2639. "[class^=Pag] [aria-label=next]",
  2640. "[aria-label='Next Page']",
  2641. "[aria-label='Next page']",
  2642. "[aria-label='next page']",
  2643. ".pagination-nav__item--next>a",
  2644. "a.pageright",
  2645. ".page-numbers.current+a",
  2646. "a.page-numbers.next",
  2647. "body [class*=pagination] li.active+span+li>a",
  2648. "body [class*=pagination] li.active+li>a",
  2649. "body [class^=pag] .current+a",
  2650. ".page_current+a",
  2651. "input[value='next']",
  2652. "input[value='Next page']",
  2653. "input[value='下一页']",
  2654. "input[value='下一頁']",
  2655. "a#pb_next",
  2656. "a#rightFix",
  2657. "a#btnPreGn",
  2658. "a.page-next",
  2659. "a.pages-next",
  2660. "a.page.right",
  2661. ".paging>.active+.item",
  2662. "a#next",
  2663. ".next>a",
  2664. ".next>button",
  2665. "a[alt=next]",
  2666. ".pg_area>em+a",
  2667. "button.next:not([disabled])",
  2668. ".btn_next:not([disabled])",
  2669. ".btn-next:not([disabled])",
  2670. "a#linkNext",
  2671. "body a[class*=page__next]",
  2672. "body [class*=pager]>a.next",
  2673. "body [class*=pagination-next]>a",
  2674. "body [class*=pagination-next]>button",
  2675. "body [class*=page--current]+li>a",
  2676. "body [class*=Pages]>.curr+a",
  2677. "body [class*=pagination] [class*=next]",
  2678. ".page>em+a",
  2679. "[name*=nextPage]",
  2680. '//button[contains(@class, "Page")][text()="Next"]',
  2681. '//button[contains(@class, "page")][text()="next"]'
  2682. ];
  2683. let next = await this.querySelectorList(body, selectorList, doc.defaultView);
  2684. if (!next) {
  2685. await sleep(1);
  2686. let nexts = body.querySelectorAll("a.next");
  2687. const prevReg = /^\s*([上前首尾]|previous)/i;
  2688. for (i = 0; i < nexts.length; i++) {
  2689. let n = nexts[i];
  2690. if (this.verifyElement(n) && this.linkHasHref(n) && !prevReg.test(n.innerText.trim())) {
  2691. next = n;
  2692. break;
  2693. }
  2694. }
  2695. }
  2696. if (next) {
  2697. let innerText = next.innerText;
  2698. let isJs = !this.linkHasHref(next);
  2699. if (innerText && nextTextReg2.test(innerText.trim())) {
  2700. if (isJs) {
  2701. if (this.verifyElement(next)) {
  2702. nextJs2 = next;
  2703. }
  2704. } else {
  2705. next2 = next;
  2706. }
  2707. next = null;
  2708. } else {
  2709. if (isJs) {
  2710. if (this.verifyElement(next)) {
  2711. jsNext = next;
  2712. }
  2713. next = null;
  2714. }
  2715. }
  2716. }
  2717. if (!next) {
  2718. await sleep(1);
  2719. next = body.querySelector("a.curr+a") ||
  2720. body.querySelector("div.wp-pagenavi>span.current+a,div.page-nav>span.current+a,div.article-paging>span+a") ||
  2721. body.querySelector(".number>ul>li.active+li>a");
  2722. }
  2723. if (!next) {
  2724. await sleep(1);
  2725. let pageDiv = body.querySelector(".pages>ul,.page_no>ul");
  2726. if (pageDiv) {
  2727. cur = pageDiv.querySelector("li>b,li>strong");
  2728. if (cur) next = cur.parentNode.nextElementSibling;
  2729. if (next) next = next.querySelector("a");
  2730. }
  2731. }
  2732. if (!next) {
  2733. await sleep(1);
  2734. next = body.querySelector(".pages>a[href='javascript:;']+a");
  2735. if (next && (next.href === "javascript:;" || next.getAttribute("href") === "#")) next = null;
  2736. }
  2737. if (!next) {
  2738. await sleep(1);
  2739. let pageDiv = body.querySelector(".pagination");
  2740. if (pageDiv) {
  2741. cur = pageDiv.querySelector("[class*=current],.page-selected");
  2742. if (cur) next = cur.parentNode.nextElementSibling;
  2743. if (next) next = next.querySelector("a");
  2744. }
  2745. }
  2746. if (!next) {
  2747. await sleep(1);
  2748. cur = body.querySelector(".paginator td strong");
  2749. if (cur) {
  2750. while (cur && !compareNodeName(cur, ["td"])) {
  2751. cur = cur.parentNode;
  2752. }
  2753. next = cur && cur.nextElementSibling;
  2754. if (next) next = next.querySelector("a");
  2755. }
  2756. }
  2757. if (!next) {
  2758. await sleep(1);
  2759. let pageDivs = body.querySelectorAll("[class*=pagination],[class*=Pagination]");
  2760. if (pageDivs && pageDivs.length) {
  2761. for (let i = pageDivs.length - 1; i >= 0; i--) {
  2762. let p = pageDivs[i];
  2763. if (/(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)/i.test(p.title || p.value || '')) {
  2764. next = p.querySelector("a,button,[type='button']") || p;
  2765. break;
  2766. } else if (/^(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)$/i.test((p.innerText || '').trim())) {
  2767. next = p.querySelector("a,button,[type='button']") || p;
  2768. break;
  2769. }
  2770. }
  2771. if (next && !this.linkHasHref(next)) {
  2772. if (!jsNext) jsNext = next;
  2773. next = null;
  2774. }
  2775. }
  2776. }
  2777. if (!next) {
  2778. let isApp = !!body.querySelector("main#app");
  2779. let aTags = body.querySelectorAll("a,button,[type='button'],.btn-action");
  2780. for (i = aTags.length - 1; i >= 0; i--) {
  2781. if (next1) break;
  2782. if (i % 100 === 0) {
  2783. await sleep(1);
  2784. }
  2785. let aTag = aTags[i];
  2786. let title = aTag.title || "";
  2787. let value = aTag.value || "";
  2788. let innerText = aTag.innerText || "";
  2789. if (innerText === "" || (title !== "" && title.length < innerText.length)) {
  2790. innerText = title;
  2791. }
  2792. if (innerText === "" || (value !== "" && value.length < innerText.length)) {
  2793. innerText = value;
  2794. }
  2795. if (innerText !== "") {
  2796. if (innerText === "§") continue;
  2797. innerText = innerText.trim();
  2798. if (innerText.length > 80) continue;
  2799. }
  2800. if (!this.verifyElement(aTag)) continue;
  2801. if (aTag.dataset && aTag.dataset.preview) continue;
  2802. let availableHref = aTag.href && aTag.href.length < 250 && !/^(javascript:|#)/.test(aTag.href);
  2803. if (availableHref && /next\-?(page)?$|\/video\/|\/vod\/play\//i.test(aTag.href)) continue;
  2804. if (compareNodeName(aTag.parentNode, ["blockquote"])) continue;
  2805. if (aTag.previousElementSibling && /\b(play|volume)\b/.test(aTag.previousElementSibling.className)) continue;
  2806. if (aTag.nextElementSibling && /\b(play|volume)\b/.test(aTag.nextElementSibling.className)) continue;
  2807. let isJs = !this.linkHasHref(aTag);
  2808. if (exist && isJs && !aTag.offsetParent) continue;
  2809. if (innerText) {
  2810. innerText = innerText.split(/\n/)[0].replace(/ /g, '');
  2811. if (isJs && /^(»|>>|>|›|→|❯)$/.test(innerText)) continue;
  2812. if (innerText && innerText.length <= 25) {
  2813. if (!next1) {
  2814. if (nextTextReg1.test(innerText)) {
  2815. if (isJs) {
  2816. if (!nextJs1) nextJs1 = aTag;
  2817. } else {
  2818. next1 = aTag;
  2819. }
  2820. }
  2821. }
  2822. if (!next4) {
  2823. if (!next2) {
  2824. if (nextTextReg2.test(innerText) || /nextpage|pager\-older/i.test(aTag.className) || /^(»|>>)$/.test(innerText)) {
  2825. if (isJs) {
  2826. if (!nextJs2) nextJs2 = aTag;
  2827. } else {
  2828. next2 = aTag;
  2829. }
  2830. }
  2831. }
  2832. if (!isApp && !next3 && !isJs) {
  2833. if (/^(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)$/i.test(aTag.textContent) && aTag.parentNode.hasAttribute && !aTag.parentNode.hasAttribute("jsaction")) {
  2834. next3 = aTag;
  2835. }
  2836. }
  2837. }
  2838. }
  2839. }
  2840. if (isJs) continue;
  2841. if (!next4) {
  2842. let prevEle = aTag.previousElementSibling;
  2843. if (prevEle && compareNodeName(prevEle, ["b", "span", "strong"])) {
  2844. if (/^\d+$/.test(aTag.innerText.trim()) && /^\d+$/.test(prevEle.innerText.trim()) && parseInt(aTag.innerText) === parseInt(prevEle.innerText) + 1) {
  2845. next4 = aTag;
  2846. }
  2847. }
  2848. }
  2849. if (urlWillChange) continue;
  2850. if (!next4 && availableHref) {
  2851. let aHref = aTag.href.indexOf("http") === 0 ? aTag.href : this.canonicalUri(aTag.href);
  2852. if (aHref.indexOf(location.hostname) === -1) continue;
  2853. let _aHref = aHref.replace("?&", "?").replace("index.php?", "?");
  2854. if (preStr || afterStr) {
  2855. let _aHrefTrim = _aHref;
  2856. if (preStr) _aHrefTrim = _aHrefTrim.replace(preStr, "");
  2857. if (afterStr) _aHrefTrim = _aHrefTrim.replace(afterStr, "");
  2858. if (_aHrefTrim == pageNum + 1) {
  2859. next4 = aTag;
  2860. }
  2861. } else if (this.curUrl !== aHref) {
  2862. _aHref = _aHref.replace(/\.s?html?$/i, "").toLowerCase();
  2863. if (_aHref.indexOf(_url) !== -1) {
  2864. let pageTwoMatch = _aHref.replace(_url, "").match(pageTwoReg);
  2865. if (pageTwoMatch) {
  2866. afterStr = pageTwoMatch[2];
  2867. next4 = aTag;
  2868. }
  2869. }
  2870. }
  2871. if (next4 && !/page/.test(next4.href)) {
  2872. let curHref = next4.getAttribute("href");
  2873. let curPageReg = new RegExp("(.*)" + (pageNum + 1) + afterStr.replace(/([\.\?])/g, '\\$1'));
  2874. let otherPageHref = curHref.replace(curPageReg, `$1${pageNum}${afterStr}`);
  2875. let otherPageEle = body.querySelector(`a[href='${otherPageHref}']`);
  2876. if (!otherPageEle) {
  2877. otherPageHref = curHref.replace(curPageReg, `$1${pageNum + 2}${afterStr}`);
  2878. otherPageEle = body.querySelector(`a[href='${otherPageHref}']`);
  2879. }
  2880. if (otherPageEle) {
  2881. let parent = otherPageEle.parentNode;
  2882. if (parent && parent.parentNode) {
  2883. parent = parent.parentNode;
  2884. if (parent.parentNode) {
  2885. parent = parent.parentNode;
  2886. }
  2887. }
  2888. if (parent && parent.contains(next4) && !/^\d+$/.test(next4.innerText.trim())) {
  2889. next4 = null;
  2890. }
  2891. }
  2892. }
  2893. }
  2894. }
  2895. if (next2 && doubtTextReg.test(next2.innerText)) {
  2896. next2 = this.verifyNext(next2, doc, false);
  2897. }
  2898. if (nextJs2 && doubtTextReg.test(nextJs2.innerText)) {
  2899. nextJs2 = this.verifyNext(nextJs2, doc, true);
  2900. }
  2901. if (next3) {
  2902. next3 = this.verifyNext(next3, doc, false);
  2903. }
  2904. }
  2905. if (!next) next = next1 || next4 || next3 || next2;
  2906. if (!next && location.pathname + location.search !== "/") {
  2907. next = jsNext || nextJs1 || nextJs2;
  2908. if (next && next.parentNode.className && next.parentNode.className.indexOf && next.parentNode.className.indexOf('tab') !== -1) next = null;
  2909. }
  2910. if (next && next.classList && (next.classList.contains("results-more") || next.classList.contains("no"))) next = null;
  2911. if (next && next.hasAttribute && next.hasAttribute("disabled")) next = null;
  2912. if (next && next.parentNode.href && compareNodeName(next.parentNode, ["a"])) next = next.parentNode;
  2913. return {next:next, canSave:canSave};
  2914. }
  2915.  
  2916. verifyNext(next, doc, isJs) {
  2917. if (!next) return null;
  2918. if (!isJs) {
  2919. let href = next.getAttribute("href");
  2920. if (href && !/\d/.test(next.getAttribute("href"))) {
  2921. return null;
  2922. }
  2923. }
  2924. if (next.previousElementSibling && compareNodeName(next.previousElementSibling, ["br"])) return null;
  2925. let eles = [];
  2926. if (next.innerText && next.innerText.indexOf("\n") === -1) {
  2927. eles = getAllElements(`//${next.nodeName}[text()='${next.innerText}']`, doc);
  2928. }
  2929. if (eles.length >= 2 && eles[0].href !== eles[1].href) {
  2930. next = null;
  2931. } else if (doc === document) {
  2932. let left = getElementLeft(next);
  2933. if (left < 20 || (document.documentElement.scrollWidth > 500 && left < 250)) {
  2934. next = null;
  2935. } else {
  2936. let top = getElementTop(next);
  2937. if (top < 20 || (left < window.innerWidth / 3 && top < window.innerHeight / 3)) {
  2938. next = null;
  2939. } else {
  2940. let bottom = top + next.offsetHeight || 0;
  2941. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  2942. if (scrollH - bottom < 10) next = null;
  2943. }
  2944. }
  2945. }
  2946. return next;
  2947. }
  2948.  
  2949. canonicalUri(src) {
  2950. if (!src) {
  2951. return "";
  2952. }
  2953. if (src.charAt(0) === "#") return this.curUrl + src;
  2954. if (src.charAt(0) === "?") return this.curUrl.replace(/^([^\?#]+).*/, "$1" + src);
  2955. let origin = location.protocol + '//' + location.host;
  2956. let url = this.basePath || origin;
  2957. url = url.replace(/(\?|#).*/, "");
  2958. if (/https?:\/\/[^\/]+$/.test(url)) url = url + '/';
  2959. if (url.indexOf("http") !== 0) url = origin + url;
  2960. var root_page = /^[^\?#]*\//.exec(url)[0],
  2961. root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  2962. absolute_regex = /^\w+\:\/\//;
  2963. this.updateUrl = false;
  2964. while (src.indexOf("../") === 0) {
  2965. src = src.substr(3);
  2966. root_page = root_page.replace(/\/[^\/]+\/$/, "/");
  2967. this.updateUrl = true;
  2968. }
  2969. src = src.replace(/\.\//, "");
  2970. if (/^\/\/\/?/.test(src)) {
  2971. src = location.protocol + src;
  2972. }
  2973. return (absolute_regex.test(src) ? src : ((src.charAt(0) === "/" ? root_domain : root_page) + src));
  2974. }
  2975.  
  2976. getLinkByPage(url, pageNum) {
  2977. if (!url) return null;
  2978. if (this.curSiteRule.pageNum) {
  2979. let result = this.curSiteRule.pageNum;
  2980. let strMatch = result.match(/\{.*?}/);
  2981. if (!strMatch) return null;
  2982. let urlReg = new RegExp("(" + result.replace(strMatch[0], ")\\d+(") + ")", "i");
  2983. let code = strMatch[0].replace(/^{/, "").replace(/}$/, "").replace(/\$p/g, pageNum);
  2984. if (code === pageNum) {
  2985. result = url.replace(urlReg, "$1" + code + "$2");
  2986. } else {
  2987. try {
  2988. code = Function('"use strict";return ' + code)();
  2989. if (code && code % 1 == 0) {
  2990. result = url.replace(urlReg, "$1" + code + "$2");
  2991. } else return null;
  2992. } catch(e) {
  2993. debug(e);
  2994. }
  2995. }
  2996. if (result != url) {
  2997. return result;
  2998. }
  2999. }
  3000. return url.replace(/([&\/\?](p=|page[=\/_-]?))\d+/i, "$1" + pageNum).replace(/([_-])\d+\./i, "$1" + pageNum + ".");
  3001. }
  3002.  
  3003. getPageNumFromUrl(url, defaultPage) {
  3004. if (!url) return defaultPage;
  3005. if (this.curSiteRule.pageNum) {
  3006. let result = this.curSiteRule.pageNum;
  3007. let strMatch = result.match(/\{.*?}/);
  3008. if (!strMatch) return defaultPage;
  3009. let urlReg = new RegExp(".*" + result.replace(strMatch[0], "(\\d+)") + ".*", "i");
  3010. let curShowNum = url.replace(urlReg, "$1");
  3011. if (curShowNum !== url) {
  3012. let code = strMatch[0].replace(/^{/, "").replace(/}$/, "");
  3013. if (code === "$p") {
  3014. return curShowNum;
  3015. } else {
  3016. try {
  3017. let page1 = parseInt(Function('"use strict";return ' + code.replace("$p", "0"))());
  3018. let page2 = parseInt(Function('"use strict";return ' + code.replace("$p", "1"))());
  3019. let numGap = page2 - page1;
  3020. let _page = (parseInt(curShowNum) - page1) / numGap;
  3021. if (_page && _page % 1 === 0) return _page;
  3022. else {
  3023. this.curSiteRule.pageNum = null;
  3024. return defaultPage;
  3025. }
  3026. } catch(e) {
  3027. debug(e);
  3028. }
  3029. }
  3030. } else {
  3031. return defaultPage;
  3032. }
  3033. }
  3034. let pageNum = url.replace(/.*[&\/\?](p=|page[=\/_-]?)(\d+).*/i, "$2");
  3035. return pageNum === url ? defaultPage : (pageNum.length > 4 ? defaultPage : pageNum);
  3036. }
  3037.  
  3038. async getNextLink(doc, exist) {
  3039. let nextLink = null, page, href;
  3040. let getNextLinkByForm = (form, submitBtn, n) => {
  3041. let params = [];
  3042. let formData = new FormData(form);
  3043. if (submitBtn && submitBtn.getAttribute) {
  3044. let btnValue, btnName;
  3045. btnName = submitBtn.getAttribute("name");
  3046. btnValue = submitBtn.getAttribute("value");
  3047. if (btnName && btnValue) params = [btnName + "=" + encodeURIComponent(btnValue)];
  3048. }
  3049. for (let [key, value] of formData) {
  3050. if (n && /^(p|page)$/i.test(key)) {
  3051. params.push(key + '=' + n);
  3052. } else {
  3053. params.push(key + '=' + encodeURIComponent(value));
  3054. }
  3055. }
  3056. params = params.join('&');
  3057. return form.action + (form.action.indexOf('?') === -1 ? '?' : '&') + params + (form.method === 'post' ? '#p{' + params + '}' : '');
  3058. };
  3059. if (this.curSiteRule.pageElementByJs) {
  3060. this.nextLinkHref = "#";
  3061. return true;
  3062. } else if (this.curSiteRule.nextLinkByJs) {
  3063. try {
  3064. let over = _url => {};
  3065. let targetUrl = await ((typeof this.curSiteRule.nextLinkByJs === 'function') ? this.curSiteRule.nextLinkByJs : new AsyncFunction("doc", '"use strict";' + this.curSiteRule.nextLinkByJs))(doc);
  3066. if (targetUrl) nextLink = {href: targetUrl};
  3067. } catch(e) {
  3068. debug(e);
  3069. }
  3070. } else if (this.curSiteRule.nextLinkByUrl) {
  3071. let targetUrl = this.curUrl.replace(new RegExp(this.curSiteRule.nextLinkByUrl[0], "i"), this.curSiteRule.nextLinkByUrl[1]);
  3072. if (targetUrl !== this.curUrl) {
  3073. let includeSel = this.curSiteRule.nextLinkByUrl[2];
  3074. let excludeSel = this.curSiteRule.nextLinkByUrl[3];
  3075. if (includeSel) {
  3076. includeSel = includeSel.trim();
  3077. if (!getElement(includeSel, doc)) {
  3078. this.nextLinkHref=false;
  3079. return null;
  3080. }
  3081. }
  3082. if (excludeSel) {
  3083. excludeSel = excludeSel.trim();
  3084. if (getElement(excludeSel, doc)) {
  3085. this.nextLinkHref=false;
  3086. return null;
  3087. }
  3088. }
  3089. let reps = targetUrl.match(/{.*?}/g);
  3090. if (reps) {
  3091. reps.forEach(rep => {
  3092. let code = rep.replace("{", "").replace("}", "").replace(/\(\)/g, "0");
  3093. let result = code.match(/^(\d*)\+1$/);
  3094. if (result) {
  3095. result = parseInt(result[1] || 1) + 1;
  3096. } else {
  3097. try {
  3098. result = Function('"use strict";return ' + code)();
  3099. } catch(e) {
  3100. debug(e);
  3101. }
  3102. }
  3103. targetUrl = targetUrl.replace(rep, result);
  3104. });
  3105. }
  3106. }
  3107. nextLink = {href: targetUrl};
  3108. } else if (typeof this.curSiteRule.nextLink !== 'undefined') {
  3109. let nextLinkSel = this.curSiteRule.nextLink;
  3110. if (nextLinkSel != 0) {
  3111. if (Array && Array.isArray && Array.isArray(nextLinkSel)) {
  3112. nextLink = getElement(nextLinkSel[nextIndex], doc, null, true);
  3113. if (!nextLink && curPage === 1 && nextIndex !== 0) {
  3114. nextIndex = 0;
  3115. nextLink = getElement(nextLinkSel[nextIndex], doc, null, true);
  3116. }
  3117. } else nextLink = getElement(nextLinkSel, doc, null, true);
  3118. }
  3119. if (nextLink && (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2)) {
  3120. let form = doc.querySelector('#search-form');
  3121. if (!nextLink.href && nextLink.hasAttribute && nextLink.hasAttribute("onclick") && form) {
  3122. if (/^\d+$/.test(nextLink.innerText)) {
  3123. nextLink.href = getNextLinkByForm(form, nextLink, nextLink.innerText);
  3124. }
  3125. } else if (compareNodeName(nextLink, ["input"]) || nextLink.type === "submit") {
  3126. form = nextLink.parentNode;
  3127. while (form) {
  3128. if (compareNodeName(form, ["form"])) break;
  3129. else form = form.parentNode;
  3130. }
  3131. if (form) {
  3132. nextLink.href = getNextLinkByForm(form, nextLink);
  3133. }
  3134. }
  3135. if (nextLink.href && this.curSiteRule.action != 0) {
  3136. nextLink.href = nextLink.href.replace(/#p{.*/, "");
  3137. }
  3138. }
  3139. } else {
  3140. page = await this.getPage(doc, exist);
  3141. nextLink = page.next;
  3142. if (nextLink) {
  3143. if (compareNodeName(nextLink, ["input"]) || nextLink.type === "submit") {
  3144. if (!/next/i.test(nextLink.getAttribute("onclick"))) {
  3145. let form = nextLink.parentNode;
  3146. while (form) {
  3147. if (compareNodeName(form, ["form"])) break;
  3148. else form = form.parentNode;
  3149. }
  3150. if (form) {
  3151. nextLink.href = getNextLinkByForm(form, nextLink);
  3152. }
  3153. }
  3154. }
  3155. let parent = nextLink;
  3156. while (parent && !compareNodeName(parent, ["body"])) {
  3157. if (parent.hasAttribute && parent.hasAttribute("disabled")) {
  3158. this.nextLinkHref = false;
  3159. return null;
  3160. }
  3161. if (parent.className && parent.classList) {
  3162. if (parent.classList.contains("noClick") || parent.classList.contains("no-pages") || parent.classList.contains("disabled")) {
  3163. this.nextLinkHref = false;
  3164. return null;
  3165. }
  3166. }
  3167. if (parent.style && parent.style.display === "none") {
  3168. this.nextLinkHref = false;
  3169. return null;
  3170. }
  3171. parent = parent.parentNode;
  3172. }
  3173. if (doc === document) {
  3174. if (!this.linkHasHref(nextLink)) {
  3175. if ((clickedSth && this.curSiteRule.smart) || !isVisible(nextLink, _unsafeWindow)) {
  3176. this.nextLinkHref = false;
  3177. return null;
  3178. }
  3179. let video = document.querySelector("video,iframe[id*=play],[id*=play]>iframe,iframe[src*=player],iframe[src*=m3u8]");
  3180. if (video) {
  3181. if (video.offsetParent && video.name !== 'pagetual-iframe') {
  3182. let scrollWidth = video.scrollWidth || video.offsetWidth;
  3183. let scrollHeight = video.scrollHeight || video.offsetHeight;
  3184. if (compareNodeName(video, ["iframe"])) {
  3185. } else if (scrollWidth > 100 && scrollHeight > 100) {
  3186. let winWidth = window.innerWidth || document.documentElement.clientWidth;
  3187. let winHeight = window.innerHeight || document.documentElement.clientHeight;
  3188. if (scrollWidth > winWidth>>1 && scrollHeight > winHeight>>1) {
  3189. debug("Disable when large media found");
  3190. } else {
  3191. video = null;
  3192. }
  3193. } else {
  3194. video = null;
  3195. }
  3196. } else {
  3197. video = null;
  3198. }
  3199. }
  3200. if (video) {
  3201. isPause = true;
  3202. this.clearAddedElements();
  3203. this.nextLinkHref = false;
  3204. return null;
  3205. }
  3206. }
  3207.  
  3208. let nextLinkCs = _unsafeWindow.getComputedStyle(nextLink);
  3209. if (nextLinkCs.cursor === "not-allowed") {
  3210. this.nextLinkHref = false;
  3211. return null;
  3212. }
  3213. this.initNext = nextLink;
  3214. }
  3215. let form = doc.querySelector('#search-form');
  3216. if (!nextLink.href && nextLink.hasAttribute("onclick") && form) {
  3217. if (form && /^\d+$/.test(nextLink.innerText)) {
  3218. href = getNextLinkByForm(form, nextLink, nextLink.innerText);
  3219. }
  3220. }
  3221. }
  3222. }
  3223. if (nextLink) {
  3224. if (!this.checkStopSign(nextLink, doc)) {
  3225. if (curPage > 1) {
  3226. if (rulesData.lastPageTips) {
  3227. showTips(i18n("lastPage"), "", 800);
  3228. }
  3229. _unsafeWindow.postMessage({
  3230. action: "lastPage",
  3231. command: 'pagetual'
  3232. }, '*');
  3233. }
  3234. return null;
  3235. }
  3236. if (this.curSiteRule.action == 3) {
  3237. if (doc == document) debug(nextLink, 'Next link');
  3238. this.nextLinkHref = '#';
  3239. } else {
  3240. let needUrl = (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2);
  3241. if (!href) href = nextLink.href;
  3242. if (href && nextLink.getAttribute) {
  3243. let _href = nextLink.getAttribute("href");
  3244. if (_href) {
  3245. let realHref = _href.replace(location.href, "");
  3246. if (realHref.charAt(0) === "#" || realHref === "?"){
  3247. href = "#";
  3248. } else {
  3249. href = _href;
  3250. }
  3251. } else if (_href === "") {
  3252. href = _href;
  3253. }
  3254. }
  3255.  
  3256. if (needUrl && (href === "" || href === null)) {
  3257. this.nextLinkHref = false;
  3258. } else if (needUrl && /^(javascript:|#)/.test(href)) {
  3259. this.nextLinkHref = false;
  3260. } else {
  3261. this.nextLinkHref = (href && !/^(javascript:|#)/.test(href)) ? this.canonicalUri(href) : "#";
  3262. let tempUrl = this.nextLinkHref;
  3263. if (tempUrl !== "#" && (this.compareUrl(tempUrl, this.initUrl) || this.compareUrl(tempUrl, this.curUrl) || this.compareUrl(tempUrl, this.curUrl + "#") || this.compareUrl(tempUrl, this.oldUrl) || this.compareUrl(tempUrl, this.oldUrl + "#"))) {
  3264. this.nextLinkHref = false;
  3265. } else if (doc === document) {
  3266. debug(nextLink, 'Next link');
  3267. }
  3268. }
  3269. }
  3270. } else {
  3271. this.nextLinkHref = false;
  3272. }
  3273. this.nextLinkEle = nextLink;
  3274. this.preload();
  3275. return nextLink;
  3276. }
  3277.  
  3278. compareUrl(url1, url2) {
  3279. if (url1 === url2) return true;
  3280. if (!url1 || !url2) return false;
  3281. let url1Arr = url1.split("?");
  3282. let url2Arr = url2.split("?");
  3283. if (url1Arr[0] != url2Arr[0]) return false;
  3284. if (!url1Arr[1] || !url2Arr[1]) return false;
  3285. url1Arr = url1Arr[1].split("&").sort().join("&");
  3286. url2Arr = url2Arr[1].split("&").sort().join("&");
  3287. return url1Arr === url2Arr;
  3288. }
  3289.  
  3290. filterEles(doc, eles) {
  3291. let filter = this.curSiteRule.filter;
  3292. if (!filter || !eles || eles.length === 0) return;
  3293. if (eles.length === 1) {
  3294. eles = eles[0].children;
  3295. if (eles.length === 1) {
  3296. eles = eles[0].children;
  3297. }
  3298. }
  3299. if (typeof filter === "string") {
  3300. if (/^\d+$/.test(filter)) {
  3301. filter = {count: parseInt(filter)};
  3302. } else filter = {words: filter};
  3303. }
  3304. [].forEach.call(eles, ele => {
  3305. if (!ele.parentNode) return;
  3306. let canKeep = (() => {
  3307. let innerText = (ele.innerText && ele.innerText.trim()) || "";
  3308. if (filter.count) {
  3309. if (innerText.length < filter.count) return false;
  3310. }
  3311. if (filter.words) {
  3312. let wordsRegExp = new RegExp(filter.words, "i");
  3313. if (innerText && wordsRegExp.test(innerText)) return false;
  3314. }
  3315. if (filter.link) {
  3316. let linkRegExp = new RegExp(filter.link, "i");
  3317. if (compareNodeName(ele, ["a"]) && linkRegExp.test(ele.href)) return false;
  3318. let aChildren = ele.querySelectorAll("a");
  3319. for (let i = 0; i < aChildren.length; i++) {
  3320. let child = aChildren[i];
  3321. if (linkRegExp.test(child.href)) return false;
  3322. }
  3323. }
  3324. if (filter.selector) {
  3325. if (getElement(filter.selector, doc, ele)) return false;
  3326. }
  3327. return true;
  3328. })();
  3329. if (!canKeep) {
  3330. ele.parentNode.removeChild(ele);
  3331. }
  3332. });
  3333. }
  3334.  
  3335. checkStopSign(nextLink, doc) {
  3336. if (this.curSiteRule.stopSign) {
  3337. let typeArray = Array && Array.isArray && Array.isArray(this.curSiteRule.stopSign);
  3338. let typeObject = !typeArray && (this.curSiteRule.stopSign.include || this.curSiteRule.stopSign.exclude || this.curSiteRule.stopSign.pageNum);
  3339. if (typeArray || typeObject) {
  3340. let includeSel, excludeSel, curSign, maxSign;
  3341. if (typeArray) {
  3342. includeSel = this.curSiteRule.stopSign[0];
  3343. excludeSel = this.curSiteRule.stopSign[1];
  3344. curSign = this.curSiteRule.stopSign[2];
  3345. maxSign = this.curSiteRule.stopSign[3];
  3346. if (Array && Array.isArray && Array.isArray(includeSel) && !curSign) {
  3347. curSign = includeSel;
  3348. includeSel = false;
  3349. }
  3350. if (excludeSel && Array && Array.isArray && Array.isArray(excludeSel) && !maxSign) {
  3351. maxSign = excludeSel;
  3352. excludeSel = false;
  3353. }
  3354. } else {
  3355. includeSel = this.curSiteRule.stopSign.include;
  3356. excludeSel = this.curSiteRule.stopSign.exclude;
  3357. curSign = this.curSiteRule.stopSign.pageNum;
  3358. }
  3359. if (includeSel) {
  3360. includeSel = includeSel.trim();
  3361. if (!getElement(includeSel, doc)) {
  3362. isPause = true;
  3363. this.nextLinkHref = false;
  3364. return false;
  3365. }
  3366. }
  3367. if (excludeSel) {
  3368. excludeSel = excludeSel.trim();
  3369. if (getElement(excludeSel, doc)) {
  3370. isPause = true;
  3371. this.nextLinkHref = false;
  3372. return false;
  3373. }
  3374. }
  3375. if (curSign) {
  3376. if (!maxSign) maxSign = curSign.slice(2);
  3377. let currentEle = getElement(curSign[0], doc);
  3378. let maxEle = getElement(maxSign[0], doc);
  3379. if (currentEle && maxEle) {
  3380. let currentSignNum, maxSignNum;
  3381. if (/\(.*\)/.test(curSign[1])) {
  3382. currentSignNum = currentEle.innerText.match(new RegExp(curSign[1]));
  3383. if (currentSignNum) currentSignNum = currentSignNum[1];
  3384. } else if (currentEle.getAttribute) {
  3385. currentSignNum = currentEle.getAttribute(curSign[1]);
  3386. }
  3387. if (/\(.*\)/.test(maxSign[1])) {
  3388. maxSignNum = maxEle.innerText.match(new RegExp(maxSign[1]));
  3389. if (maxSignNum) maxSignNum = maxSignNum[1];
  3390. } else if (maxEle.getAttribute) {
  3391. maxSignNum = maxEle.getAttribute(maxSign[1]);
  3392. }
  3393. if (currentSignNum && maxSignNum && currentSignNum == maxSignNum) {
  3394. isPause = true;
  3395. this.nextLinkHref = false;
  3396. return false;
  3397. }
  3398. }
  3399. }
  3400. } else {
  3401. try {
  3402. let stopSign = ((typeof this.curSiteRule.stopSign === 'function') ? this.curSiteRule.stopSign : Function("doc", "nextLink", '"use strict";' + this.curSiteRule.stopSign))(doc, nextLink);
  3403. if (stopSign) {
  3404. isPause = true;
  3405. this.nextLinkHref = false;
  3406. return false;
  3407. }
  3408. } catch(e) {
  3409. debug(e);
  3410. }
  3411. }
  3412. }
  3413. return true;
  3414. }
  3415.  
  3416. preloadImageHandler() {
  3417. if (this.preloadingImage || !this.unCheckedImgs.length) return;
  3418. this.preloadingImage = true;
  3419. setTimeout(() => {
  3420. this.preloadingImage = false;
  3421. this.preloadImageHandler();
  3422. }, 10);
  3423. let iSrc = this.unCheckedImgs.shift();
  3424. let img = document.createElement('img');
  3425. img.src = iSrc;
  3426. this.preloadDiv.appendChild(img);
  3427. }
  3428.  
  3429. preload() {
  3430. if (!rulesData.preload) return;
  3431. if (this.curSiteRule.preload === 0) return;
  3432. if (!this.nextLinkHref || this.nextLinkHref == "#") return;
  3433. if (this.readyStateUnComplete) return;
  3434. if (document.readyState !== 'complete') {
  3435. this.readyStateUnComplete = true;
  3436. let self = this;
  3437. window.addEventListener("load", e => {
  3438. self.readyStateUnComplete = false;
  3439. self.preload();
  3440. });
  3441. return;
  3442. }
  3443. let self = this, url = this.nextLinkHref;
  3444. let postParams = url.match(/#p{(.*)}$/);
  3445. if (postParams) {
  3446. postParams = postParams[1];
  3447. url = url.replace(/#p{.*/, "");
  3448. }
  3449. _GM_xmlhttpRequest({
  3450. url: url,
  3451. method: postParams ? 'POST' : 'GET',
  3452. data: postParams,
  3453. overrideMimeType: 'text/html;charset=' + charset,
  3454. headers: {
  3455. 'Referer': location.href,
  3456. 'User-Agent': navigator.userAgent,
  3457. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + charset,
  3458. },
  3459. timeout: 10000,
  3460. onload: function(res) {
  3461. var doc = null;
  3462. try {
  3463. doc = document.implementation.createHTMLDocument('');
  3464. doc.documentElement.innerHTML = createHTML(res.response);
  3465. var body = getBody(doc);
  3466. if (!self.preloadDiv) {
  3467. self.preloadDiv = document.createElement('div');
  3468. self.preloadDiv.id = "pagetual-preload";
  3469. self.preloadDiv.style.cssText = 'display:none!important;';
  3470. getBody(document).appendChild(self.preloadDiv);
  3471. self.checkedImgs = {};
  3472. self.unCheckedImgs = [];
  3473. }
  3474. let code = self.curSiteRule.preloadImages;
  3475. if (code) {
  3476. let imgSrcArr = new Function("doc", '"use strict";' + code)(doc);
  3477. if (imgSrcArr && imgSrcArr.length) {
  3478. imgSrcArr.forEach(imgSrc => {
  3479. if (imgSrc && !self.checkedImgs[imgSrc]) {
  3480. self.checkedImgs[imgSrc] = true;
  3481. self.unCheckedImgs.push(imgSrc);
  3482. }
  3483. });
  3484. }
  3485. self.preloadImageHandler();
  3486. } else if (code !== 0 && code !== false) {
  3487. if (body && body.firstChild) {
  3488. self.lazyImgAction(body.children, doc);
  3489. }
  3490. [].forEach.call(doc.images, i => {
  3491. let iSrc = i.src;
  3492. if (iSrc && !self.checkedImgs[iSrc]) {
  3493. self.checkedImgs[iSrc] = true;
  3494. self.unCheckedImgs.push(iSrc);
  3495. }
  3496. });
  3497. self.preloadImageHandler();
  3498. }
  3499. }
  3500. catch(e) {
  3501. debug(e);
  3502. return;
  3503. }
  3504. }
  3505. });
  3506. }
  3507.  
  3508. getInsert(refresh) {
  3509. if (refresh) {
  3510. this.insert = null;
  3511. }
  3512. if (this.insert && this.insert.parentNode && document.documentElement.contains(this.insert)) {
  3513. return this.insert;
  3514. }
  3515. if (this.curSiteRule.insert) {
  3516. let insertSel = this.curSiteRule.insert;
  3517. if (Array && Array.isArray && Array.isArray(insertSel)) {
  3518. insertSel = insertSel[nextIndex < insertSel.length ? nextIndex : 0];
  3519. }
  3520. this.insert = getElement(insertSel, document, null, true);
  3521. } else {
  3522. this.docPageElement = null;
  3523. let pageElement = this.getPageElement(document, _unsafeWindow);
  3524. if (this.curSiteRule.smart && this.nextLinkHref == "#" && this.curSiteRule.pageElement === 'body') {
  3525. debug("Stop as jsNext & whole body");
  3526. isPause = true;
  3527. return null;
  3528. }
  3529. if (pageElement && pageElement.length > 0) {
  3530. let pEIndex = pageElement.length - 1;
  3531. let pELast = pageElement[pEIndex];
  3532. while(pELast && compareNodeName(pELast, ["link", "meta", "style", "script"])) {
  3533. pEIndex--;
  3534. pELast = pageElement[pEIndex];
  3535. }
  3536. this.insert = pELast.nextSibling ? pELast.nextSibling : pELast.parentNode.appendChild(document.createTextNode(' '));
  3537. }
  3538. }
  3539. return this.insert;
  3540. }
  3541.  
  3542. pageInit(doc, eles) {
  3543. let code = this.curSiteRule.pageInit;
  3544. if (code) {
  3545. let initFunc = ((typeof code == 'function') ? code : Function("doc", "eles", '"use strict";' + code));
  3546. let checkInit = (resolve) => {
  3547. try {
  3548. if (initFunc(doc, eles) === false) {
  3549. setTimeout(() => {
  3550. checkInit(resolve);
  3551. }, 100);
  3552. } else {
  3553. resolve(true);
  3554. }
  3555. } catch(e) {
  3556. resolve(false);
  3557. debug(e);
  3558. }
  3559. };
  3560. return new Promise((resolve) => {
  3561. checkInit(function(e) {
  3562. resolve(e)
  3563. });
  3564. })
  3565. }
  3566. }
  3567.  
  3568. pageAction(doc, eles) {
  3569. let code = this.curSiteRule.pageAction;
  3570. if (code) {
  3571. try {
  3572. ((typeof code == 'function') ? code : Function("doc", "eles", '"use strict";' + code))(doc, eles);
  3573. } catch(e) {
  3574. debug(e);
  3575. }
  3576. }
  3577. this.openInNewTab(eles);
  3578. this.replaceElement(doc);
  3579. }
  3580.  
  3581. openInNewTab(eles) {
  3582. if (openInNewTab) {
  3583. [].forEach.call(eles, ele => {
  3584. if (compareNodeName(ele, ["a"]) && ele.href && !/^(mailto:|javascript:)|#/.test(ele.href)) {
  3585. ele.setAttribute('target', openInNewTab == 1 ? '_blank' : '_self');
  3586. } else {
  3587. [].forEach.call(ele.querySelectorAll('a[href]:not([href^="mailto:"]):not([href^="javascript:"]):not([href^="#"])'), a => {
  3588. if (openInNewTab == 1) {
  3589. a.setAttribute('target', '_blank');
  3590. if (a.getAttribute('onclick') == 'atarget(this)') {
  3591. a.removeAttribute('onclick');
  3592. }
  3593. } else a.setAttribute('target', '_self');
  3594. });
  3595. }
  3596. });
  3597. }
  3598. }
  3599.  
  3600. lazyImgAction(eles, doc) {
  3601. if (!eles || eles.length == 0) return;
  3602. let lazyImgSrc = this.curSiteRule.lazyImgSrc;
  3603. if (lazyImgSrc === 0 || lazyImgSrc === '0') return;
  3604. let imgLazyAttrs = [];
  3605. let lazyAttrs = ["div[data-thumb]|data-src", "div.img|data-src", "div.lazy|data-src", "div.lazy|data-original", "a.lazy|data-bg", "a.lazyload|data-original"];
  3606. let removeProps = [];
  3607. let setLazyImg = img => {
  3608. let realSrc;
  3609. imgLazyAttrs.forEach(attr => {
  3610. realSrc = img.getAttribute(lazyImgSrc[0]);
  3611. if (realSrc) {
  3612. removeProps.forEach(prop => {
  3613. img.removeAttribute(prop.trim());
  3614. });
  3615. img.src = realSrc;
  3616. return;
  3617. }
  3618. })
  3619. if (!realSrc) {
  3620. let lazyAttr = "";
  3621. if (img.getAttribute("_src") && !img.src) {
  3622. lazyAttr = "_src";
  3623. realSrc = img.getAttribute(lazyAttr);
  3624. } else {
  3625. for (let i in lazyImgAttr) {
  3626. lazyAttr = lazyImgAttr[i];
  3627. let attrValue = img.getAttribute(lazyAttr);
  3628. if (attrValue) {
  3629. realSrc = attrValue;
  3630. break;
  3631. }
  3632. }
  3633. }
  3634. if (!realSrc && img._lazyrias && img._lazyrias.srcset) {
  3635. realSrc = img._lazyrias.srcset[img._lazyrias.srcset.length - 1];
  3636. lazyAttr = "_lazyrias";
  3637. }
  3638. if (!realSrc && img.srcset) {
  3639. lazyAttr = "srcset";
  3640. var srcs = img.srcset.split(/[xw],/i), largeSize = 0;
  3641. srcs.forEach(srci => {
  3642. let srcInfo = srci.trim().split(" "), curSize = parseInt(srcInfo[1]);
  3643. if (srcInfo[1] && curSize > largeSize) {
  3644. largeSize = curSize;
  3645. realSrc = srcInfo[0];
  3646. }
  3647. });
  3648. }
  3649. if (realSrc) {
  3650. img.src = realSrc;
  3651. img.removeAttribute("srcset");
  3652. img.removeAttribute(lazyAttr);
  3653. if (img.classList && img.classList.contains && img.classList.contains("lazy")) {
  3654. img.classList.remove("lazy");
  3655. }
  3656. if (img.style.display == "none") {
  3657. img.style.display = "";
  3658. }
  3659. if (img.style.visibility == "hidden") {
  3660. img.style.visibility = "";
  3661. }
  3662. if (img.style.opacity == 0) {
  3663. img.style.opacity = "";
  3664. }
  3665. }
  3666. }
  3667. };
  3668. if (lazyImgSrc) {
  3669. if (!Array.isArray(lazyImgSrc)) {
  3670. lazyAttrs = lazyImgSrc.split(",");
  3671. } else {
  3672. lazyAttrs = lazyImgSrc[0].split(",");
  3673. removeProps = lazyImgSrc[1].split(",");
  3674. }
  3675. }
  3676. lazyAttrs.forEach(attr => {
  3677. let attrArr = attr.split("|");
  3678. if (attrArr.length !== 2) {
  3679. imgLazyAttrs.push(attr.trim());
  3680. } else {
  3681. let selector = attrArr[0].trim();
  3682. let lazyAttr = attrArr[1].trim();
  3683. if (selector == "img") {
  3684. imgLazyAttrs.push(lazyAttr);
  3685. } else {
  3686. selector += "[" + lazyAttr + "]";
  3687. [].forEach.call(doc.querySelectorAll(selector), ele => {
  3688. ele.style.setProperty("background-image", "url(" + ele.getAttribute(lazyAttr) + ")", "important");
  3689. removeProps.forEach(prop => {
  3690. ele.removeAttribute(prop.trim());
  3691. });
  3692. });
  3693. }
  3694. }
  3695. });
  3696. [].forEach.call(doc.querySelectorAll("img,picture>source"), img => {
  3697. setLazyImg(img);
  3698. });
  3699. }
  3700.  
  3701. canListenUrlChange() {
  3702. if (this.curSiteRule) {
  3703. if (this.curSiteRule.listenUrlChange === true) return true;
  3704. if (this.curSiteRule.listenUrlChange === false) return false;
  3705. if (this.docElementValid()) {
  3706. return false;
  3707. }
  3708. }
  3709. return true;
  3710. }
  3711.  
  3712. docElementValid() {
  3713. return (this.docPageElement && document.documentElement.contains(this.docPageElement[0]));
  3714. }
  3715.  
  3716. urlChanged() {
  3717. urlChanged = true;
  3718. this.clearAddedElements();
  3719. }
  3720.  
  3721. initPage(callback) {
  3722. let self = this;
  3723. if (self.initing) return;
  3724. self.initing = true;
  3725. setTimeout(() => {
  3726. self.initing = false;
  3727. }, 100);
  3728. curPage = 1;
  3729. urlChanged = false;
  3730. tryTimes = 0;
  3731. this.clearAddedElements();
  3732. this.insert = null;
  3733. this.visibilityItems = [];
  3734. this.visibleIndex = -1;
  3735. this.pageDoc = document;
  3736. this.nextLinkHref = null;
  3737. this.curUrl = location.href;
  3738. this.oldUrl = "";
  3739. this.initUrl = location.href;
  3740. this.historyUrl = "";
  3741. this.possibleCheck = 0;
  3742. let base = document.querySelector("base");
  3743. this.basePath = (base && base.href) || location.href;
  3744. this.getRule(async () => {
  3745. if (self.curSiteRule.sideController === true || (self.curSiteRule.sideController !== false && rulesData.sideController)) {
  3746. isPause = manualPause;
  3747. }
  3748. if (typeof(self.curSiteRule.rate) !== "undefined") {
  3749. rate = self.curSiteRule.rate;
  3750. }
  3751. if (self.curSiteRule.enable == 0) {
  3752. debug("Stop as rule disable");
  3753. isPause = true;
  3754. _GM_registerMenuCommand(i18n("enable"), () => {
  3755. showTips(i18n("enableSiteTips"));
  3756. if(!self.customRules) {
  3757. self.customRules = [];
  3758. }
  3759. for (let i in self.customRules) {
  3760. if (self.customRules[i].url == self.curSiteRule.url) {
  3761. self.customRules.splice(i, 1);
  3762. break;
  3763. }
  3764. }
  3765. self.curSiteRule.enable = 1;
  3766. self.customRules.unshift(self.curSiteRule);
  3767. storage.setItem("customRules", self.customRules);
  3768. location.reload();
  3769. });
  3770. return;
  3771. }
  3772. if (rulesData.sideControllerAlways) {
  3773. sideController.setup();
  3774. }
  3775. //若是再亂匹配就不緩存wedata,或者只在找完本地規則之後再考慮wedata的緩存
  3776. if (self.curSiteRule.smart) {
  3777. delete self.curSiteRule.pageElement;
  3778. if (!self.possibleRule) {
  3779. self.smartRules = self.smartRules.filter(item => {return item && item.url != self.curSiteRule.url});
  3780. self.smartRules.unshift(self.curSiteRule);
  3781. if (self.smartRules.length > 100) {
  3782. self.smartRules.pop();
  3783. }
  3784. storage.setItem("smartRules", self.smartRules);
  3785. }
  3786. } else if (self.curSiteRule && self.curSiteRule.url.length > 13) {
  3787. self.addToHpRules();
  3788. }
  3789. let css = self.curSiteRule.css || rulesData.customCss;
  3790. if (css) {
  3791. let cssArr = css.split("inIframe:");
  3792. if (cssArr && cssArr.length) {
  3793. _GM_addStyle(cssArr[0]);
  3794. }
  3795. }
  3796. if (/sidesearch=(1|true)$/.test(self.curUrl)) {
  3797. openInNewTab = 0;
  3798. } else if (typeof self.curSiteRule.openInNewTab !== 'undefined') {
  3799. openInNewTab = self.curSiteRule.openInNewTab ? 1 : 2;
  3800. }
  3801. let autoClick = self.curSiteRule.autoClick;
  3802. if (autoClick) {
  3803. let autoClickBtn;
  3804. autoClickBtn = getElement(autoClick, document, null, true);
  3805. if (autoClickBtn) {
  3806. emuClick(autoClickBtn);
  3807. }
  3808. }
  3809. let code = self.curSiteRule.init;
  3810. if (code) {
  3811. try {
  3812. await ((typeof code == 'function') ? code : new AsyncFunction('doc', 'win', 'iframe', 'click', 'enter', 'input', 'sleep', '"use strict";' + code))(null, null, null, async sel => {await clickAction(sel, document)}, async sel => {await enterAction(sel, document)}, async (sel, v) =>{await inputAction(sel, v, document)}, async time => {await sleep(time)});
  3813. } catch(e) {
  3814. debug(e);
  3815. }
  3816. }
  3817. await self.getNextLink(document, true);
  3818. if (self.curSiteRule.pageNum && self.nextLinkHref && self.nextLinkHref != "#") {
  3819. let num1st = self.getPageNumFromUrl(location.href, 1);
  3820. let num2nd = self.getPageNumFromUrl(self.nextLinkHref, 1);
  3821. if (num2nd != num1st + 1) {
  3822. self.curSiteRule.pageNum = null;
  3823. }
  3824. }
  3825. if (self.curSiteRule.smart && self.nextLinkHref == false && self.possibleRule) {
  3826. let urlReg = new RegExp(self.possibleRule.url, "i");
  3827. function checkPossible () {
  3828. if (self.possibleCheck++ < 3) {
  3829. setTimeout(() => {
  3830. if (self.curSiteRule.smart) {
  3831. var href = location.href.slice(0, 500);
  3832. if (urlReg.test(href) && self.ruleMatch(self.possibleRule)) {
  3833. self.initPage(() => {});
  3834. } else checkPossible();
  3835. }
  3836. }, 3000);
  3837. }
  3838. }
  3839. checkPossible();
  3840. }
  3841. self.refreshByClick();
  3842. if (emuIframe && emuIframe.parentNode) {
  3843. emuIframe.parentNode.removeChild(emuIframe);
  3844. emuIframe = null;
  3845. }
  3846.  
  3847. let pageElementCss = self.curSiteRule.pageElementCss || rulesData.pageElementCss;
  3848. if (pageElementCss && pageElementCss !== '0') {
  3849. self.getPageElement(document, _unsafeWindow);
  3850. }
  3851. callback();
  3852. let initRun = typeof self.curSiteRule.initRun == 'undefined' ? rulesData.initRun : self.curSiteRule.initRun;
  3853. if (self.nextLinkHref) {
  3854. sideController.setup();
  3855. if (initRun && initRun != false) {
  3856. setTimeout(() => {
  3857. nextPage();
  3858. }, 300);
  3859. }
  3860. }
  3861. });
  3862. }
  3863.  
  3864. async hookUrlSetEle(ele, doc) {
  3865. let self = this;
  3866. return new Promise((resolve) => {
  3867. let catchUrl = e => {
  3868. ele.dataset.url = self.catchedUrl;
  3869. ele.setAttribute('onclick', 'window.open(this.dataset.url)');
  3870. window.removeEventListener('pagetual_openUrl', catchUrl);
  3871. resolve();
  3872. };
  3873. window.addEventListener('pagetual_openUrl', catchUrl);
  3874. emuClick(ele, doc);
  3875. });
  3876. }
  3877.  
  3878. async hookUrl(doc) {
  3879. let sel = this.curSiteRule.hookUrl;
  3880. if (!sel) return;
  3881. let self = this;
  3882. if (!this.initHook) {
  3883. this.initHook = true;
  3884. Object.defineProperty(doc.defaultView, 'open', {
  3885. get: function () {
  3886. return (s) => {
  3887. self.catchedUrl = s;
  3888. var e = new CustomEvent('pagetual_openUrl');
  3889. window.dispatchEvent(e);
  3890. }
  3891. }
  3892. });
  3893. }
  3894. let eles = getAllElements(sel, doc);
  3895. for (let i = 0; i < eles.length; i++) {
  3896. await sleep(1);
  3897. let ele = eles[i];
  3898. if (!ele.dataset.url) {
  3899. await this.hookUrlSetEle(ele, doc);
  3900. }
  3901. }
  3902. }
  3903.  
  3904. beginLoading() {
  3905. isLoading = true;
  3906. if (targetY >= 0) {
  3907. window.scrollTo({ top: targetY, behavior: 'instant'});
  3908. targetY = -1;
  3909. }
  3910. let lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3911. ruleParser.insertElement(loadingDiv);
  3912. if (forceState == 2) {
  3913. getBody(document).appendChild(loadingDiv);
  3914. } else {
  3915. let parent = loadingDiv.parentNode;
  3916. if (compareNodeName(parent, ["tbody"])) {
  3917. parent = parent.parentNode;
  3918. }
  3919. if (compareNodeName(parent, ["table"])) {
  3920. parent.parentNode.appendChild(loadingDiv);
  3921. }
  3922. }
  3923. getBody(document).scrollTop = lastScrollTop;
  3924. document.documentElement.scrollTop = lastScrollTop;
  3925. }
  3926.  
  3927. insertElement(ele) {
  3928. if (!this.insert || !this.insert.parentNode) {
  3929. this.getInsert();
  3930. }
  3931. if (this.insert && this.insert.parentNode) {
  3932. let self = this;
  3933. if (ele.nodeName == "#document-fragment") {
  3934. [].forEach.call(ele.children, el => {
  3935. self.addedElePool.push(el);
  3936. });
  3937. } else {
  3938. this.addedElePool.push(ele);
  3939. }
  3940. if (this.curSiteRule.insertPos == 2 || this.curSiteRule.insertPos == "in") {
  3941. this.insert.appendChild(ele);
  3942. } else {
  3943. this.insert.parentNode.insertBefore(ele, this.insert);
  3944. }
  3945. }
  3946. }
  3947.  
  3948. noValidContent(url) {
  3949. if (!this.curSiteRule.nextLinkByUrl) showTips(i18n("noValidContent"), url);
  3950. }
  3951.  
  3952. async insertPage(doc, eles, url, callback, tried) {
  3953. this.oldUrl = this.curUrl;
  3954. let oldTitle = document.title;
  3955. try {
  3956. let oldTitle = this.pageDoc.title;
  3957. } catch (e) {}
  3958. this.pageDoc = doc;
  3959. this.curUrl = url;
  3960. isLoading = true;
  3961. let nextLink = await this.getNextLink(doc);
  3962. this.nextTitle = "";
  3963. if (this.curSiteRule.pageBarText) {
  3964. if (this.curSiteRule.pageBarText == 1 || this.curSiteRule.pageBarText == true) {
  3965. this.nextTitle = doc.title;
  3966. } else {
  3967. try {
  3968. this.nextTitle = ((typeof this.curSiteRule.pageBarText == 'function') ? this.curSiteRule.pageBarText : Function("doc",'"use strict";' + this.curSiteRule.pageBarText))(doc);
  3969. } catch(e) {
  3970. debug(e);
  3971. }
  3972. }
  3973. }
  3974. if (curPage == 1 && !tried && !nextLink && this.curSiteRule.smart && this.curSiteRule.pageElement && this.curSiteRule.action != 0) {
  3975. this.curSiteRule.action = 1;
  3976. this.curUrl = location.href;
  3977. isLoading = false;
  3978. return false;
  3979. }
  3980.  
  3981. if (targetY >= 0) {
  3982. window.scrollTo({ top: targetY, behavior: 'instant'});
  3983. targetY = -1;
  3984. }
  3985. let lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3986. this.getInsert();
  3987. await this.pageInit(doc, eles);
  3988. var self = this, newEles = [];
  3989. if (!eles || eles.length == 0 || !self.insert || !self.insert.parentNode) {
  3990. if (callback) callback(eles);
  3991. loadPageOver();
  3992. } else {
  3993. if (callback) callback(eles);
  3994. loadPageOver();
  3995. const collection = document.createDocumentFragment();
  3996. [].forEach.call(eles, ele => {
  3997. let newEle = ele.cloneNode(true);
  3998. let oldCanvass = ele.querySelectorAll("canvas");
  3999. let newCanvass = newEle.querySelectorAll("canvas");
  4000. if (self.updateUrl) {
  4001. [].forEach.call(newEle.querySelectorAll("img"), img => {
  4002. if (img.getAttribute("src")) img.src = self.canonicalUri(img.getAttribute("src"));
  4003. });
  4004. [].forEach.call(newEle.querySelectorAll("a"), a => {
  4005. if (a.getAttribute("href")) a.href = self.canonicalUri(a.getAttribute("href"));
  4006. });
  4007. }
  4008. for (let i = 0; i < oldCanvass.length; i++) {
  4009. let oldCanvas = oldCanvass[i];
  4010. let newCanvas = newCanvass[i];
  4011. newCanvas.getContext('2d').drawImage(oldCanvas, 0, 0);
  4012. }
  4013. if (!compareNodeName(newEle, ["style", "script"])) self.visibilityItems.push(newEle);
  4014. collection.appendChild(newEle)
  4015. newEles.push(newEle);
  4016. });
  4017. self.insertElement(collection);
  4018. }
  4019. getBody(document).scrollTop = lastScrollTop;
  4020. document.documentElement.scrollTop = lastScrollTop;
  4021. this.pageAction(doc, newEles);
  4022. let enableHistory = this.curSiteRule.history;
  4023. let enableHistoryAfterInsert = false;
  4024. if (enableHistory == 1) {
  4025. enableHistory = true;
  4026. } else if (enableHistory == 2) {
  4027. enableHistory = true;
  4028. enableHistoryAfterInsert = true;
  4029. } else if (enableHistory == 0) {
  4030. enableHistory = false;
  4031. } else {
  4032. enableHistory = rulesData.enableHistory;
  4033. enableHistoryAfterInsert = rulesData.enableHistoryAfterInsert;
  4034. }
  4035. if (enableHistory) {
  4036. this.historyUrl = enableHistoryAfterInsert ? this.curUrl : this.oldUrl;
  4037. if(this.historyUrl != location.href) {
  4038. let isJs = this.hrefIsJs(this.historyUrl);
  4039. if (!isJs) {
  4040. let historyTitle = enableHistoryAfterInsert ? doc.title : oldTitle;
  4041. _unsafeWindow.history.replaceState(undefined, historyTitle, this.historyUrl);
  4042. document.title = historyTitle;
  4043. }
  4044. }
  4045. }
  4046. isLoading = false;
  4047. _unsafeWindow.postMessage({
  4048. action: "insert",
  4049. command: 'pagetual'
  4050. }, '*');
  4051. return true;
  4052. }
  4053. }
  4054. var ruleParser = new RuleParser();
  4055.  
  4056. class SideController {
  4057. //static controller;
  4058. constructor() {
  4059. this.inited = false;
  4060. }
  4061.  
  4062. /*static getInstance() {
  4063. if (!SideController.controller) {
  4064. SideController.controller = new SideController();
  4065. }
  4066. return SideController.controller;
  4067. }*/
  4068.  
  4069. setup() {
  4070. if (ruleParser.curSiteRule.sideController === false) return;
  4071. if (!rulesData.sideController && !ruleParser.curSiteRule.sideController) return;
  4072. this.addToStage();
  4073. }
  4074.  
  4075. init() {
  4076. if (this.inited) return;
  4077. this.inited = true;
  4078. let self = this;
  4079. this.cssText = `
  4080. #pagetual-sideController {
  4081. position: fixed;
  4082. top: calc(50% - 83px);
  4083. left: calc(99% - 40px);
  4084. width: 40px;
  4085. border-radius: 20px;
  4086. box-shadow: rgb(0 0 0) 0px 0px 10px;
  4087. text-align: center;
  4088. background: #ffffffd0!important;
  4089. user-select: none;
  4090. z-index: 2147483646!important;
  4091. padding: 0!important;
  4092. opacity: 0.35;
  4093. transition: opacity .5s ease, background .5s, box-shadow .5s;
  4094. }
  4095. #pagetual-sideController * {
  4096. font-weight: bold;
  4097. font-family: arial;
  4098. font-style: normal;
  4099. font-size: 20px!important;
  4100. color: black!important;
  4101. line-height: normal;
  4102. float: none;
  4103. text-align: center;
  4104. }
  4105. #pagetual-sideController.stop {
  4106. -webkit-filter: invert(100%);
  4107. filter: invert(100%);
  4108. }
  4109. .pagetual-sideController-btn {
  4110. padding: 5px 0;
  4111. cursor: pointer;
  4112. transition: transform .15s ease-in-out, opacity .3s ease;
  4113. }
  4114. #pagetual-sideController .pagetual-sideController-btn:hover {
  4115. transform: scale(1.5);
  4116. color: red!important;
  4117. }
  4118. #pagetual-sideController #pagetual-sideController-move > svg {
  4119. transition: transform .3s ease;
  4120. }
  4121. #pagetual-sideController #pagetual-sideController-move > svg:hover {
  4122. transform: scale(1.2);
  4123. }
  4124. #pagetual-sideController.minSize #pagetual-sideController-move > svg {
  4125. background: white;
  4126. opacity: 0;
  4127. }
  4128. #pagetual-sideController #pagetual-sideController-move > img,
  4129. #pagetual-sideController #pagetual-sideController-move > span {
  4130. width: 35px;
  4131. height: 35px;
  4132. cursor: pointer;
  4133. }
  4134. #pagetual-sideController.minSize #pagetual-sideController-move > img,
  4135. #pagetual-sideController.minSize #pagetual-sideController-move > span {
  4136. border-radius: 50px;
  4137. text-shadow: rgb(255 255 255) 0px 0px 10px;
  4138. }
  4139. #pagetual-sideController #pagetual-sideController-pagenum {
  4140. font-size: 15px!important;
  4141. line-height: 30px;
  4142. text-align: center;
  4143. position: absolute;
  4144. right: calc(50% - 15px);
  4145. top: calc(50% - 15px);
  4146. border: 1px solid #00000099;
  4147. display: inline-block;
  4148. width: 30px;
  4149. height: 30px;
  4150. box-sizing: border-box;
  4151. border-radius: 50%;
  4152. background: white;
  4153. opacity: 0;
  4154. transition: opacity .5s ease;
  4155. pointer-events: none;
  4156. }
  4157. #pagetual-sideController.minSize #pagetual-sideController-pagenum {
  4158. opacity: 0.8;
  4159. }
  4160. #pagetual-sideController:hover {
  4161. opacity: 1;
  4162. }
  4163. #pagetual-sideController>.extra {
  4164. bottom: 170px;
  4165. left: 0px;
  4166. width: 40px;
  4167. position: absolute;
  4168. }
  4169. #pagetual-sideController>.extra>svg {
  4170. width: 40px;
  4171. height: 30px;
  4172. opacity: 0.1;
  4173. cursor: pointer;
  4174. margin: 0 0 5px 0;
  4175. transition: opacity .3s ease;
  4176. }
  4177. #pagetual-sideController.minSize>.extra>svg {
  4178. opacity: 0;
  4179. }
  4180. #pagetual-sideController>.extra>svg:hover {
  4181. opacity: 1;
  4182. }
  4183. #pagetual-sideController.minSize {
  4184. box-shadow: rgb(0 0 0 / 0%) 0px 0px 0px;
  4185. background: #00000000!important;
  4186. pointer-events: none;
  4187. }
  4188. #pagetual-sideController.minSize #pagetual-sideController-move {
  4189. pointer-events: all;
  4190. }
  4191. #pagetual-sideController.minSize .pagetual-sideController-btn {
  4192. opacity: 0;
  4193. }
  4194. `;
  4195. let frame = document.createElement("div");
  4196. frame.id = "pagetual-sideController";
  4197. frame.innerHTML = createHTML(`
  4198. <div class="extra">
  4199. <svg id="loadNow" class="pagetual" viewBox="0 0 1030 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><title>${i18n("loadNow")}</title><path d="M712.106667 525.653333l-291.413334 247.893334a21.333333 21.333333 0 0 1-14.506666 5.546666 20.053333 20.053333 0 0 1-22.186667-19.2V264.106667a20.053333 20.053333 0 0 1 20.906667-19.2 20.906667 20.906667 0 0 1 14.506666 5.546666l291.413334 247.893334a17.92 17.92 0 0 1 1.28 27.306666zM512 0a512 512 0 1 0 512 512A512 512 0 0 0 512 0z" fill="#5E5C5C"></path></svg>
  4200. <svg id="scroll" class="pagetual" viewBox="0 0 1030 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><title>${i18n("sideControllerScroll")}</title><path d="M912 544v82.64C912 846.096 732.912 1024 512 1024S112 846.096 112 626.64V544h800z" fill="#5E5C5C"></path><path d="M478.656 0v43.328a96 96 0 0 1-32.48 71.952c-27.68 24.448-41.968 48.128-42.896 71.04l-0.096 4.352v104c0 24.224 14.512 49.344 43.52 75.312a96 96 0 0 1 31.952 71.52V496H112.032L112 393.712C112 181.648 264.848 8.72 472.352 0.208L478.656 0z" fill="#999999"></path><path d="M534.24 0C747.584 5.232 912 179.504 912 393.728v102.256L534.208 496v-52.912a96 96 0 0 1 33.536-72.88c28.48-24.416 43.2-48.16 44.16-71.2l0.096-4.336v-104c0-24.352-14.928-49.52-44.784-75.488a96 96 0 0 1-33.008-72.432V0z" fill="#5E5C5C"></path></svg>
  4201. </div>
  4202. <div id="pagetual-sideController-top" class="pagetual-sideController-btn">⊼</div>
  4203. <div>
  4204. <div id="pagetual-sideController-pre" class="pagetual-sideController-btn">∧</div>
  4205. <div id="pagetual-sideController-move"><svg class="pagetual" width="30" height="30" style="border-radius: 15px;display: initial;position: relative;cursor: pointer;margin: 0;width: 30px;height: 30px;vertical-align: middle;fill: currentColor;overflow: hidden;" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M296 440c-44.1 0-80 35.9-80 80s35.9 80 80 80 80-35.9 80-80-35.9-80-80-80z" fill="#604b4a"></path><path d="M960 512c0-247-201-448-448-448S64 265 64 512c0 1.8 0.1 3.5 0.1 5.3 0 0.9-0.1 1.8-0.1 2.7h0.2C68.5 763.3 267.7 960 512 960c236.2 0 430.1-183.7 446.7-415.7 0.1-0.8 0.1-1.6 0.2-2.3 0.4-4.6 0.5-9.3 0.7-13.9 0.1-2.7 0.4-5.3 0.4-8h-0.2c0-2.8 0.2-5.4 0.2-8.1z m-152 8c0 44.1-35.9 80-80 80s-80-35.9-80-80 35.9-80 80-80 80 35.9 80 80zM512 928C284.4 928 99 744.3 96.1 517.3 97.6 408.3 186.6 320 296 320c110.3 0 200 89.7 200 200 0 127.9 104.1 232 232 232 62.9 0 119.9-25.2 161.7-66-66 142.7-210.4 242-377.7 242z" fill="#604b4a"></path></svg><div id="pagetual-sideController-pagenum"></div></div>
  4206. <div id="pagetual-sideController-next" class="pagetual-sideController-btn">∨</div>
  4207. </div>
  4208. <div id="pagetual-sideController-bottom" class="pagetual-sideController-btn">⊻</div>
  4209. `);
  4210. frame.classList.add("stop");
  4211. let top = frame.querySelector("#pagetual-sideController-top");
  4212. let pre = frame.querySelector("#pagetual-sideController-pre");
  4213. let move = frame.querySelector("#pagetual-sideController-move");
  4214. let next = frame.querySelector("#pagetual-sideController-next");
  4215. let bottom = frame.querySelector("#pagetual-sideController-bottom");
  4216. let pagenum = frame.querySelector("#pagetual-sideController-pagenum");
  4217. let scroll = frame.querySelector("#scroll");
  4218. let loadNow = frame.querySelector("#loadNow");
  4219. if (rulesData.sideControllerScroll === false) {
  4220. scroll.style.display = "none";
  4221. }
  4222. if (rulesData.sideControllerLoadNow === false) {
  4223. loadNow.style.display = "none";
  4224. }
  4225. if (sideControllerIcon) move.innerHTML = sideControllerIcon;
  4226.  
  4227. frame.addEventListener("dblclick", e => {
  4228. e.preventDefault();
  4229. e.stopPropagation();
  4230. });
  4231.  
  4232. frame.addEventListener("mouseenter", e => {
  4233. clearTimeout(self.hideTimer);
  4234. frame.classList.remove("minSize");
  4235. });
  4236.  
  4237. frame.addEventListener("mouseleave", e => {
  4238. clearTimeout(self.hideTimer);
  4239. self.hideTimer = setTimeout(() => {
  4240. frame.classList.add("minSize");
  4241. }, 800);
  4242. });
  4243.  
  4244. document.body.addEventListener('touchstart', e => {
  4245. if (e.target === frame || frame.contains(e.target)) {
  4246. frame.classList.remove("minSize");
  4247. } else {
  4248. frame.classList.add("minSize");
  4249. }
  4250. });
  4251.  
  4252. scroll.addEventListener("click", e => {
  4253. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  4254. autoScroll = parseInt(autoScroll) || 0;
  4255. if (autoScroll < 0) autoScroll = 0;
  4256. if (autoScroll && autoScroll != autoScrollRate) {
  4257. autoScrollRate = autoScroll;
  4258. storage.setItem("autoScrollRate", autoScrollRate);
  4259. }
  4260. setListData("autoScroll", location.host + location.pathname, autoScroll);
  4261. startAutoScroll();
  4262. }, true);
  4263.  
  4264. loadNow.addEventListener("click", e => {
  4265. if (autoLoadNum != -1) {
  4266. autoLoadNum = -1;
  4267. return;
  4268. }
  4269. let loadNum = window.prompt(i18n("loadConfirm"), loadNowNum);
  4270. if (loadNum === "" || loadNum === null) return;
  4271. loadNum = Math.abs(parseInt(loadNum)) || 0;
  4272. if (loadNowNum != loadNum) {
  4273. loadNowNum = loadNum;
  4274. storage.setItem("loadNowNum", loadNowNum);
  4275. }
  4276. autoLoadNum = loadNum;
  4277. nextPage();
  4278. }, true);
  4279.  
  4280. pre.addEventListener("click", e => {
  4281. let prePageBar = getPageBar().preBar;
  4282. if (prePageBar) {
  4283. scrollToPageBar(prePageBar);
  4284. } else {
  4285. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  4286. targetY = scrollTop - (window.innerHeight || document.documentElement.clientHeight);
  4287. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4288. }
  4289. }, true);
  4290.  
  4291. next.addEventListener("click", e => {
  4292. let pageBarObj = getPageBar();
  4293. let nextPageBar = pageBarObj.nextBar;
  4294. if (nextPageBar) {
  4295. scrollToPageBar(nextPageBar);
  4296. } else {
  4297. if (pageBarObj.preBar) {
  4298. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  4299. targetY = scrollH || 9999999;
  4300. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4301. } else {
  4302. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  4303. targetY = scrollTop + (window.innerHeight || document.documentElement.clientHeight);
  4304. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4305. }
  4306. }
  4307. }, true);
  4308.  
  4309. top.addEventListener("click", e => {
  4310. getBody(document).scrollTop=0;
  4311. document.documentElement.scrollTop=0;
  4312. e.preventDefault();
  4313. e.stopPropagation();
  4314. }, true);
  4315.  
  4316. bottom.addEventListener("click", e => {
  4317. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  4318. changeStop(true, true);
  4319. }
  4320. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  4321. getBody(document).scrollTop = scrollH || 9999999;
  4322. document.documentElement.scrollTop = scrollH || 9999999;
  4323. e.preventDefault();
  4324. e.stopPropagation();
  4325. }, true);
  4326.  
  4327. let initX, initY, moving = false;
  4328. let removeTimer;
  4329. move.addEventListener("click", e => {
  4330. if (!moving) {
  4331. changeStop(!isPause, true);
  4332. }
  4333. }, true);
  4334. move.addEventListener("dblclick", e => {
  4335. clearTimeout(removeTimer);
  4336. document.removeEventListener("mousemove", mouseMoveHandler, true);
  4337. document.removeEventListener("mouseup", mouseUpHandler, true);
  4338. changeStop(!isPause, true);
  4339. if (isPause) {
  4340. ruleParser.hideAddedElements();
  4341. } else {
  4342. ruleParser.showAddedElements();
  4343. }
  4344. }, true);
  4345.  
  4346. move.oncontextmenu = e => {
  4347. e.preventDefault();
  4348. picker.start();
  4349. };
  4350.  
  4351. let clientX = e => {
  4352. if (e.type.indexOf('mouse') === 0) {
  4353. return e.clientX;
  4354. } else {
  4355. return e.changedTouches[0].clientX;
  4356. }
  4357. };
  4358.  
  4359. let clientY = e => {
  4360. if (e.type.indexOf('mouse') === 0) {
  4361. return e.clientY;
  4362. } else {
  4363. return e.changedTouches[0].clientY;
  4364. }
  4365. };
  4366.  
  4367. let mouseMoveHandler = e => {
  4368. if (moving) {
  4369. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  4370. let windowWidth = window.innerWidth || document.documentElement.clientWidth;
  4371. initX = (clientX(e) - 10 + 40) / windowWidth * 100;
  4372. initY = (clientY(e) - 83 + 83) / windowHeight * 100;
  4373. this.frame.style.top = `calc(${initY}% - 83px)`;
  4374. this.frame.style.left = `calc(${initX}% - 40px)`;
  4375. } else if (Math.abs(clientX(e) - initX) + Math.abs(clientY(e) - initY) > 20) {
  4376. moving = true;
  4377. clearTimeout(removeTimer);
  4378. }
  4379. };
  4380. let mouseUpHandler = e => {
  4381. clearTimeout(removeTimer);
  4382. document.removeEventListener("mousemove", mouseMoveHandler, true);
  4383. document.removeEventListener("mouseup", mouseUpHandler, true);
  4384. document.removeEventListener("touchmove", mouseMoveHandler, true);
  4385. document.removeEventListener("touchend", mouseUpHandler, true);
  4386. if (moving) {
  4387. rulesData.sideControllerPos = {x: parseInt(initX), y: parseInt(initY)};
  4388. storage.setItem("rulesData", rulesData);
  4389. }
  4390. };
  4391. let mouseDownHandler = e => {
  4392. initX = clientX(e);
  4393. initY = clientY(e);
  4394. moving = false;
  4395. clearTimeout(removeTimer);
  4396. removeTimer = setTimeout(() => {
  4397. if (e.type === "touchstart") {
  4398. picker.start();
  4399. } else {
  4400. self.remove();
  4401. }
  4402. }, 1500);
  4403. document.addEventListener("mousemove", mouseMoveHandler, true);
  4404. document.addEventListener("mouseup", mouseUpHandler, true);
  4405. document.addEventListener("touchmove", mouseMoveHandler, true);
  4406. document.addEventListener("touchend", mouseUpHandler, true);
  4407. e.stopPropagation();
  4408. e.preventDefault();
  4409. };
  4410.  
  4411. move.addEventListener("mousedown", mouseDownHandler, true);
  4412. move.addEventListener("touchstart", mouseDownHandler, { passive: false, capture: true });
  4413.  
  4414. this.frame = frame;
  4415. this.pagenum = pagenum;
  4416. if (rulesData.sideControllerPos) {
  4417. this.frame.style.top = `calc(${rulesData.sideControllerPos.y}% - 83px)`;
  4418. this.frame.style.left = `calc(${rulesData.sideControllerPos.x}% - 40px)`;
  4419. }
  4420. }
  4421.  
  4422. addToStage() {
  4423. this.init();
  4424. if (!this.styleEle || !this.styleEle.parentNode) {
  4425. this.styleEle = _GM_addStyle(this.cssText);
  4426. }
  4427. if (!isPause) {
  4428. this.frame.classList.remove("stop");
  4429. }
  4430. this.pagenum.innerHTML = createHTML(curPage);
  4431. this.frame.title = i18n("page") + curPage;
  4432. if (this.frame.parentNode) return;
  4433. getBody(document).appendChild(this.frame);
  4434. clearTimeout(this.hideTimer);
  4435. this.frame.classList.add("minSize");
  4436. }
  4437.  
  4438. remove() {
  4439. if (this.frame && this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  4440. }
  4441. }
  4442. const sideController = new SideController();
  4443.  
  4444. class NextSwitch {
  4445. //static nextSwitch;
  4446. constructor() {
  4447. this.inited = false;
  4448. }
  4449.  
  4450. /*static getInstance() {
  4451. if (!NextSwitch.nextSwitch) {
  4452. NextSwitch.nextSwitch = new NextSwitch();
  4453. }
  4454. return NextSwitch.nextSwitch;
  4455. }*/
  4456.  
  4457. init() {
  4458. if (this.inited) return;
  4459. this.inited = true;
  4460. let self = this;
  4461. this.cssText = `
  4462. #pagetual-nextSwitch {
  4463. position: fixed;
  4464. top: 10px;
  4465. left: calc(50% - 160px);
  4466. background: aliceblue;
  4467. padding: 10px;
  4468. border-radius: 5px;
  4469. text-align: center;
  4470. opacity: 0.95;
  4471. color: #161616;
  4472. z-index: 2147483647;
  4473. font-size: 16px;
  4474. box-shadow: rgb(0 0 0) 0px 0px 10px;
  4475. }
  4476. #pagetual-nextSwitch>.title {
  4477. margin: -5px 45px 10px 45px;
  4478. font-size: 20px;
  4479. font-weight: bold;
  4480. border-bottom: 1px solid black;
  4481. user-select: none;
  4482. color: orangered;
  4483. }
  4484. #pagetual-nextSwitch>.group {
  4485. display: flex;
  4486. flex-direction: column;
  4487. }
  4488. #pagetual-nextSwitch>.group>span {
  4489. color: #161616;
  4490. cursor: pointer;
  4491. margin: 3px;
  4492. font-size: larger;
  4493. }
  4494. #pagetual-nextSwitch>.group>span:hover {
  4495. color: red;
  4496. }
  4497. #pagetual-nextSwitch>.group>span.current {
  4498. border: 2px dotted red;
  4499. border-radius: 10px;
  4500. }
  4501. #pagetual-nextSwitch>.closeSwitch {
  4502. position: absolute;
  4503. top: 3px;
  4504. right: 10px;
  4505. background: none;
  4506. border: none;
  4507. vertical-align: top;
  4508. transition: transform .15s ease-in-out;
  4509. float: right;
  4510. cursor: pointer;
  4511. }
  4512. #pagetual-nextSwitch svg {
  4513. width: 30px;
  4514. height: 30px;
  4515. vertical-align: middle;
  4516. fill: #161616;
  4517. overflow: hidden;
  4518. }
  4519. #pagetual-nextSwitch button:hover {
  4520. transform: scale(1.2);
  4521. }
  4522. `;
  4523. let frame = document.createElement("div");
  4524. frame.id = "pagetual-nextSwitch";
  4525. frame.innerHTML = createHTML(`
  4526. <div class="title">${i18n("nextSwitch")}</div>
  4527. <button type="button" class="closeSwitch">
  4528. <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2754">
  4529. <path d="M512 128c212 0 384 172 384 384s-172 384-384 384-384-172-384-384 172-384 384-384m0-64C264.8 64 64 264.8 64 512s200.8 448 448 448 448-200.8 448-448S759.2 64 512 64z m238.4 254.4l-45.6-45.6L512 467.2 318.4 273.6l-45.6 45.6L467.2 512 273.6 705.6l45.6 45.6L512 557.6l193.6 193.6 45.6-45.6L557.6 512l192.8-193.6z" p-id="2755">
  4530. </path>
  4531. </svg>
  4532. </button>
  4533. <div class="group"></div>
  4534. `);
  4535. let group = frame.querySelector(".group");
  4536. let closeBtn = frame.querySelector(".closeSwitch");
  4537. closeBtn.addEventListener("click", e => {
  4538. self.close();
  4539. }, true);
  4540. this.frame = frame;
  4541. let currentSpan;
  4542. ruleParser.curSiteRule.nextLink.forEach((link, i) => {
  4543. let span = document.createElement("span");
  4544. let target = getElement(link, document);
  4545. let index = "<b>" + (i + 1) + "</b>: ";
  4546. if (target) {
  4547. let targetInner = target.innerText.trim();
  4548. span.innerHTML = index + (targetInner || link);
  4549. } else {
  4550. span.innerHTML = index + "Not Found";
  4551. }
  4552. span.title = link;
  4553. span.addEventListener("click", e => {
  4554. if (currentSpan) currentSpan.classList.remove("current");
  4555. span.classList.add("current");
  4556. currentSpan = span;
  4557. nextIndex = i;
  4558. setListData("nextSwitch", location.host, nextIndex === 0 ? "" : nextIndex);
  4559. ruleParser.curUrl += "#pagetual";
  4560. ruleParser.oldUrl = ruleParser.curUrl;
  4561. autoLoadNum = -1;
  4562. if (!ruleParser.nextLinkHref) {
  4563. isLoading = false;
  4564. }
  4565. ruleParser.getNextLink(ruleParser.pageDoc || document);
  4566. self.close();
  4567. }, true);
  4568. if (i == nextIndex) {
  4569. span.classList.add("current");
  4570. currentSpan = span;
  4571. }
  4572. group.appendChild(span);
  4573. });
  4574. }
  4575.  
  4576. start() {
  4577. this.init();
  4578. if (!this.styleEle || !this.styleEle.parentNode) {
  4579. this.styleEle = _GM_addStyle(this.cssText);
  4580. }
  4581. document.documentElement.appendChild(this.frame);
  4582. }
  4583.  
  4584. close() {
  4585. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  4586. }
  4587. }
  4588. const nextSwitch = new NextSwitch();
  4589.  
  4590. class Picker {
  4591. //static picker;
  4592. constructor() {
  4593. this.inited = false;
  4594. }
  4595.  
  4596. /*static getInstance() {
  4597. if (!Picker.picker) {
  4598. Picker.picker = new Picker();
  4599. }
  4600. return Picker.picker;
  4601. }*/
  4602.  
  4603. init() {
  4604. if (this.inited) return;
  4605. this.inited = true;
  4606. let self = this;
  4607. this.signList = [];
  4608. this.cssText = `
  4609. body.pagetual-picker,
  4610. body.pagetual-picker *:hover,
  4611. body.pagetual-picker a:hover {
  4612. cursor: crosshair !important;
  4613. }
  4614. #pagetual-picker {
  4615. position: fixed;
  4616. top: 10px;
  4617. left: calc(50% - 178px);
  4618. background: aliceblue;
  4619. padding: 10px;
  4620. border-radius: 5px;
  4621. text-align: center;
  4622. opacity: 0.95;
  4623. color: #161616;
  4624. z-index: 2147483646;
  4625. font-size: 16px;
  4626. overflow: hidden;
  4627. box-shadow: rgb(0 0 0) 0px 0px 10px;
  4628. }
  4629. #pagetual-picker * {
  4630. margin: 0;
  4631. padding: 0;
  4632. font-family: Times New Roman;
  4633. overflow: initial;
  4634. user-select: none;
  4635. line-height: unset;
  4636. min-width: unset;
  4637. min-height: unset;
  4638. }
  4639. #pagetual-picker>.title {
  4640. margin: -5px 45px 10px 45px;
  4641. font-size: 20px;
  4642. font-weight: bold;
  4643. cursor: pointer;
  4644. border-bottom: 1px solid black;
  4645. user-select: none;
  4646. color: orangered;
  4647. height: initial;
  4648. width: initial;
  4649. position: initial;
  4650. transition: transform .3s ease;
  4651. }
  4652. #pagetual-picker>.title:hover {
  4653. transform: scale(1.1);
  4654. }
  4655. #pagetual-picker button {
  4656. background: none;
  4657. border: none;
  4658. vertical-align: top;
  4659. transition: transform .15s ease-in-out;
  4660. float: right;
  4661. cursor: pointer;
  4662. overflow: hidden;
  4663. background-color: unset!important;
  4664. }
  4665. #pagetual-picker button:hover {
  4666. transform: scale(1.2);
  4667. }
  4668. #pagetual-picker>.closePicker {
  4669. position: absolute;
  4670. top: 3px;
  4671. right: 10px;
  4672. }
  4673. #pagetual-picker>.logoIcon {
  4674. position: absolute;
  4675. top: 3px;
  4676. left: 10px;
  4677. }
  4678. #pagetual-picker>.logoIcon.showSign>svg>path {
  4679. fill: gray!important;
  4680. }
  4681. #pagetual-picker textarea{
  4682. display: inline-block;
  4683. width: calc(100% - 65px);
  4684. height: 20px;
  4685. min-width: 250px;
  4686. max-width: calc(65vw - 50px);
  4687. min-height: unset;
  4688. max-height: unset;
  4689. padding: 6px 12px;
  4690. font-size: 16px;
  4691. font-weight: 400;
  4692. line-height: 1.5;
  4693. color: #495057;
  4694. background-color: #fff;
  4695. background-clip: padding-box;
  4696. border: 1px solid #ced4da;
  4697. border-radius: 4px;
  4698. transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
  4699. box-sizing: content-box;
  4700. margin-right: 5px;
  4701. resize: both;
  4702. box-shadow: 0 1px 5px 1px #ddd;
  4703. overflow-wrap: anywhere;
  4704. }
  4705. #pagetual-picker textarea:focus {
  4706. color: black;
  4707. background-color: #fff;
  4708. border-color: #80bdff;
  4709. outline: 0;
  4710. box-shadow: 0 0 0 3.2px rgb(0 123 255 / 25%);
  4711. }
  4712. #pagetual-picker [type=checkbox],
  4713. #pagetual-picker [type=radio] {
  4714. line-height: 20px;
  4715. height: 25px;
  4716. width: 25px;
  4717. margin-left: 5px;
  4718. vertical-align: middle;
  4719. appearance: auto;
  4720. display: inline-block;
  4721. position: initial;
  4722. }
  4723. #pagetual-picker [type=checkbox]:after,
  4724. #pagetual-picker [type=radio]:after,
  4725. #pagetual-picker [type=checkbox]:before,
  4726. #pagetual-picker [type=radio]:before {
  4727. border: none;
  4728. background: none;
  4729. }
  4730. #pagetual-picker label {
  4731. font-size: 18px;
  4732. line-height: 25px;
  4733. vertical-align: middle;
  4734. display: inline-block;
  4735. color: black;
  4736. position: initial;
  4737. cursor: pointer;
  4738. }
  4739. #pagetual-picker .bottom {
  4740. text-align: left;
  4741. margin: 10px 0;
  4742. width: 100%;
  4743. }
  4744. #pagetual-picker .bottom>button {
  4745. float: right;
  4746. }
  4747. #pagetual-picker svg {
  4748. width: 30px;
  4749. height: 30px;
  4750. vertical-align: middle;
  4751. fill: #161616;
  4752. overflow: hidden;
  4753. }
  4754. #pagetual-picker svg * {
  4755. pointer-events: none;
  4756. }
  4757. #pagetual-picker .allpath {
  4758. font-size: 18px;
  4759. margin: 10px auto;
  4760. max-width: 330px;
  4761. word-break: break-all;
  4762. cursor: context-menu;
  4763. overflow: hidden;
  4764. max-height: 42px;
  4765. -moz-transition:max-height 1s ease-in;
  4766. -webkit-transition:max-height 1s ease-in;
  4767. transition:max-height 1s ease-in;
  4768. color: black;
  4769. }
  4770. #pagetual-picker .allpath:hover {
  4771. max-height: calc(100vh - 130px);
  4772. overflow: auto;
  4773. }
  4774. #pagetual-picker .allpath>span.path {
  4775. cursor: pointer;
  4776. }
  4777. #pagetual-picker .allpath>span.path:hover {
  4778. opacity: 0.6;
  4779. }
  4780. #pagetual-picker .allpath>span.path:hover,
  4781. #pagetual-picker .allpath>span.path.checked {
  4782. color: orangered;
  4783. }
  4784. #pagetual-picker .moreConfig {
  4785. display: flex;
  4786. justify-content: space-between;
  4787. border-top: 1px solid;
  4788. padding-top: 10px;
  4789. width: 100%;
  4790. }
  4791. #pagetual-picker .command {
  4792. width: 100%;
  4793. color: black!important;
  4794. text-align: center;
  4795. font-size: large;
  4796. margin-top: 10px;
  4797. box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.12);
  4798. border-radius: 5px;
  4799. }
  4800. #pagetual-picker .command:hover {
  4801. color: orangered;
  4802. }
  4803. #pagetual-picker #showDetail {
  4804. float: initial;
  4805. margin-top: 10px;
  4806. }
  4807. #pagetual-picker.showDetail #showDetail {
  4808. float: right;
  4809. }
  4810. #pagetual-picker #showDetail>svg {
  4811. -moz-transition:transform 0.3s ease;
  4812. -webkit-transition:transform 0.3s ease;
  4813. transition:transform 0.3 ease;
  4814. }
  4815. #pagetual-picker.showDetail #showDetail>svg {
  4816. transform: rotate(180deg);
  4817. }
  4818. #pagetual-picker .tempRule {
  4819. display: none;
  4820. margin-top: 10px;
  4821. height: 300px;
  4822. min-height: 150px;
  4823. }
  4824. #pagetual-picker.showDetail .tempRule {
  4825. display: inline-block;
  4826. word-break: break-all;
  4827. }
  4828. #pagetual-picker #saveDetail {
  4829. display: none;
  4830. position: absolute;
  4831. bottom: 10px;
  4832. right: 8px;
  4833. }
  4834. #pagetual-picker.showDetail #saveDetail {
  4835. display: inline-block;
  4836. }
  4837. #pagetual-picker #saveDetail svg {
  4838. width: 35px;
  4839. height: 35px;
  4840. }
  4841. #pagetual-picker .addProp {
  4842. display: none;
  4843. flex-direction: column;
  4844. position: absolute;
  4845. bottom: 45px;
  4846. right: 12px;
  4847. }
  4848. #pagetual-picker.showDetail .addProp {
  4849. display: flex;
  4850. }
  4851. #pagetual-picker .addProp>button {
  4852. font-size: 30px;
  4853. font-family: Arial,sans-serif;
  4854. line-height: 35px;
  4855. color: #161616;
  4856. }
  4857. #pagetual-picker #edit{
  4858. -webkit-animation: jumpAnimation .6s 5;
  4859. animation: jumpAnimation .6s 5;
  4860. }
  4861. @keyframes jumpAnimation {
  4862. 0% {
  4863. transform: scale(1) translateY(0);
  4864. animation-timing-function: ease-out;
  4865. }
  4866. 50% {
  4867. transform: scale(1.2) translateY(-5px);
  4868. animation-timing-function: ease-in;
  4869. }
  4870. 100% {
  4871. transform: scale(1) translateY(0);
  4872. animation-timing-function: ease-out;
  4873. }
  4874. }
  4875. @-webkit-keyframes jumpAnimation {
  4876. 0% {
  4877. -webkit-transform: scale(1) translateY(0);
  4878. animation-timing-function: ease-out;
  4879. }
  4880. 50% {
  4881. -webkit-transform: scale(1.2) translateY(-5px);
  4882. animation-timing-function: ease-in;
  4883. }
  4884. 100% {
  4885. -webkit-transform: scale(1) translateY(0);
  4886. animation-timing-function: ease-out;
  4887. }
  4888. }
  4889. `;
  4890. this.mainSignDiv = this.createSignDiv();
  4891. this.allSignDiv = [];
  4892. let frame = document.createElement("div");
  4893. frame.id = "pagetual-picker";
  4894. frame.innerHTML = createHTML(`
  4895. <button title="Pagetual" type="button" class="logoIcon">
  4896. <svg width="30" height="30" class="upSvg pagetual" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M296 440c-44.1 0-80 35.9-80 80s35.9 80 80 80 80-35.9 80-80-35.9-80-80-80z" style="fill: #604b4a;" fill="#604b4a"></path><path d="M960 512c0-247-201-448-448-448S64 265 64 512c0 1.8 0.1 3.5 0.1 5.3 0 0.9-0.1 1.8-0.1 2.7h0.2C68.5 763.3 267.7 960 512 960c236.2 0 430.1-183.7 446.7-415.7 0.1-0.8 0.1-1.6 0.2-2.3 0.4-4.6 0.5-9.3 0.7-13.9 0.1-2.7 0.4-5.3 0.4-8h-0.2c0-2.8 0.2-5.4 0.2-8.1z m-152 8c0 44.1-35.9 80-80 80s-80-35.9-80-80 35.9-80 80-80 80 35.9 80 80zM512 928C284.4 928 99 744.3 96.1 517.3 97.6 408.3 186.6 320 296 320c110.3 0 200 89.7 200 200 0 127.9 104.1 232 232 232 62.9 0 119.9-25.2 161.7-66-66 142.7-210.4 242-377.7 242z" style="fill: #604b4a;" fill="#604b4a"></path></svg>
  4897. </button>
  4898. <div class="title" title="${i18n("configure")}">${i18n("picker")}</div>
  4899. <button title="${i18n("closePicker")}" type="button" class="closePicker">
  4900. <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M512 128c212 0 384 172 384 384s-172 384-384 384-384-172-384-384 172-384 384-384m0-64C264.8 64 64 264.8 64 512s200.8 448 448 448 448-200.8 448-448S759.2 64 512 64z m238.4 254.4l-45.6-45.6L512 467.2 318.4 273.6l-45.6 45.6L467.2 512 273.6 705.6l45.6 45.6L512 557.6l193.6 193.6 45.6-45.6L557.6 512l192.8-193.6z" style="fill: #604b4a;" fill="#604b4a"></path></svg>
  4901. </button>
  4902. <div class="allpath" title="${i18n("switchSelector")}"></div>
  4903. <div>
  4904. <textarea class="selector" spellcheck="false" name="selector" placeholder="${i18n("pickerPlaceholder")}"></textarea>
  4905. <button id="check" title="${i18n("pickerCheck")}" type="button">
  4906. <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M512 128a384 384 0 1 0 0 768 384 384 0 0 0 0-768z m0-85.333333c259.2 0 469.333333 210.133333 469.333333 469.333333s-210.133333 469.333333-469.333333 469.333333S42.666667 771.2 42.666667 512 252.8 42.666667 512 42.666667zM696.149333 298.666667L768 349.866667 471.594667 725.333333 256 571.733333l53.888-68.266666 143.744 102.4z" style="fill: #604b4a;" fill="#604b4a"></path></svg>
  4907. </button>
  4908. </div>
  4909. <div class="bottom">
  4910. <input name="xpath" id="checkbox_id" type="checkbox" />
  4911. <label for="checkbox_id">XPath</label>
  4912. <button id="edit" title="${i18n("gotoEdit")}" type="button">
  4913. <svg viewBox="0 0 1024 1024" style="color: orangered;fill: orangered;" version="1.1" xmlns="http://www.w3.org/2000/svg">
  4914. <path d="M775.84 392.768l-155.2-172.352L160.768 643.264l-38.368 187.936 190.56-12.832zM929.952 229.952l-131.2-150.944-0.288-0.32a16 16 0 0 0-22.592-0.96l-131.168 120.576 155.168 172.352 128.832-118.464a15.936 15.936 0 0 0 1.248-22.24zM96 896h832v64H96z">
  4915. </path>
  4916. </svg>
  4917. </button>
  4918. </div>
  4919. <div class="moreConfig">
  4920. <div title="${i18n('forceStateIframe')}">
  4921. <input name="forceState" id="forceStateIframe" type="radio" />
  4922. <label for="forceStateIframe">${i18n('iframe')}</label>
  4923. </div>
  4924. <div title="${i18n('forceStateDynamic')}">
  4925. <input name="forceState" id="forceStateDynamic" type="radio" />
  4926. <label for="forceStateDynamic">${i18n('dynamic')}</label>
  4927. </div>
  4928. <div title="${i18n('forceStateDisable')}">
  4929. <input name="forceState" id="forceStateDisable" type="radio" />
  4930. <label for="forceStateDisable">${i18n('disable')}</label>
  4931. </div>
  4932. </div>
  4933. <button id="nextSwitch" class="command" title="${i18n("nextSwitch")}" type="button">${i18n("nextSwitch")}</button>
  4934. <button id="loadNow" class="command" title="${i18n("loadNow")}" type="button">${i18n("loadNow")}</button>
  4935. <button id="autoScroll" class="command" title="${i18n("toggleAutoScroll")}" type="button"></button>
  4936. <button id="ruleRequest" class="command" title="${i18n("ruleRequest")}" type="button">${i18n("ruleRequest")}</button>
  4937. <div>
  4938. <textarea class="tempRule" spellcheck="false" placeholder="{Rule object}" title="Rule for current site"></textarea>
  4939. <button id="showDetail" title="" type="button">
  4940. <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M511.1 63.7c-247.4 0-448 200.6-448 448s200.6 448 448 448 448-200.6 448-448-200.6-448-448-448z m281.2 374.5L535.6 694.9c-12.5 12.5-32.8 12.5-45.3 0l-255.8-256c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l210.7 210.7c12.5 12.5 32.8 12.5 45.3 0l211.4-211.4c12.5-12.5 32.8-12.5 45.3 0 12.3 12.5 12.3 32.8-0.2 45.3z" style="fill: orangered;" fill="orangered"></path></svg>
  4941. </button>
  4942. <div class="addProp">
  4943. <button id="addOtherProp" title="${i18n("addOtherProp")}" type="button">+</button>
  4944. <button id="addNextSelector" title="${i18n("addNextSelector")}" type="button">></button>
  4945. <button id="addPageSelector" title="${i18n("addPageSelector")}" type="button">❏</button>
  4946. </div>
  4947. <button id="saveDetail" title="${i18n("save")}" type="button">
  4948. <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M704 128H192c-35.2 0-64 28.8-64 64v640c0 35.2 28.8 64 64 64h640c35.2 0 64-28.8 64-64V320L704 128zM256 256h320v128H256V256z m256 512c-70.4 0-128-57.6-128-128s57.6-128 128-128 128 57.6 128 128-57.6 128-128 128z" style="fill: orangered;" fill="orangered"></path></svg>
  4949. </button>
  4950. </div>
  4951. `);
  4952. let forceStateIframe = frame.querySelector("#forceStateIframe");//forceState 1 禁用 2 强嵌 3 动态
  4953. let forceStateDynamic = frame.querySelector("#forceStateDynamic");
  4954. let forceStateDisable = frame.querySelector("#forceStateDisable");
  4955. let clickRadio = e => {
  4956. let radio = e.currentTarget.querySelector('input');
  4957. if (radio.checked) {
  4958. forceState = "";
  4959. } else {
  4960. switch (radio.id) {
  4961. case "forceStateIframe":
  4962. forceState = 2;
  4963. break;
  4964. case "forceStateDynamic":
  4965. forceState = 3;
  4966. break;
  4967. case "forceStateDisable":
  4968. forceState = 1;
  4969. break;
  4970. default:
  4971. return;
  4972. }
  4973. }
  4974. setListData("forceState", location.host, forceState);
  4975. self.close();
  4976. setTimeout(() => {
  4977. location.reload();
  4978. }, 500);
  4979. };
  4980. forceStateIframe.parentNode.addEventListener("mousedown", clickRadio);
  4981. forceStateDynamic.parentNode.addEventListener("mousedown", clickRadio);
  4982. forceStateDisable.parentNode.addEventListener("mousedown", clickRadio);
  4983. if (forceState == 1) forceStateDisable.checked = true;
  4984. else if (forceState == 2) forceStateIframe.checked = true;
  4985. else if (forceState == 3) forceStateDynamic.checked = true;
  4986. let closeBtn = frame.querySelector(".closePicker");
  4987. let logoBtn = frame.querySelector(".logoIcon");
  4988. let title = frame.querySelector(".title");
  4989. let allpath = frame.querySelector(".allpath");
  4990. let selectorInput = frame.querySelector(".selector");
  4991. let xpath = frame.querySelector("#checkbox_id");
  4992. let checkBtn = frame.querySelector("#check");
  4993. let editBtn = frame.querySelector("#edit");
  4994. let nextSwitchBtn = frame.querySelector("#nextSwitch");
  4995. let autoScrollBtn = frame.querySelector("#autoScroll");
  4996. let loadNow = frame.querySelector("#loadNow");
  4997. let tempRule = frame.querySelector(".tempRule");
  4998. let showDetailBtn = frame.querySelector("#showDetail");
  4999. let saveDetailBtn = frame.querySelector("#saveDetail");
  5000. let addOtherProp = frame.querySelector("#addOtherProp");
  5001. let addNextSelector = frame.querySelector("#addNextSelector");
  5002. let addPageSelector = frame.querySelector("#addPageSelector");
  5003. let ruleRequestBtn = frame.querySelector("#ruleRequest");
  5004. ruleRequestBtn.addEventListener("click", e => {
  5005. _GM_openInTab("https://github.com/hoothin/UserScripts/issues/new?labels=Pagetual&template=custom-rule-request.md&title=Request%20Pagetual%20support%20for%20" + location.hostname + "#" + location.href, {active: true});
  5006. }, true);
  5007. autoScrollBtn.addEventListener("click", e => {
  5008. self.close();
  5009. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  5010. autoScroll = parseInt(autoScroll) || 0;
  5011. if (autoScroll < 0) autoScroll = 0;
  5012. if (autoScroll && autoScroll != autoScrollRate) {
  5013. autoScrollRate = autoScroll;
  5014. storage.setItem("autoScrollRate", autoScrollRate);
  5015. }
  5016. setListData("autoScroll", location.host + location.pathname, autoScroll);
  5017. startAutoScroll();
  5018. }, true);
  5019. addOtherProp.addEventListener("click", e => {
  5020. let propName = prompt(i18n("propName"), "author");
  5021. if (!propName) return;
  5022. let propValue = prompt(i18n("propValue"));
  5023. if (!propValue) return;
  5024. if (propValue === "true") propValue = true;
  5025. else if (propValue === "false") propValue = false;
  5026. else if (/^\d+$/.test(propValue)) propValue = parseInt(propValue);
  5027. if (propName === "author" && propValue) {
  5028. author = propValue;
  5029. storage.setItem("author", propValue);
  5030. }
  5031. let editTemp = self.getTempRule();
  5032. if (!editTemp) return;
  5033. editTemp[propName] = propValue;
  5034. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  5035. }, true);
  5036. addNextSelector.addEventListener("click", e => {
  5037. let editTemp = self.getTempRule();
  5038. if (!editTemp) return;
  5039. let selector = self.selectorInput.value;
  5040. if (selector) {
  5041. editTemp.nextLink = selector;
  5042. }
  5043. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  5044. }, true);
  5045. addPageSelector.addEventListener("click", e => {
  5046. let editTemp = self.getTempRule();
  5047. if (!editTemp) return;
  5048. let selector = self.selectorInput.value;
  5049. if (selector) {
  5050. editTemp.pageElement = selector;
  5051. }
  5052. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  5053. }, true);
  5054. showDetailBtn.addEventListener("click", e => {
  5055. frame.classList.toggle("showDetail");
  5056. }, true);
  5057. saveDetailBtn.addEventListener("click", e => {
  5058. let editTemp = self.getTempRule(true);
  5059. if (tempRule.value && !editTemp) {
  5060. return;
  5061. }
  5062. if(!ruleParser.customRules) {
  5063. ruleParser.customRules = [];
  5064. }
  5065. ruleParser.customRules = ruleParser.customRules.filter(item => {return item.url != editTemp.url || item.name != editTemp.name});
  5066. if (tempRule.value) {
  5067. ruleParser.customRules.unshift(editTemp);
  5068. ruleParser.curSiteRule = editTemp;
  5069. } else {
  5070. ruleParser.curSiteRule = {};
  5071. isPause = true;
  5072. }
  5073. storage.setItem("customRules", ruleParser.customRules);
  5074. if (ruleParser.hpRules && ruleParser.curSiteRule && !ruleParser.curSiteRule.smart) {
  5075. ruleParser.addToHpRules(true);
  5076. }
  5077. if (window.confirm(i18n("reloadPage"))) {
  5078. setTimeout(() => {location.reload()}, 100);
  5079. }
  5080. }, true);
  5081. nextSwitchBtn.addEventListener("click", e => {
  5082. self.close();
  5083. nextSwitch.start();
  5084. }, true);
  5085. loadNow.addEventListener("click", e => {
  5086. self.close();
  5087. let loadNum = window.prompt(i18n("loadConfirm"), "1");
  5088. if (loadNum === "" || loadNum === null) return;
  5089. autoLoadNum = Math.abs(parseInt(loadNum));
  5090. nextPage();
  5091. }, true);
  5092. closeBtn.addEventListener("click", e => {
  5093. self.close();
  5094. }, true);
  5095. this.showSign = true;
  5096. logoBtn.addEventListener("click", e => {
  5097. logoBtn.classList.toggle("showSign");
  5098. self.showSign = !self.showSign;
  5099. getBody(document).classList.toggle("pagetual-picker");
  5100. }, true);
  5101. let moving = false;
  5102. let initX = 0, initY = 0, initPos = {x: 0, y: 0};
  5103. let moveHanlder = e => {
  5104. if (moving) {
  5105. frame.style.left = e.clientX - initX + "px";
  5106. frame.style.top = e.clientY - initY + "px";
  5107. e.stopPropagation();
  5108. e.preventDefault();
  5109. } else if(Math.abs(e.clientX - initPos.x) + Math.abs(e.clientY - initPos.y) > 20) {
  5110. moving = true;
  5111. }
  5112. };
  5113. let upHanlder = e => {
  5114. if (moving) {
  5115. moving = false;
  5116. } else {
  5117. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  5118. }
  5119. document.removeEventListener("mousemove", moveHanlder, true);
  5120. title.removeEventListener("mouseup", upHanlder, true);
  5121. e.stopPropagation();
  5122. e.preventDefault();
  5123. };
  5124. title.addEventListener("mousedown", e => {
  5125. initPos = {x: e.clientX, y: e.clientY};
  5126. initX = e.clientX - parseInt(getComputedStyle(frame).left);
  5127. initY = e.clientY - parseInt(getComputedStyle(frame).top);
  5128. document.addEventListener("mousemove", moveHanlder, true);
  5129. title.addEventListener("mouseup", upHanlder, true);
  5130. });
  5131. frame.addEventListener("mouseenter", e => {
  5132. if (!self.showSign || moving) return;
  5133. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  5134. self.checkInputSelector(false);
  5135. });
  5136. frame.addEventListener("mouseleave", e => {
  5137. if (!self.showSign) {
  5138. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  5139. self.clearSigns();
  5140. return;
  5141. }
  5142. if (moving) return;
  5143. document.documentElement.appendChild(self.mainSignDiv);
  5144. self.clearSigns();
  5145. });
  5146. checkBtn.addEventListener("click", e => {
  5147. self.checkInputSelector();
  5148. if (this.selectorInput.value && self.foundEle) {
  5149. debug(self.foundEle);
  5150. self.foundEle[0].scrollIntoView({ behavior: "smooth" });
  5151. _GM_setClipboard(this.selectorInput.value);
  5152. showTips(i18n("copied"));
  5153. } else showTips("Null");
  5154. });
  5155. xpath.addEventListener("click", e => {
  5156. if (!selectorInput.value) {
  5157. self.setSelectorDiv("");
  5158. return;
  5159. }
  5160. let element = getElement(selectorInput.value, document);
  5161. let selector = self.getSelectorFromEle(element);
  5162. selectorInput.value = selector;
  5163. self.setSelectorDiv(selector);
  5164. });
  5165. editBtn.addEventListener("click", e => {
  5166. rulesData.editTemp = self.getTempRule();
  5167. storage.setItem("rulesData", rulesData);
  5168. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  5169. });
  5170. editBtn.oncontextmenu = e => {
  5171. e.preventDefault();
  5172. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  5173. };
  5174. this.frame = frame;
  5175. this.xpath = xpath;
  5176. this.allpath = allpath;
  5177. this.selectorInput = selectorInput;
  5178. this.nextSwitchBtn = nextSwitchBtn;
  5179. this.autoScrollBtn = autoScrollBtn;
  5180. this.loadNow = loadNow;
  5181. this.tempRule = tempRule;
  5182. this.logoBtn = logoBtn;
  5183. let setTitleTimer;
  5184. this.moveHandler = e => {
  5185. if (!self.showSign || e.target === document) return;
  5186. let target = self.getTarget(e.target);
  5187. self.adjustSignDiv(self.mainSignDiv, target);
  5188. clearTimeout(setTitleTimer);
  5189. setTitleTimer = setTimeout(() => {
  5190. if (self.inPicker && target.hasAttributes()) {
  5191. let title = target.nodeName.toLowerCase() + "\n";
  5192. for (const attr of target.attributes) {
  5193. title += `【${attr.name}】${attr.value ? " ➡️ " + attr.value : ""}\n`;
  5194. }
  5195. getBody(document).title = title;
  5196. }
  5197. }, 100);
  5198. };
  5199. this.clickHandler = e => {
  5200. if (!self.showSign || !e.isTrusted) return;
  5201. if (self.inPicker) {
  5202. e.stopPropagation();
  5203. e.preventDefault();
  5204. }
  5205. let target = self.getTarget(e.target);
  5206. let selector = self.getSelectorFromEle(target);
  5207. selectorInput.value = selector;
  5208. self.setSelectorDiv(selector);
  5209. };
  5210. }
  5211.  
  5212. getTempRule(detail) {
  5213. if (this.tempRule.value) {
  5214. try {
  5215. this.editTemp = JSON.parse(this.tempRule.value);
  5216. } catch (e) {
  5217. this.editTemp = null;
  5218. if (detail) {
  5219. let pos = e && e.message && e.message.match(/position (\d+)/);
  5220. if (pos) {
  5221. pos = parseInt(pos[1]);
  5222. this.tempRule.value = this.tempRule.value.slice(0, pos) + "➡️" + this.tempRule.value.slice(pos);
  5223. }
  5224. showTips(i18n("errorJson"));
  5225. return null;
  5226. }
  5227. }
  5228. }
  5229. if (!this.editTemp) {
  5230. if (ruleParser.curSiteRule.url && !ruleParser.curSiteRule.smart) {
  5231. this.editTemp = ruleParser.curSiteRule;
  5232. } else {
  5233. this.editTemp = {
  5234. name: document.title,
  5235. url: "^" + (location.origin + location.pathname).replace(/[^\/]*$/, "").replace(/^https?/, "https?").replace(/\./g, "\\."),
  5236. example: location.href
  5237. };
  5238. if (author) this.editTemp.author = author;
  5239. }
  5240. delete this.editTemp.from;
  5241. delete this.editTemp.type;
  5242. delete this.editTemp.updatedAt;
  5243. }
  5244. if (this.selectorInput.value && (!this.frame.classList.contains("showDetail") || !this.editTemp || !this.editTemp.pageElement)) {
  5245. if (this.foundEle && this.foundEle.length === 1) {
  5246. let foundEleRect = this.foundEle[0].getBoundingClientRect();
  5247. if (foundEleRect.height < 100) {
  5248. showTips("Next Link", "", 500);
  5249. this.editTemp.nextLink = this.selectorInput.value;
  5250. return this.editTemp;
  5251. }
  5252. }
  5253. showTips("Page Element", "", 500);
  5254. this.editTemp.pageElement = this.selectorInput.value;
  5255. }
  5256. return this.editTemp;
  5257. }
  5258.  
  5259. getTarget(ele) {
  5260. while (ele.parentNode && (ele.offsetWidth === 0 || ele.offsetHeight === 0)) {
  5261. ele = ele.parentNode;
  5262. }
  5263. return ele;
  5264. }
  5265.  
  5266. close() {
  5267. this.clearSigns();
  5268. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  5269. if (this.mainSignDiv.parentNode) this.mainSignDiv.parentNode.removeChild(this.mainSignDiv);
  5270. getBody(document).classList.remove("pagetual-picker");
  5271. getBody(document).removeEventListener("mousemove", this.moveHandler, true);
  5272. getBody(document).removeEventListener("click", this.clickHandler, true);
  5273. getBody(document).title = "";
  5274. this.inPicker = false;
  5275. }
  5276.  
  5277. setImportant(ele, prop, value) {
  5278. ele.style.setProperty(prop, value, "important");
  5279. }
  5280.  
  5281. createSignDiv() {
  5282. let signDiv = document.createElement("div");
  5283. this.setImportant(signDiv, "position", "absolute");
  5284. this.setImportant(signDiv, "pointer-events", "none");
  5285. this.setImportant(signDiv, "z-index", "2147483645");
  5286. this.setImportant(signDiv, "background", "rgba(120, 170, 210, 0.6)");
  5287. this.setImportant(signDiv, "transition", "all 0.15s ease-out");
  5288. this.setImportant(signDiv, "box-shadow", "rgb(0 0 0) 0px 0px 3px 0px");
  5289. return signDiv;
  5290. }
  5291.  
  5292. adjustSignDiv(div, target) {
  5293. let rect = target.getBoundingClientRect();
  5294. this.setImportant(div, "width", rect.width + "px");
  5295. this.setImportant(div, "height", rect.height + "px");
  5296. this.setImportant(div, "left", rect.left + window.scrollX + "px");
  5297. this.setImportant(div, "top", rect.top + window.scrollY + "px");
  5298. }
  5299.  
  5300. getSelectorFromEle(ele) {
  5301. return this.xpath.checked ? createXPathFromElement(ele) : geneSelector(ele, true);
  5302. }
  5303.  
  5304. fillTempRuleTextarea() {
  5305. if (!this.frame.classList.contains("showDetail") || !this.editTemp || !this.editTemp.pageElement) this.tempRule.value = JSON.stringify(this.getTempRule(), null, 4);
  5306. }
  5307.  
  5308. setSelectorDiv(selector) {
  5309. let self = this;
  5310. this.allpath.innerHTML = createHTML("");
  5311. if (selector) {
  5312. if (this.xpath.checked) {
  5313. let span = document.createElement("span");
  5314. span.innerText = selector;
  5315. span.addEventListener("click", e => {
  5316. self.selectorInput.value = selector;
  5317. self.checkInputSelector();
  5318. }, true);
  5319. this.allpath.appendChild(span);
  5320. } else {
  5321. selector.split(">").forEach((item, index) => self.geneSelectorItem(item, index));
  5322. }
  5323. }
  5324. this.checkInputSelector();
  5325. }
  5326.  
  5327. geneSelectorItem(item, index) {
  5328. let self = this;
  5329. item = item.trim();
  5330. if (!item) return;
  5331. if (index !== 0) {
  5332. let span = document.createElement("span");
  5333. span.innerText = " > ";
  5334. this.allpath.appendChild(span);
  5335. }
  5336. let span = document.createElement("span");
  5337. span.className = "path";
  5338. span.innerText = item;
  5339. span.addEventListener("click", e => {
  5340. let selector = "";
  5341. let target = e.target;
  5342. while (target) {
  5343. selector = target.innerText + selector;
  5344. target = target.previousElementSibling;
  5345. }
  5346. self.selectorInput.value = selector;
  5347. self.checkInputSelector();
  5348. if (self.checkedPath) {
  5349. self.checkedPath.classList.remove("checked");
  5350. }
  5351. span.classList.add("checked");
  5352. self.checkedPath = span;
  5353. }, true);
  5354. this.allpath.appendChild(span);
  5355. }
  5356.  
  5357. checkInputSelector(fill = true) {
  5358. let self = this;
  5359. this.clearSigns();
  5360. if (!this.selectorInput.value) return;
  5361. let eles = getAllElements(this.selectorInput.value, document);
  5362. this.foundEle = null;
  5363. if (eles && eles.length > 0) {
  5364. this.foundEle = eles;
  5365. eles.forEach(ele => {
  5366. let sign = self.createSignDiv();
  5367. document.documentElement.appendChild(sign);
  5368. self.adjustSignDiv(sign, ele);
  5369. self.signList.push(sign);
  5370. });
  5371. if (fill) this.fillTempRuleTextarea();
  5372. }
  5373. }
  5374.  
  5375. clearSigns() {
  5376. this.signList.forEach(sign => {
  5377. if (sign.parentNode) sign.parentNode.removeChild(sign);
  5378. });
  5379. this.signList = [];
  5380. }
  5381.  
  5382. start() {
  5383. this.init();
  5384. if (this.inPicker) return;
  5385. this.inPicker = true;
  5386. if (!this.styleEle || !this.styleEle.parentNode) {
  5387. this.styleEle = _GM_addStyle(this.cssText);
  5388. }
  5389. document.documentElement.appendChild(this.frame);
  5390. document.documentElement.appendChild(this.mainSignDiv);
  5391. getBody(document).classList.add("pagetual-picker");
  5392.  
  5393. this.logoBtn.classList.remove("showSign");
  5394. this.showSign = true;
  5395.  
  5396. getBody(document).addEventListener("mousemove", this.moveHandler, true);
  5397. getBody(document).addEventListener("click", this.clickHandler, true);
  5398. this.xpath.checked = isXPath(ruleParser.curSiteRule.pageElement);
  5399. this.tempRule.value = "";
  5400. this.editTemp = null;
  5401. this.frame.classList.remove("showDetail");
  5402.  
  5403. this.loadNow.style.display = ruleParser.nextLinkHref ? "block" : "none";
  5404. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  5405. this.nextSwitchBtn.style.display = "block";
  5406. } else {
  5407. this.nextSwitchBtn.style.display = "none";
  5408. }
  5409. this.autoScrollBtn.innerText = i18n(autoScroll ? "disableAutoScroll" : "enableAutoScroll");
  5410.  
  5411. let pageElementSel = ruleParser.curSiteRule.pageElement || "";
  5412. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  5413. pageElementSel = pageElementSel[nextIndex < pageElementSel.length ? nextIndex : 0];
  5414. }
  5415. this.setSelectorDiv(pageElementSel);
  5416. this.fillTempRuleTextarea();
  5417. }
  5418. }
  5419. const picker = new Picker();
  5420.  
  5421. var editor, editorChanged = false, customRulesInput;
  5422. function createEdit() {
  5423. var options = {
  5424. mode: 'code',
  5425. modes: ['code', 'tree'],
  5426. templates: [
  5427. {
  5428. text: 'New site',
  5429. title: 'Insert a new site',
  5430. className: 'jsoneditor-type-object',
  5431. field: 'SiteTemplate',
  5432. value: {
  5433. 'name': 'Site name',
  5434. 'url': 'Site url'
  5435. }
  5436. }
  5437. ],
  5438. schema: {
  5439. "title": "Sites data",
  5440. "description": "Object containing site config",
  5441. "type": "array",
  5442. "items": {
  5443. "type": 'object',
  5444. "properties": {
  5445. "name": {
  5446. "title": "Site Name",
  5447. "description": "The site's name.",
  5448. "examples": [
  5449. "Google"
  5450. ],
  5451. "type": "string"
  5452. },
  5453. "url": {
  5454. "title": "Site Url",
  5455. "description": "The Regexp of site's url.",
  5456. "examples": [
  5457. "^https:\/\/yande\\.re\/"
  5458. ],
  5459. "type": "string"
  5460. }
  5461. },
  5462. "required": ["name", "url"]
  5463. }
  5464. },
  5465. onChange: () => {
  5466. editorChanged = true;
  5467. }
  5468. };
  5469. setTimeout(() => {
  5470. var container = document.getElementById("jsoneditor");
  5471. if (!container) {
  5472. container = document.createElement("div");
  5473. configCon.appendChild(container);
  5474. }
  5475. container.style.height = '800px';
  5476. container.innerHTML = "";
  5477. try {
  5478. editor = new _unsafeWindow.JSONEditor(container, options);
  5479. editor.set(ruleParser.customRules);
  5480. } catch (e) {
  5481. editor = null;
  5482. container.style.display = 'none';
  5483. customRulesInput.style.display = "";
  5484. }
  5485. }, 500);
  5486. }
  5487.  
  5488. function checkGuidePage(href) {
  5489. if (guidePage.test(href)) {
  5490. if (typeof _unsafeWindow.JSONEditor !== 'undefined') {
  5491. createEdit();
  5492. } else {
  5493. let timeout = 30;
  5494. let checkEditorReady = setInterval(() => {
  5495. if (typeof _unsafeWindow.JSONEditor !== 'undefined') {
  5496. createEdit();
  5497. clearInterval(checkEditorReady);
  5498. } else if (timeout-- <= 0) {
  5499. editor = null;
  5500. customRulesInput.style.display = "";
  5501. clearInterval(checkEditorReady);
  5502. }
  5503. }, 100);
  5504. }
  5505. return true;
  5506. }
  5507. return false;
  5508. }
  5509.  
  5510. function startAutoScroll() {
  5511. clearInterval(autoScrollInterval);
  5512. if (autoScroll <= 0) return;
  5513. let scrollRange_o = 1;
  5514. if (autoScroll > 1000) {
  5515. scrollRange_o = parseInt(autoScroll / 1000);
  5516. }
  5517. let devicePixelRatio = window.devicePixelRatio;
  5518. let scrollRange = Math.ceil(scrollRange_o / devicePixelRatio);
  5519.  
  5520. let scrollTarget, body = getBody(document);
  5521. let checkOverflow = ele => {
  5522. return ele.scrollHeight !== ele.clientHeight && getComputedStyle(ele).overflowY !== "hidden";
  5523. };
  5524. if (document.documentElement.scrollTop || checkOverflow(document.documentElement)) {
  5525. scrollTarget = document.documentElement;
  5526. } else if (body.scrollTop || checkOverflow(body)) {
  5527. scrollTarget = body;
  5528. } else {
  5529. let tempEle;
  5530. let img = body.querySelector('img');
  5531. if (img) {
  5532. tempEle = img;
  5533. while (tempEle && !checkOverflow(tempEle)) {
  5534. tempEle = tempEle.parentNode;
  5535. }
  5536. }
  5537. if (!tempEle && document.activeElement) {
  5538. let tempEle = document.activeElement;
  5539. while (tempEle && !checkOverflow(tempEle)) {
  5540. tempEle = tempEle.parentNode;
  5541. }
  5542. }
  5543. if (tempEle) scrollTarget = tempEle;
  5544. }
  5545. scrollTarget = scrollTarget || document.documentElement;
  5546.  
  5547. autoScrollInterval = setInterval(() => {
  5548. if (isPause && !urlChanging) return;
  5549. if (devicePixelRatio !== window.devicePixelRatio) {
  5550. devicePixelRatio = window.devicePixelRatio;
  5551. scrollRange = Math.ceil(scrollRange_o / devicePixelRatio);
  5552. }
  5553. scrollTarget.scrollTop += scrollRange;
  5554. }, parseInt(1000 / autoScroll));
  5555. }
  5556.  
  5557. var inUpdate = false;
  5558. var importHandler, configCon;
  5559. function initConfig(href) {
  5560. if (location.hostname === "github.com") {
  5561. if (location.href.indexOf("https://github.com/hoothin/UserScripts/issues/new?labels=Pagetual&template=custom-rule-request.md&title=Request%20Pagetual%20support%20for%20") === 0) {
  5562. let issue_body = document.getElementById("issue_body");
  5563. if (!issue_body) return true;
  5564. issue_body.value = issue_body.value.replace("\n", "\n" + location.hash.slice(1) + "\n");
  5565. let starButton = document.createElement("a");
  5566. starButton.href = "https://github.com/hoothin/UserScripts#star";
  5567. starButton.className = "js-toggler-target rounded-left-2 btn-with-aria-count btn-sm btn";
  5568. starButton.innerHTML = createHTML('<svg height="16" viewBox="0 0 16 16" version="1.1" width="16" class="octicon octicon-star d-inline-block mr-2"><path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path></svg><span class="d-inline">Star</span>');
  5569. starButton.style.float = "right";
  5570. document.querySelector(".Layout-main>h2").appendChild(starButton);
  5571. return true;
  5572. } else if (location.href === "https://github.com/hoothin/UserScripts#star") {
  5573. let starButton = document.querySelector(".starring-container:not(.on)>.unstarred>form>button");
  5574. if (starButton) emuClick(starButton);
  5575. return true;
  5576. }
  5577. }
  5578. let isGuidePage = checkGuidePage(href);
  5579.  
  5580. var click2import, importUrlPres;
  5581.  
  5582. let inConfig = isGuidePage;
  5583. if (!inConfig) {
  5584. for (let i = 0; i < configPage.length; i++) {
  5585. if (configPage[i] == location.href) {
  5586. inConfig = true;
  5587. break;
  5588. }
  5589. }
  5590. }
  5591. if (!isGuidePage) {
  5592. if (location.hostname === "hoothin.github.io" || location.hostname === "pagetual.hoothin.com") isGuidePage = true;
  5593. }
  5594. configCon = document.getElementById("configCon");
  5595. if (configCon) {
  5596. configCon.parentNode.removeChild(configCon);
  5597. }
  5598. if (ruleImportUrlReg.test(href) || inConfig) {
  5599. let importing = false;
  5600. if (!inUpdate && rulesData.uninited) {
  5601. setTimeout(() => {
  5602. if (!inUpdate && !importing) showTips(i18n("firstAlert"));
  5603. }, 3000);
  5604. showTips(i18n("firstAlert"));
  5605. }
  5606. let defaultOption = document.querySelector('#discussion_rating_4');
  5607. if (defaultOption) defaultOption.checked = true;
  5608. let createImportBtn = (pre) => {
  5609. let importBtn = document.createElement("button");
  5610. importBtn.id = "pagetualImport";
  5611. importBtn.innerText = i18n("import");
  5612. importBtn.style.marginTop = "100px";
  5613. importBtn.style.float = "right";
  5614. importBtn.style.position = "relative";
  5615. importBtn.style.display = "block";
  5616. importBtn.style.fontSize = "20px";
  5617. importBtn.addEventListener("click", e => {
  5618. let parentNode = importBtn.parentNode;
  5619. if (!parentNode) return;
  5620. parentNode.removeChild(importBtn);
  5621. try {
  5622. let rules = parentNode.innerText.trim();
  5623. let isContent = /['"]name['"]/i.test(rules);
  5624. if (isContent) {
  5625. let ruleList = JSON.parse(`[${rules}]`);
  5626. for (let i in ruleList) {
  5627. let hasRule = false;
  5628. let r = ruleList[i];
  5629. for (let j in ruleParser.customRules) {
  5630. if (ruleParser.customRules[j].name == r.name) {
  5631. ruleParser.customRules[j] = r;
  5632. hasRule = true;
  5633. break;
  5634. }
  5635. }
  5636. if (!hasRule) ruleParser.customRules.push(r);
  5637. ruleParser.hpRules.unshift(r);
  5638. }
  5639. storage.setItem("customRules", ruleParser.customRules);
  5640. storage.setItem("hpRules", ruleParser.hpRules);
  5641. storage.setItem("smartRules", []);
  5642. showTips(i18n("importSucc"));
  5643. } else {
  5644. rules = rules.split("\n");
  5645. let diff = false;
  5646. for (let c = 0; c < rules.length; c++) {
  5647. let urlArr = rules[c].split("|"), url, type = 1;
  5648. if (urlArr.length == 1) {
  5649. url = urlArr[0].trim();
  5650. if (!/^http/.test(url)) {
  5651. showTips(i18n("errorWrongUrl"));
  5652. return;
  5653. }
  5654. } else if (urlArr.length == 2) {
  5655. type = urlArr[0].trim();
  5656. url = urlArr[1].trim();
  5657. if (!/^http/.test(url)) {
  5658. showTips(i18n("errorWrongUrl"));
  5659. return;
  5660. }
  5661. } else {
  5662. break;
  5663. }
  5664. let maxId = 1, hasUrl = false;
  5665. if (!rulesData.urls) {
  5666. rulesData.urls = [];
  5667. maxId = 1;
  5668. } else {
  5669. rulesData.urls.forEach(u => {
  5670. if (maxId < u.id) {
  5671. maxId = u.id;
  5672. }
  5673. if (u.url == url) {
  5674. hasUrl = true;
  5675. }
  5676. });
  5677. if (hasUrl) break;
  5678. }
  5679. diff = true;
  5680. if (!rulesData.sort) rulesData.sort = [1];
  5681. rulesData.urls.push({id: maxId + 1, url: url, type: type});
  5682. rulesData.sort.unshift(maxId + 1);
  5683. }
  5684. if (!diff) {
  5685. showTips(i18n("errorAlreadyExists"));
  5686. setTimeout(() => {
  5687. showTips(i18n("beginUpdate"), "", 50000);
  5688. updateRules(() => {
  5689. showTips(i18n("updateSucc"));
  5690. location.reload();
  5691. }, (rule, err) => {
  5692. showTips(`Failed to update ${rule.url} rules!`);
  5693. debug(err);
  5694. });
  5695. }, 500);
  5696. return;
  5697. }
  5698. storage.setItem("rulesData", rulesData);
  5699.  
  5700. if (rulesData.urls) ruleUrls = ruleUrls.concat(rulesData.urls);
  5701. if (rulesData.sort) {
  5702. let urls = [];
  5703. rulesData.sort.forEach(id => {
  5704. for (let s = 0; s < ruleUrls.length; s++) {
  5705. if (id == ruleUrls[s].id) {
  5706. urls.push(ruleUrls[s]);
  5707. break;
  5708. }
  5709. }
  5710. });
  5711. ruleUrls = urls;
  5712. }
  5713. showTips(i18n("beginUpdate"), "", 30000);
  5714. updateRules(() => {
  5715. showTips(i18n("updateSucc"));
  5716. location.reload();
  5717. }, (rule, err) => {
  5718. showTips(`Failed to update ${rule.url} rules!`);
  5719. debug(err);
  5720. });
  5721. importing = true;
  5722. }
  5723. } catch (e) {
  5724. _GM_notification(e.toString());
  5725. }
  5726. });
  5727. if (pre) {
  5728. let clientHeight = 35 - pre.clientHeight;
  5729. if (clientHeight > -20) clientHeight = -20;
  5730. importBtn.style.marginTop = `${clientHeight}px`;
  5731. pre.appendChild(importBtn);
  5732. }
  5733. return importBtn;
  5734. };
  5735. [].forEach.call(document.querySelectorAll('pre[name=pagetual],pre[name=user-content-pagetual]'), pre => {
  5736. let importBtn = createImportBtn(pre);
  5737. if (rulesData.uninited) {
  5738. pre.style.display = "";
  5739. }
  5740. });
  5741. click2import = document.querySelector("[name='user-content-click2import'],[name='click2import']");
  5742. if (click2import) {
  5743. click2import.innerText = i18n("click2ImportRule");
  5744. click2import.style.display = rulesData.uninited ? "block" : "none";
  5745. }
  5746. if (!importHandler) {
  5747. importHandler = e => {
  5748. if (compareNodeName(e.target, ["pre"])) {
  5749. let nameAttr = e.target.getAttribute("name");
  5750. if (nameAttr == "pagetual" || nameAttr == "user-content-pagetual") {
  5751. if (e.target.querySelector('#pagetualImport')) return;
  5752. let importBtn = createImportBtn(e.target);
  5753. }
  5754. }
  5755. };
  5756. }
  5757. document.removeEventListener("mouseover", importHandler);
  5758. document.addEventListener("mouseover", importHandler);
  5759.  
  5760. if (inConfig) {
  5761. if (!inUpdate && _GM_info.script && _GM_info.script.version && _GM_info.script.version !== '1.0.0') {
  5762. let versionEle = document.querySelector('.markdown-body>h1[id],article>h1');
  5763. let latestVer = versionEle && versionEle.innerText.match(/\d[\d\.]+/)[0];
  5764. if (latestVer && latestVer != _GM_info.script.version) {
  5765. showTips(i18n('outOfDate'), "", 3000);
  5766. }
  5767. }
  5768. _GM_addStyle(`
  5769. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  5770. cursor: pointer;
  5771. user-select: none;
  5772. display: inline-block;
  5773. margin-right: 5px;
  5774. -moz-transition:color 0.3s ease, transform 0.3s;
  5775. -webkit-transition:color 0.3s ease, transform 0.3s;
  5776. transition:color 0.3s ease, transform 0.3s;
  5777. }
  5778. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  5779. color:red;
  5780. transform: scale(1.5);
  5781. -webkit-transform: scale(1.5);
  5782. }
  5783. .updateDate{
  5784. cursor: pointer;
  5785. user-select: none;
  5786. -moz-transition:color 0.3s ease, transform 0.3s;
  5787. -webkit-transition:color 0.3s ease, transform 0.3s;
  5788. transition:color 0.3s ease, transform 0.3s;
  5789. transform-origin: left;
  5790. -webkit-transform-origin: left;
  5791. }
  5792. .updateDate:hover{
  5793. color:red;
  5794. transform: scale(1.1);
  5795. -webkit-transform: scale(1.1);
  5796. }
  5797. input[type=number]::-webkit-inner-spin-button,
  5798. input[type=number]::-webkit-outer-spin-button {
  5799. -webkit-appearance: none;
  5800. margin: 0;
  5801. }
  5802. input[type=number] {
  5803. -moz-appearance:textfield;
  5804. }
  5805. table td>h3 {
  5806. margin: 16px!important;
  5807. padding: 0!important;
  5808. }
  5809. table td>h4 {
  5810. padding: 0!important;
  5811. }
  5812. #saveBtn {
  5813. width: 60vw;
  5814. position: fixed;
  5815. z-index: 999;
  5816. bottom: 0;
  5817. left: 20vw;
  5818. font-size: xx-large;
  5819. opacity: 0.6;
  5820. cursor: pointer;
  5821. -moz-transition:all 0.3s ease;
  5822. -webkit-transition:all 0.3s ease;
  5823. transition:all 0.3s ease;
  5824. }
  5825. #configCon #saveBtn:hover {
  5826. opacity: 1;
  5827. margin-bottom: 0px;
  5828. }
  5829. #configCon #saveBtn {
  5830. margin-bottom: -30px;
  5831. }
  5832. #configCon.showSave #saveBtn {
  5833. margin-bottom: 0px;
  5834. }
  5835. `);
  5836. configCon = document.querySelector(".markdown-body,.theme-default-content");
  5837. if (!configCon) {
  5838. setTimeout(() => {
  5839. location.reload();
  5840. }, 1000);
  5841. return true;
  5842. }
  5843. let insertPos = configCon.querySelector("hr,#jsoneditor");
  5844. configCon = document.createElement("div");
  5845. configCon.id = "configCon";
  5846. insertPos.parentNode.insertBefore(configCon, insertPos);
  5847.  
  5848. importUrlPres = document.querySelectorAll("pre[name='user-content-pagetual'],pre[name='pagetual']");
  5849. if (importUrlPres) {
  5850. [].forEach.call(importUrlPres, importUrlPre => {
  5851. importUrlPre.style.overflow = "hidden";
  5852. importUrlPre.style.display = rulesData.uninited ? "block" : "none";
  5853. });
  5854. }
  5855. let otherconfig = document.querySelector("a[name='user-content-otherconfig'],a[name='otherconfig']");
  5856. if (otherconfig) otherconfig.parentNode.removeChild(otherconfig);
  5857. let rulesExample = document.querySelector("#user-content-rules-example+a,#rules-example>a");
  5858. if (rulesExample) {
  5859. rulesExample.innerText = i18n("rulesExample");
  5860. if (lang == "zh-CN") {
  5861. rulesExample.href = rulesExample.href.replace("en", "cn");
  5862. } else if (lang == "zh-TW" || lang == "zh-HK") {
  5863. rulesExample.href = rulesExample.href.replace("/en", "");
  5864. }
  5865. }
  5866. document.documentElement.scrollTop = 0;
  5867.  
  5868. let newPos, lastPos = 0;
  5869. window.addEventListener('scroll', function(e) {
  5870. newPos = window.scrollY;
  5871. if (newPos > lastPos) {
  5872. configCon.classList.add("showSave");
  5873. } else {
  5874. configCon.classList.remove("showSave");
  5875. }
  5876. lastPos = newPos;
  5877. });
  5878. } else return isGuidePage;
  5879. } else return isGuidePage;
  5880. let ruleBarInsertPos = document.createTextNode(' ');
  5881. configCon.appendChild(ruleBarInsertPos);
  5882. class Rulebar {
  5883. init(ruleUrl) {
  5884. let id = ruleUrl.id;
  5885. this.ruleUrl = ruleUrl;
  5886. this.item = document.createElement("p");
  5887. this.item.dataset.id = id;
  5888. let url = document.createElement("a");
  5889. url.href = ruleUrl.url;
  5890. url.innerHTML = ruleUrl.url;
  5891. url.title = ruleUrl.url;
  5892. let up = document.createElement("span");
  5893. up.innerHTML = "↑ ";
  5894. up.title = i18n("sortTitle");
  5895. let down = document.createElement("span");
  5896. down.innerHTML = "↓ ";
  5897. down.title = i18n("sortTitle");
  5898. let del = document.createElement("span");
  5899. del.innerHTML = "× ";
  5900. up.onclick = e => {
  5901. this.moveUp();
  5902. };
  5903. down.onclick = e => {
  5904. this.moveDown();
  5905. };
  5906. del.onclick = e => {
  5907. this.del();
  5908. };
  5909. this.item.appendChild(up);
  5910. this.item.appendChild(down);
  5911. this.item.appendChild(del);
  5912. this.item.appendChild(url);
  5913. if (ruleParser.rules) {
  5914. url.style.maxWidth = "calc(100% - 150px)";
  5915. url.style.overflow = "hidden";
  5916. url.style.display = "inline-block";
  5917. url.style.textOverflow = "ellipsis";
  5918. url.style.verticalAlign = "bottom";
  5919. url.style.whiteSpace = "nowrap";
  5920. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == id ? 1 : 0), 0);
  5921. let idSpan = document.createElement("span");
  5922. idSpan.style.float = "right";
  5923. idSpan.innerHTML = `[rules: ${rulesLength}]`;
  5924. this.item.appendChild(idSpan);
  5925. this.idSpan = idSpan;
  5926. }
  5927. configCon.insertBefore(this.item, ruleBarInsertPos);
  5928. }
  5929. updateNum() {
  5930. if (ruleParser.rules) {
  5931. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == this.item.dataset.id ? 1 : 0), 0);
  5932. this.idSpan.innerHTML = `[rules: ${rulesLength}]`;
  5933. }
  5934. }
  5935. saveSort() {
  5936. let sort = [];
  5937. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i => {
  5938. sort.push(i.dataset.id);
  5939. });
  5940. rulesData.sort = sort;
  5941. let urls = [];
  5942. sort.forEach(id => {
  5943. for (let s = 0; s < ruleUrls.length; s++) {
  5944. if (id == ruleUrls[s].id) {
  5945. urls.push(ruleUrls[s]);
  5946. break;
  5947. }
  5948. }
  5949. });
  5950. ruleUrls = urls;
  5951. storage.setItem("rulesData", rulesData);
  5952. showTips(i18n("sortTitle"));
  5953. }
  5954. moveUp() {
  5955. let preE = this.item.previousElementSibling;
  5956. if (compareNodeName(preE, ["p"]) && preE.children.length > 1) {
  5957. this.item.parentNode.insertBefore(this.item, preE);
  5958. this.saveSort();
  5959. }
  5960. }
  5961. moveDown() {
  5962. let nextE = this.item.nextElementSibling;
  5963. if (compareNodeName(nextE, ["p"]) && nextE.children.length > 1) {
  5964. this.item.parentNode.insertBefore(nextE, this.item);
  5965. this.saveSort();
  5966. }
  5967. }
  5968. del() {
  5969. if (this.ruleUrl.id < 2) {
  5970. showTips(i18n("cantDel"));
  5971. } else if (window.confirm(i18n("confirmDel"))) {
  5972. for (let u = 0; u < rulesData.urls.length; u++) {
  5973. if (this.ruleUrl.id == rulesData.urls[u].id) {
  5974. rulesData.urls.splice(u, 1);
  5975. break;
  5976. }
  5977. }
  5978. for (let u = 0; u < ruleUrls.length; u++) {
  5979. if (this.ruleUrl.id == ruleUrls[u].id) {
  5980. ruleUrls.splice(u, 1);
  5981. break;
  5982. }
  5983. }
  5984. for (let u = 0; u < rulesData.sort.length; u++) {
  5985. if (this.ruleUrl.id == rulesData.sort[u]) {
  5986. rulesData.sort.splice(u, 1);
  5987. break;
  5988. }
  5989. }
  5990. rulesData.ruleVersion = 0;
  5991. storage.setItem("rulesData", rulesData);
  5992. ruleParser.rules = ruleParser.rules.filter(item => {return item.from != this.ruleUrl.id});
  5993. storage.setItem("rules", ruleParser.rules);
  5994. this.item.parentNode.removeChild(this.item);
  5995. //location.reload();
  5996. }
  5997. }
  5998. }
  5999. let langSelect = document.createElement("select");
  6000. langSelect.style.float = "right";
  6001. langSelect.style.position = "relative";
  6002. langSelect.style.zIndex = "1";
  6003. let option = document.createElement("option");
  6004. option.value = "";
  6005. option.innerText = "Language";
  6006. langSelect.appendChild(option);
  6007. for (let key in langList) {
  6008. let option = document.createElement("option");
  6009. option.value = key;
  6010. option.innerText = langList[key];
  6011. langSelect.appendChild(option);
  6012. }
  6013. langSelect.value = rulesData.lang || "";
  6014. configCon.appendChild(langSelect);
  6015.  
  6016. let updateP = document.createElement("p"), i = 0;
  6017. let now = new Date().getTime();
  6018.  
  6019.  
  6020. let pastDate = (new Date(updateDate)).toString(), passStr;
  6021. let passTime = (now - updateDate) / 1000;
  6022. if (isNaN(passTime)) {
  6023. passStr = i18n("firstUpdate");
  6024. } else {
  6025. if (passTime < 60) {
  6026. passStr = i18n("passSec", parseInt(passTime));
  6027. } else if (passTime < 60 * 60) {
  6028. passStr = i18n("passMin", parseInt(passTime / 60));
  6029. } else if (passTime < 60 * 60 * 24) {
  6030. passStr = i18n("passHour", parseInt(passTime / 3600));
  6031. } else {
  6032. passStr = i18n("passDay", parseInt(passTime / 86400));
  6033. }
  6034. passStr += " 🖱 " + i18n("click2update");
  6035. }
  6036.  
  6037. let rulebarList = [], updateFail = false;
  6038. updateP.className = "updateDate";
  6039. updateP.innerHTML = passStr;
  6040. updateP.title = i18n("update") + " - " + pastDate;
  6041. configCon.appendChild(updateP);
  6042. if (ruleUrls) {
  6043. ruleUrls.forEach(ruleUrl => {
  6044. let rulebar = new Rulebar();
  6045. rulebar.init(ruleUrl);
  6046. rulebarList.push(rulebar);
  6047. });
  6048. }
  6049. let customUrlsTitle = document.createElement("h2");
  6050. customUrlsTitle.innerHTML = i18n("customUrls");
  6051. configCon.appendChild(customUrlsTitle);
  6052. let customUrlsInput = document.createElement("textarea");
  6053. customUrlsInput.style.width = "100%";
  6054. customUrlsInput.style.position = "relative";
  6055. customUrlsInput.placeholder = "http://wedata.net/databases/AutoPagerize/items_all.json \nhttps://hoothin.github.io/UserScripts/Pagetual/pagetualRules.json";
  6056. customUrlsInput.spellcheck = false;
  6057. configCon.appendChild(customUrlsInput);
  6058.  
  6059. let btns = document.createElement("div");
  6060. btns.style.display = "flex";
  6061. configCon.appendChild(btns);
  6062. let upBtnImg = document.createElement("div");
  6063. upBtnImg.style.width = "33%";
  6064. let upBtnImgTitle = document.createElement("h2");
  6065. upBtnImgTitle.style.whiteSpace = "nowrap";
  6066. upBtnImgTitle.style.overflow = "auto";
  6067. upBtnImgTitle.innerHTML = i18n("upBtnImg");
  6068. upBtnImg.appendChild(upBtnImgTitle);
  6069. let upBtnImgInput = document.createElement("input");
  6070. upBtnImgInput.style.width = "100%";
  6071. upBtnImgInput.style.position = "relative";
  6072. upBtnImgInput.placeholder = "data:image/png;base64,UpBtn";
  6073. upBtnImgInput.value = rulesData.upBtnImg || '';
  6074. upBtnImgInput.spellcheck = false;
  6075. upBtnImg.appendChild(upBtnImgInput);
  6076. btns.appendChild(upBtnImg);
  6077.  
  6078. let downBtnImg = document.createElement("div");
  6079. downBtnImg.style.width = "33%";
  6080. let downBtnImgTitle = document.createElement("h2");
  6081. downBtnImgTitle.style.whiteSpace = "nowrap";
  6082. downBtnImgTitle.style.overflow = "auto";
  6083. downBtnImgTitle.innerHTML = i18n("downBtnImg");
  6084. downBtnImg.appendChild(downBtnImgTitle);
  6085. let downBtnImgInput = document.createElement("input");
  6086. downBtnImgInput.style.width = "100%";
  6087. downBtnImgInput.style.position = "relative";
  6088. downBtnImgInput.placeholder = "data:image/png;base64,DownBtn";
  6089. downBtnImgInput.value = rulesData.downBtnImg || '';
  6090. downBtnImgInput.spellcheck = false;
  6091. downBtnImg.appendChild(downBtnImgInput);
  6092. btns.appendChild(downBtnImg);
  6093.  
  6094. let sideControllerIconDiv = document.createElement("div");
  6095. sideControllerIconDiv.style.width = "33%";
  6096. let sideControllerIconTitle = document.createElement("h2");
  6097. sideControllerIconTitle.style.whiteSpace = "nowrap";
  6098. sideControllerIconTitle.style.overflow = "auto";
  6099. sideControllerIconTitle.innerHTML = i18n("sideControllerIcon");
  6100. sideControllerIconDiv.appendChild(sideControllerIconTitle);
  6101. let sideControllerIconInput = document.createElement("input");
  6102. sideControllerIconInput.style.width = "100%";
  6103. sideControllerIconInput.style.position = "relative";
  6104. sideControllerIconInput.placeholder = "📄";
  6105. sideControllerIconInput.value = rulesData.sideControllerIcon || '';
  6106. sideControllerIconInput.spellcheck = false;
  6107. sideControllerIconDiv.appendChild(sideControllerIconInput);
  6108. btns.appendChild(sideControllerIconDiv);
  6109.  
  6110. let otherBtns = document.createElement("div");
  6111. otherBtns.style.display = "flex";
  6112. configCon.appendChild(otherBtns);
  6113. let loadingText = document.createElement("div");
  6114. loadingText.style.width = "100%";
  6115. let loadingTextTitle = document.createElement("h2");
  6116. loadingTextTitle.style.whiteSpace = "nowrap";
  6117. loadingTextTitle.style.overflow = "auto";
  6118. loadingTextTitle.innerHTML = i18n("loadingTextTitle");
  6119. loadingText.appendChild(loadingTextTitle);
  6120. let loadingTextInput = document.createElement("input");
  6121. loadingTextInput.value = rulesData.loadingText || '';
  6122. loadingTextInput.placeholder = i18n("loadingText");
  6123. loadingTextInput.style.width = "100%";
  6124. loadingTextInput.style.position = "relative";
  6125. loadingTextInput.style.margin = "0";
  6126. loadingTextInput.spellcheck = false;
  6127. loadingText.appendChild(loadingTextInput);
  6128. otherBtns.appendChild(loadingText);
  6129.  
  6130. let opacity = document.createElement("div");
  6131. let opacityTitle = document.createElement("h2");
  6132. opacityTitle.style.whiteSpace = "nowrap";
  6133. opacityTitle.style.overflow = "visible";
  6134. opacityTitle.innerHTML = i18n("opacity");
  6135. opacity.appendChild(opacityTitle);
  6136. let opacityInput = document.createElement("input");
  6137. opacityInput.value = rulesData.opacity * 100;
  6138. opacityInput.type = "number";
  6139. opacityInput.min = 0;
  6140. opacityInput.max = 100;
  6141. opacityInput.style.width = "110px";
  6142. opacityInput.style.position = "relative";
  6143. opacityInput.style.margin = "0";
  6144. opacityInput.placeholder = i18n("opacityPlaceholder");
  6145. opacityInput.spellcheck = false;
  6146. opacityInput.oninput = e => {
  6147. if (opacityInput.value > 100) opacityInput.value = 100;
  6148. else if (opacityInput.value < 0) opacityInput.value = 0;
  6149. };
  6150. opacity.appendChild(opacityInput);
  6151. otherBtns.appendChild(opacity);
  6152.  
  6153. let pageElementCss = document.createElement("div");
  6154. pageElementCss.style.marginBottom = "30px";
  6155. let pageElementCssTitle = document.createElement("h2");
  6156. pageElementCssTitle.innerHTML = i18n("pageElementCss");
  6157. pageElementCss.appendChild(pageElementCssTitle);
  6158. let pageElementCssInput = document.createElement("input");
  6159. pageElementCssInput.value = rulesData.pageElementCss || '';
  6160. pageElementCssInput.style.width = "100%";
  6161. pageElementCssInput.style.position = "relative";
  6162. pageElementCssInput.style.margin = "0";
  6163. pageElementCssInput.placeholder = "font-size: xx-large;";
  6164. pageElementCssInput.spellcheck = false;
  6165. pageElementCss.appendChild(pageElementCssInput);
  6166. configCon.appendChild(pageElementCss);
  6167.  
  6168. let customCss = document.createElement("div");
  6169. customCss.style.marginBottom = "50px";
  6170. let customCssTitle = document.createElement("h2");
  6171. customCssTitle.innerHTML = i18n("customCss");
  6172. customCss.appendChild(customCssTitle);
  6173. let customCssInput = document.createElement("textarea");
  6174. customCssInput.value = rulesData.customCss || '';
  6175. customCssInput.style.width = "100%";
  6176. customCssInput.style.position = "relative";
  6177. customCssInput.style.margin = "0";
  6178. customCssInput.placeholder = ".pagetual {\n}";
  6179. customCssInput.spellcheck = false;
  6180. customCss.appendChild(customCssInput);
  6181. configCon.appendChild(customCss);
  6182.  
  6183. let configTable = document.createElement("table");
  6184. configTable.style.width = "100%";
  6185. let configTbody = document.createElement("tbody");
  6186. configTbody.style.width = "99%";
  6187. configTbody.style.display = "inline-table";
  6188. configTable.appendChild(configTbody);
  6189. configCon.appendChild(configTable);
  6190. function createCheckbox(innerText, val, tag, parentCheck, otherType, alwaysShow) {
  6191. if (typeof val == 'undefined') val = "";
  6192. let title = document.createElement(tag || "h3");
  6193. title.innerHTML = innerText;
  6194. title.style.overflowWrap = "normal";
  6195. let input = document.createElement("input");
  6196. if (otherType === 'key') {
  6197. input.type = 'text';
  6198. input.setAttribute('readOnly', 'readonly');
  6199. input.addEventListener("keydown", e => {
  6200. if (e.key === 'Escape' || e.key === 'Backspace') input.value = '';
  6201. else input.value = e.key;
  6202. e.stopPropagation();
  6203. e.preventDefault();
  6204. });
  6205. } else {
  6206. input.type = otherType || "checkbox";
  6207. }
  6208. input.style.width = "35px";
  6209. input.style.height = "20px";
  6210. input.style.float = "left";
  6211. input.style.margin = "0 2px";
  6212. input.value = val;
  6213. input.checked = val;
  6214. let td = document.createElement("td");
  6215. td.appendChild(input);
  6216. if (parentCheck) {
  6217. title.appendChild(input);
  6218. title.style.margin = "0";
  6219. td.appendChild(title);
  6220. let parent = parentCheck.parentNode.nextElementSibling;
  6221. let tr = parent.querySelector("tr");
  6222. if (!tr) {
  6223. tr = document.createElement("tr");
  6224. parent.appendChild(tr);
  6225. }
  6226. tr.appendChild(td);
  6227. if (!alwaysShow) {
  6228. if (!parentCheck.checked) {
  6229. td.style.display = "none";
  6230. }
  6231. parentCheck.addEventListener("click", e => {
  6232. td.style.display = parentCheck.checked ? "" : "none";
  6233. });
  6234. }
  6235. } else {
  6236. let tr = document.createElement("tr");
  6237. tr.appendChild(td);
  6238. td = document.createElement("td");
  6239. td.appendChild(title);
  6240. tr.appendChild(td);
  6241. configTable.children[0].appendChild(tr);
  6242. }
  6243. let xNodePos = innerText.indexOf('【X】');
  6244. if (xNodePos !== -1) {
  6245. input.style.float = "";
  6246. let xNode = title.firstChild.splitText(xNodePos);
  6247. xNode.splitText(3);
  6248. xNode.parentNode.replaceChild(input, xNode);
  6249. }
  6250. return input;
  6251. }
  6252.  
  6253. let setConfigPageInput = createCheckbox(i18n("setConfigPage"), false);
  6254. let enableWhiteListInput = createCheckbox(i18n("autoRun"), rulesData.enableWhiteList != true);
  6255. let sideControllerInput = createCheckbox(i18n("sideController"), rulesData.sideController);
  6256. let sideControllerAlwaysInput = createCheckbox(i18n("sideControllerAlways"), rulesData.sideControllerAlways, "h4", sideControllerInput);
  6257. let sideControllerScrollInput = createCheckbox(i18n("sideControllerScroll"), rulesData.sideControllerScroll !== false, "h4", sideControllerInput);
  6258. let sideControllerLoadNowInput = createCheckbox(i18n("loadNow"), rulesData.sideControllerLoadNow !== false, "h4", sideControllerInput);
  6259. let enableDebugInput = createCheckbox(i18n("enableDebug"), rulesData.enableDebug != false);
  6260. let enableHistoryInput = createCheckbox(i18n("enableHistory"), rulesData.enableHistory === true);
  6261. let enableHistoryAfterInsertInput = createCheckbox(i18n("enableHistoryAfterInsert"), rulesData.enableHistoryAfterInsert === true, "h4", enableHistoryInput);
  6262. let openInNewTabInput = createCheckbox(i18n("openInNewTab"), rulesData.openInNewTab != false);
  6263. let hidePageBarInput = createCheckbox(i18n("hideBarTips"), rulesData.opacity == 0);
  6264. let hidePageBarArrowInput = createCheckbox(i18n("hideBarArrow"), rulesData.hideBarArrow);
  6265. let hideLoadingIconInput = createCheckbox(i18n("hideLoadingIcon"), rulesData.hideLoadingIcon != false);
  6266. let initRunInput = createCheckbox(i18n("initRun"), rulesData.initRun != false);
  6267. let autoLoadNumInput = createCheckbox(i18n("autoLoadNum"), rulesData.autoLoadNum, "h4", initRunInput, "number");
  6268. let preloadInput = createCheckbox(i18n("preload"), rulesData.preload != false);
  6269. let rateInput = createCheckbox(i18n("turnRate"), rulesData.rate, "h4", preloadInput, "number", true);
  6270. let dbClick2StopInput = createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  6271. let manualModeInput = createCheckbox(i18n("manualMode"), rulesData.manualMode);
  6272. let clickModeInput = createCheckbox(i18n("clickMode"), rulesData.clickMode);
  6273. let pageBarMenuInput = createCheckbox(i18n("pageBarMenu"), rulesData.pageBarMenu != false);
  6274. let arrowToScrollInput = createCheckbox(i18n("arrowToScroll"), rulesData.arrowToScroll);
  6275. let contentVisibilityInput = createCheckbox(i18n("contentVisibility"), rulesData.contentVisibility);
  6276. let wedata2githubInput = createCheckbox(i18n("wedata2github"), rulesData.wedata2github);
  6277. let customFirstInput = createCheckbox(i18n("customFirst"), rulesData.customFirst);
  6278. let lastPageTipsInput = createCheckbox(i18n("lastPageTips"), rulesData.lastPageTips);
  6279. let updateNotificationInput = createCheckbox(i18n("updateNotification"), rulesData.updateNotification != false);
  6280.  
  6281. let hideBarInput = createCheckbox(i18n("hideBar"), rulesData.hideBar && !rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  6282. hideBarInput.name = 'hideBar';
  6283. let hideBarButNoStopInput = createCheckbox(i18n("hideBarButNoStop"), rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  6284. hideBarButNoStopInput.name = 'hideBar';
  6285. hideBarInput.addEventListener('mouseup', e => {
  6286. if (hideBarInput.checked) {
  6287. setTimeout(() => {hideBarInput.checked = false}, 0);
  6288. }
  6289. });
  6290. hideBarButNoStopInput.addEventListener('mouseup', e => {
  6291. if (hideBarButNoStopInput.checked) {
  6292. setTimeout(() => {hideBarButNoStopInput.checked = false}, 0);
  6293. }
  6294. });
  6295. hidePageBarInput.addEventListener('click', e => {
  6296. opacityInput.value = hidePageBarInput.checked ? 0 : 100;
  6297. });
  6298.  
  6299. let dbClick2StopCtrlInput = createCheckbox(i18n("dbClick2StopCtrl"), rulesData.dbClick2StopCtrl, "h4", dbClick2StopInput);
  6300. let dbClick2StopAltInput = createCheckbox(i18n("dbClick2StopAlt"), rulesData.dbClick2StopAlt, "h4", dbClick2StopInput);
  6301. let dbClick2StopShiftInput = createCheckbox(i18n("dbClick2StopShift"), rulesData.dbClick2StopShift, "h4", dbClick2StopInput);
  6302. let dbClick2StopMetaInput = createCheckbox(i18n("dbClick2StopMeta"), rulesData.dbClick2StopMeta, "h4", dbClick2StopInput);
  6303. let dbClick2StopKeyInput = createCheckbox(i18n("dbClick2StopKey"), rulesData.dbClick2StopKey, "h4", dbClick2StopInput, "key");
  6304.  
  6305. let otherConfigPage = (rulesData.configPage || configPage[0]) != location.href.replace(/#.*/, "");
  6306. if (!otherConfigPage) {
  6307. setConfigPageInput.parentNode.parentNode.style.display = "none";
  6308. }
  6309.  
  6310. updateP.onclick = e => {
  6311. updateFail = false;
  6312. //ruleParser.rules = [];
  6313. showTips(i18n("beginUpdate"), "", 30000);
  6314. updateRules(() => {
  6315. if (!updateFail) {
  6316. showTips(i18n("updateSucc"));
  6317. if (importUrlPres) {
  6318. [].forEach.call(importUrlPres, importUrlPre => {
  6319. importUrlPre.style.display = "none";
  6320. });
  6321. }
  6322. if (click2import) click2import.style.display = "none";
  6323. }
  6324. updateP.innerHTML = i18n("passSec", 0);
  6325. updateP.title = i18n("update");
  6326. rulebarList.forEach(rulebar => {
  6327. rulebar.updateNum();
  6328. });
  6329. }, (rule, err) => {
  6330. if (rule.id == 1) {
  6331. showTips(`Failed to update wedata rules! Try to switch to wedata mirror!`);
  6332. wedata2githubInput.scrollIntoView({ behavior: "smooth" });
  6333. } else {
  6334. showTips(`Failed to update ${rule.url} rules!`);
  6335. }
  6336. debug(err);
  6337. updateFail = true;
  6338. });
  6339. };
  6340. let customRulesTitle = document.createElement("h2");
  6341. customRulesTitle.innerHTML = i18n("customRules", /tree/.test(location.href) ? location.href.replace('tree', 'edit').replace(/\/$/, '') + '/pagetualRules.json' : 'https://github.com/hoothin/UserScripts/edit/master/Pagetual/pagetualRules.json');
  6342. configCon.appendChild(customRulesTitle);
  6343. customRulesInput = document.createElement("textarea");
  6344. customRulesInput.spellcheck = false;
  6345. configCon.appendChild(customRulesInput);
  6346. if (rulesData.editTemp) {
  6347. if (!ruleParser.customRules) {
  6348. ruleParser.customRules = [];
  6349. }
  6350. for (let i in ruleParser.customRules) {
  6351. if (ruleParser.customRules[i].url == rulesData.editTemp.url) {
  6352. ruleParser.customRules.splice(i, 1);
  6353. break;
  6354. }
  6355. }
  6356. ruleParser.customRules.unshift(rulesData.editTemp);
  6357. rulesData.editTemp = null;
  6358. storage.setItem("rulesData", rulesData);
  6359. customRulesInput.previousElementSibling.scrollIntoView();
  6360. }
  6361. customRulesInput.style.width = "100%";
  6362. customRulesInput.style.height = "800px";
  6363. customRulesInput.placeholder = `[\n {\n "name":"yande",\n "action":"0",\n "url":"^https:\/\/yande\\.re\/",\n "pageElement":"ul#post-list-posts>li",\n "nextLink":"a.next_page",\n "css":".javascript-hide {display: inline-block !important;}"\n },\n {\n "name":"tieba",\n "action":"1",\n "url":"^https:\/\/tieba\\.baidu.com\/f\\?kw=",\n "pageElement":"ul#thread_list>li",\n "nextLink":".next.pagination-item "\n }\n]`;
  6364. let preCustom = getFormatJSON(ruleParser.customRules);
  6365. customRulesInput.value = preCustom;
  6366. if (isGuidePage) customRulesInput.style.display = "none";
  6367. let blacklistInput = document.createElement("textarea");
  6368. blacklistInput.style.width = "100%";
  6369. blacklistInput.style.height = "500px";
  6370. blacklistInput.style.display = "none";
  6371. blacklistInput.spellcheck = false;
  6372. blacklistInput.placeholder = "http://*.xxx.com/*/y\n/^https?://.*\\.xxx\\.com/i \t\t<= Regexp\n//http://*.aaa.com/ \t\t<= Disable\n/*http://*.bbb.com\nhttp://*.ccc.com*/ \t\t<= Block comment";
  6373. blacklistInput.value = rulesData.blacklist ? rulesData.blacklist.join("\n") : "";
  6374. let blacklistBtn = document.createElement("button");
  6375. blacklistBtn.innerText = i18n("editBlacklist");
  6376. blacklistBtn.style.width = "100%";
  6377. blacklistBtn.onclick = e => {
  6378. blacklistInput.style.display = blacklistInput.style.display == "none" ? "" : "none";
  6379. };
  6380. configCon.appendChild(blacklistBtn);
  6381. configCon.appendChild(blacklistInput);
  6382. let saveBtn = document.createElement("button");
  6383. saveBtn.innerHTML = i18n("save");
  6384. saveBtn.id = "saveBtn";
  6385. configCon.appendChild(saveBtn);
  6386. saveBtn.onclick = e => {
  6387. try {
  6388. let customRules;
  6389. if (editor) {
  6390. if (editorChanged) {
  6391. editorChanged = false;
  6392. storage.setItem("hpRules", []);
  6393. storage.setItem("smartRules", []);
  6394. }
  6395. customRules = editor.get();
  6396. if (!customRules) {
  6397. customRules = "";
  6398. } else {
  6399. if (Array && Array.isArray && !Array.isArray(customRules)) {
  6400. showTips(i18n("errorRulesMustBeArray"));
  6401. return;
  6402. }
  6403. }
  6404. } else {
  6405. if (customRulesInput.value != preCustom) {
  6406. storage.setItem("hpRules", []);
  6407. storage.setItem("smartRules", []);
  6408. }
  6409. if (customRulesInput.value == "") {
  6410. customRules = "";
  6411. } else {
  6412. customRules = JSON.parse(customRulesInput.value);
  6413. if (Array && Array.isArray && !Array.isArray(customRules)) {
  6414. showTips(i18n("errorRulesMustBeArray"));
  6415. return;
  6416. }
  6417. customRulesInput.value = JSON.stringify(customRules, null, 4);
  6418. }
  6419. }
  6420. debug(customRules);
  6421. storage.setItem("customRules", customRules);
  6422. } catch(e) {
  6423. debug(e);
  6424. let pos = e && e.message && e.message.match(/position (\d+)/);
  6425. if (pos && !editor) {
  6426. pos = parseInt(pos[1]);
  6427. customRulesInput.value = customRulesInput.value.slice(0, pos) + "➡️" + customRulesInput.value.slice(pos);
  6428. }
  6429. showTips(i18n("errorJson"));
  6430. return;
  6431. }
  6432. rulesData.lang = langSelect.value || "";
  6433. if (setConfigPageInput.checked) rulesData.configPage = location.href;
  6434. rulesData.wedata2github = wedata2githubInput.checked;
  6435. let opacity = parseInt(opacityInput.value) || 0;
  6436. if (opacity > 100) opacity = 100;
  6437. else if (opacity < 0) opacity = 0;
  6438. rulesData.opacity = opacity / 100;
  6439. rulesData.blacklist = blacklistInput.value ? blacklistInput.value.trim().split("\n") : "";
  6440. rulesData.hideBar = hideBarInput.checked;
  6441. rulesData.hideBarButNoStop = hideBarButNoStopInput.checked;
  6442. rulesData.dbClick2Stop = dbClick2StopInput.checked;
  6443. rulesData.enableWhiteList = !enableWhiteListInput.checked;
  6444. rulesData.enableDebug = enableDebugInput.checked;
  6445. rulesData.updateNotification = updateNotificationInput.checked;
  6446. rulesData.enableHistory = enableHistoryInput.checked;
  6447. rulesData.enableHistoryAfterInsert = enableHistoryAfterInsertInput.checked;
  6448. rulesData.openInNewTab = openInNewTabInput.checked;
  6449. rulesData.hideLoadingIcon = hideLoadingIconInput.checked;
  6450. rulesData.hideBarArrow = hidePageBarArrowInput.checked;
  6451. rulesData.customFirst = customFirstInput.checked;
  6452. rulesData.lastPageTips = lastPageTipsInput.checked;
  6453. rulesData.initRun = initRunInput.checked;
  6454. rulesData.autoLoadNum = autoLoadNumInput.value !== "0" ? autoLoadNumInput.value : '';
  6455. rulesData.rate = parseFloat(rateInput.value) || 0;
  6456. rulesData.preload = preloadInput.checked;
  6457. rulesData.manualMode = manualModeInput.checked;
  6458. rulesData.clickMode = clickModeInput.checked;
  6459. rulesData.pageBarMenu = pageBarMenuInput.checked;
  6460. rulesData.arrowToScroll = arrowToScrollInput.checked;
  6461. rulesData.contentVisibility = contentVisibilityInput.checked;
  6462. if (rulesData.sideController != sideControllerInput.checked) {
  6463. rulesData.sideControllerPos = false;
  6464. }
  6465. rulesData.sideController = sideControllerInput.checked;
  6466. rulesData.sideControllerScroll = sideControllerScrollInput.checked;
  6467. rulesData.sideControllerLoadNow = sideControllerLoadNowInput.checked;
  6468. rulesData.sideControllerAlways = sideControllerAlwaysInput.checked;
  6469. rulesData.pageElementCss = pageElementCssInput.value;
  6470. rulesData.customCss = customCssInput.value;
  6471. rulesData.upBtnImg = upBtnImgInput.value;
  6472. rulesData.downBtnImg = downBtnImgInput.value;
  6473. rulesData.sideControllerIcon = sideControllerIconInput.value;
  6474. rulesData.loadingText = loadingTextInput.value;
  6475. rulesData.dbClick2StopCtrl = dbClick2StopCtrlInput.checked;
  6476. rulesData.dbClick2StopAlt = dbClick2StopAltInput.checked;
  6477. rulesData.dbClick2StopShift = dbClick2StopShiftInput.checked;
  6478. rulesData.dbClick2StopMeta = dbClick2StopMetaInput.checked;
  6479. rulesData.dbClick2StopKey = dbClick2StopKeyInput.value;
  6480. storage.setItem("rulesData", rulesData);
  6481. let customUrls = customUrlsInput.value.trim(), urlImported = false;
  6482. if (customUrls) {
  6483. customUrls = customUrls.split(/\n/);
  6484. for (let c = 0; c < customUrls.length; c++) {
  6485. let url;
  6486. if (/^0\s*\|/.test(customUrls[c])) {
  6487. url = customUrls[c].replace(/^0\s*\|\s*/, "").trim();
  6488. if (!/^http/.test(url)) {
  6489. showTips(i18n("errorWrongUrl"));
  6490. return;
  6491. }
  6492. } else {
  6493. url = customUrls[c].trim();
  6494. if (!/^http/.test(url)) {
  6495. showTips(i18n("errorWrongUrl"));
  6496. return;
  6497. }
  6498. }
  6499. let maxId = 1, hasUrl = false;
  6500. if (!rulesData.urls) {
  6501. rulesData.urls = [];
  6502. }
  6503. ruleUrls.forEach(u => {
  6504. if (maxId < u.id) {
  6505. maxId = u.id;
  6506. }
  6507. if (u.url == url) {
  6508. hasUrl = true;
  6509. }
  6510. });
  6511. if (hasUrl) break;
  6512. if (!rulesData.sort) rulesData.sort = [1];
  6513. let newRule = {id: maxId + 1, url: url};
  6514. ruleUrls.push(newRule);
  6515. rulesData.urls.push(newRule);
  6516. rulesData.sort.push(maxId + 1);
  6517. storage.setItem("rulesData", rulesData);
  6518. let rulebar = new Rulebar();
  6519. rulebar.init(newRule);
  6520. rulebarList.push(rulebar);
  6521. }
  6522. }
  6523. showTips(i18n("settingsSaved"));
  6524. };
  6525. return true;
  6526. }
  6527.  
  6528. function updateRules (success, fail, keepCache) {
  6529. if (!storage.supportCrossSave()) {
  6530. fail({url:''}, "Not support cross storage");
  6531. showTips("Current platform do not support cross storage!");
  6532. return;
  6533. }
  6534. if (inUpdate) return;
  6535. inUpdate = true;
  6536. let ruleIndex = ruleUrls.length - 1;
  6537. if (!keepCache) {
  6538. storage.setItem("hpRules", []);
  6539. storage.setItem("smartRules", []);
  6540. }
  6541. let allOk = true;
  6542. let preLength = ruleParser.rules.length;
  6543. let fetchVersion = -1;
  6544. async function needUpdate(url, id) {
  6545. if (!/^https:\/\/hoothin\.github\.io\/|\/hoothin\/UserScripts\/.*\/Pagetual\/pagetualRules\.json/i.test(url)) {
  6546. return true;
  6547. }
  6548. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == id ? 1 : 0), 0);
  6549. if (rulesLength === 0) return true;
  6550. if (fetchVersion >= 0) {
  6551. return fetchVersion > (rulesData.ruleVersion || 0);
  6552. }
  6553. fetchVersion = await new Promise(resolve => {
  6554. _GM_xmlhttpRequest({
  6555. url: url.replace(/\/\w+\.json/i, "/version"),
  6556. method: 'GET',
  6557. timeout: 20000,
  6558. headers: {
  6559. 'accept': 'application/json,text/html'
  6560. },
  6561. onload: function(res) {
  6562. let version = parseInt(res.response || res.responseText);
  6563. resolve(version || -1);
  6564. },
  6565. onerror: function(e) {
  6566. resolve(-1);
  6567. },
  6568. ontimeout: function(e) {
  6569. resolve(-1);
  6570. }
  6571. });
  6572. });
  6573. return fetchVersion > (rulesData.ruleVersion || 0);
  6574. }
  6575. async function addNextRule() {
  6576. if (ruleIndex < 0) {
  6577. let now = new Date().getTime();
  6578. storage.setItem("ruleLastUpdate", now);
  6579. storage.setItem("rules", ruleParser.rules);
  6580. let curLength = ruleParser.rules.length;
  6581. if (curLength !== preLength && rulesData.updateNotification) {
  6582. _GM_notification({
  6583. text: `Rules has updated( ${preLength} => ${curLength} )`,
  6584. title: "Pagetual rules updated",
  6585. onclick: (event) => {
  6586. event.preventDefault();
  6587. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  6588. }
  6589. });
  6590. }
  6591. inUpdate = false;
  6592. let rulesDataChanged = false;
  6593. if (fetchVersion >= 0 && rulesData.ruleVersion !== fetchVersion) {
  6594. rulesData.ruleVersion = fetchVersion;
  6595. rulesDataChanged = true;
  6596. }
  6597. if (rulesData.uninited && allOk && ruleUrls.length > 1) {
  6598. rulesData.uninited = false;
  6599. rulesDataChanged = true;
  6600. }
  6601. if (rulesDataChanged) {
  6602. storage.setItem("rulesData", rulesData);
  6603. }
  6604. success();
  6605. } else {
  6606. let rule = ruleUrls[ruleIndex--];
  6607. if (await needUpdate(rule.url, rule.id)) {
  6608. ruleParser.addRuleByUrl(rule.url, rule.id, (json, err) => {
  6609. if (!json) {
  6610. allOk = false;
  6611. fail(rule, err);
  6612. }
  6613. addNextRule();
  6614. });
  6615. } else {
  6616. addNextRule();
  6617. }
  6618. }
  6619. }
  6620. addNextRule();
  6621. }
  6622.  
  6623. function objIsArr(obj) {
  6624. return obj &&
  6625. typeof obj === 'object' &&
  6626. typeof obj.length === 'number' &&
  6627. !(obj.propertyIsEnumerable('length'));
  6628. }
  6629.  
  6630. function isVisible(el, win) {
  6631. if(!el || !el.offsetParent)return false;
  6632. var loopable = true,
  6633. visible = el.nodeName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  6634. while(loopable && visible) {
  6635. el = el.parentNode;
  6636.  
  6637. if(el && el.nodeType === 1 && !compareNodeName(el, ["body"])) {
  6638. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  6639. }else {
  6640. loopable = false;
  6641. }
  6642. }
  6643. return visible;
  6644. }
  6645.  
  6646. function getElementTop(ele) {
  6647. if (!ele) return 0;
  6648. if (ele.getBoundingClientRect) {
  6649. return ele.getBoundingClientRect().top + document.documentElement.scrollTop;
  6650. }
  6651. var actualTop = ele.offsetTop;
  6652. var current = ele.offsetParent;
  6653. while (current) {
  6654. actualTop += current.offsetTop;
  6655. current = current.offsetParent;
  6656. }
  6657. return actualTop;
  6658. }
  6659.  
  6660. function getElementLeft(ele) {
  6661. if (!ele) return 0;
  6662. if (ele.getBoundingClientRect) {
  6663. return ele.getBoundingClientRect().left + document.documentElement.scrollLeft;
  6664. }
  6665. var actualLeft = ele.offsetLeft;
  6666. var current = ele.offsetParent;
  6667. while (current) {
  6668. actualLeft += current.offsetLeft;
  6669. current = current.offsetParent;
  6670. }
  6671. return actualLeft;
  6672. }
  6673.  
  6674. function getElementBottom(ele) {
  6675. return getElementTop(ele) + (ele.offsetHeight || ele.scrollHeight);
  6676. }
  6677.  
  6678. function getFormatJSON(obj){
  6679. if(!objIsArr(obj) || obj.length === 0)return "";
  6680. return JSON.stringify(obj, null, 4);
  6681. }
  6682.  
  6683. function globMatch(first, second) {
  6684. if (first === '*') {
  6685. return true;
  6686. }
  6687. if (first.length == 0 && second.length == 0){
  6688. return true;
  6689. }
  6690.  
  6691. if (first.length > 1 && first[0] == '*' &&
  6692. second.length == 0){
  6693. return false;
  6694. }
  6695.  
  6696. if ((first.length > 1 && first[0] == '?') ||
  6697. (first.length != 0 && second.length != 0 &&
  6698. first[0] == second[0])){
  6699. return globMatch(first.substring(1),
  6700. second.substring(1));
  6701. }
  6702.  
  6703. if (first.length > 0 && first[0] == '*'){
  6704. return globMatch(first.substring(1), second) ||
  6705. globMatch(first, second.substring(1));
  6706. }
  6707.  
  6708. return false;
  6709. }
  6710.  
  6711. let pageReady = false;
  6712. function initRules(callback) {
  6713. charset = (document.characterSet || document.charset || document.inputEncoding);
  6714. let equiv = document.querySelector('[http-equiv="Content-Type"]');
  6715. if (equiv && equiv.content) {
  6716. let innerCharSet = equiv.content.match(/charset\=([^;]+)/);
  6717. if (!innerCharSet) {
  6718. charsetValid = false;
  6719. } else if (innerCharSet[1].replace("-", "").toLowerCase() != charset.replace("-", "").toLowerCase()) {
  6720. charsetValid = false;
  6721. }
  6722. } else charsetValid = false;
  6723. storage.getItem("rulesData", data => {
  6724. /*0 wedata格式,1 pagetual格式*/
  6725. ruleUrls = [{
  6726. id: 1,
  6727. url: data && data.wedata2github ? 'https://hoothin.github.io/UserScripts/Pagetual/items_all.json' : 'http://wedata.net/databases/AutoPagerize/items_all.json',
  6728. type: 0,
  6729. }];
  6730. if (data) {
  6731. rulesData = data;
  6732. if (data.urls) ruleUrls = ruleUrls.concat(data.urls);
  6733. if (data.sort) {
  6734. let urls = [];
  6735. data.sort.forEach(id => {
  6736. for (let s = 0; s < ruleUrls.length; s++) {
  6737. if (id == ruleUrls[s].id) {
  6738. urls.push(ruleUrls[s]);
  6739. break;
  6740. }
  6741. }
  6742. });
  6743. ruleUrls = urls;
  6744. }
  6745. }
  6746. if (rulesData.lang) {
  6747. setLang(rulesData.lang);
  6748. }
  6749. if (rulesData.firstRun) {
  6750. rulesData.firstRun = false;
  6751. storage.setItem("rulesData", rulesData);
  6752. setTimeout(() => {
  6753. storage.getItem("rulesData", data => {
  6754. if (data.firstRun === false) {
  6755. _GM_openInTab(firstRunPage, {active: true});
  6756. }
  6757. });
  6758. }, 100);
  6759. }
  6760. _GM_registerMenuCommand(i18n("configure"), () => {
  6761. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  6762. });
  6763. if (rulesData.blacklist && rulesData.blacklist.length > 0) {
  6764. let href = location.href.slice(0, 500);
  6765. let commentStart = false;
  6766. for (let i = 0; i < rulesData.blacklist.length; i++) {
  6767. let curGlob = rulesData.blacklist[i];
  6768. if (!curGlob) continue;
  6769. if (curGlob.indexOf("//") == 0) continue;
  6770. if (commentStart) {
  6771. if (/\*\/$/.test(curGlob)) {
  6772. commentStart = false;
  6773. }
  6774. continue;
  6775. }
  6776. if (curGlob.indexOf("/*") == 0) {
  6777. commentStart = true;
  6778. continue;
  6779. }
  6780. if (curGlob.indexOf("/") == 0) {
  6781. let regMatch = curGlob.match(/^\/(.*)\/(\w*)$/);
  6782. if (regMatch && new RegExp(regMatch[1], regMatch[2]).test(href)) {
  6783. forceState == 1;
  6784. return;
  6785. }
  6786. } else if (globMatch(curGlob, href)) {
  6787. forceState == 1;
  6788. return;
  6789. }
  6790. }
  6791. }
  6792. _GM_registerMenuCommand(i18n("editCurrent"), () => {
  6793. picker.start();
  6794. });
  6795. ruleParser.initSavedRules(async () => {
  6796. let upBtnImg = rulesData.upBtnImg, downBtnImg = rulesData.downBtnImg, _sideControllerIcon = rulesData.sideControllerIcon;
  6797. if (upBtnImg && downBtnImg) {
  6798. downSvgCSS = downSvgCSS.replace("transform: rotate(180deg);", "");
  6799. } else if (upBtnImg && !downBtnImg) {
  6800. downBtnImg = upBtnImg;
  6801. } else if(downBtnImg && !upBtnImg) {
  6802. upBtnImg = downBtnImg;
  6803. }
  6804. if (upBtnImg) {
  6805. upSvg = /https?:|data/.test(upBtnImg) ? `<img class="pagetual" src="${upBtnImg}"/>` : `<span>${upBtnImg}</span>`;
  6806. }
  6807. if (downBtnImg) {
  6808. downSvg = /https?:|data/.test(downBtnImg) ? `<img class="pagetual" src="${downBtnImg}"/>` : `<span>${downBtnImg}</span>`;
  6809. }
  6810. if (_sideControllerIcon) {
  6811. sideControllerIcon = /https?:|data/.test(_sideControllerIcon) ? `<img class="pagetual" src="${_sideControllerIcon}"/>` : `<span>${_sideControllerIcon}</span>`;
  6812. }
  6813. setLoadingDiv(rulesData.loadingText || i18n("loadingText"));
  6814. if (typeof(rulesData.opacity) == "undefined") {
  6815. rulesData.opacity = 1;
  6816. }
  6817. if (typeof(rulesData.hideBar) == "undefined") {
  6818. rulesData.hideBar = false;
  6819. }
  6820. if (typeof(rulesData.dbClick2Stop) == "undefined") {
  6821. rulesData.dbClick2Stop = true;
  6822. }
  6823. if (typeof(rulesData.enableWhiteList) == "undefined") {
  6824. rulesData.enableWhiteList = false;
  6825. }
  6826. if (typeof(rulesData.enableHistory) == "undefined") {
  6827. rulesData.enableHistory = false;
  6828. }
  6829. if (typeof(rulesData.openInNewTab) == "undefined") {
  6830. rulesData.openInNewTab = false;
  6831. }
  6832. if (typeof(rulesData.enableDebug) == "undefined") {
  6833. rulesData.enableDebug = true;
  6834. }
  6835. if (typeof(rulesData.updateNotification) == "undefined") {
  6836. rulesData.updateNotification = true;
  6837. }
  6838. if (typeof(rulesData.initRun) == "undefined") {
  6839. rulesData.initRun = true;
  6840. }
  6841. if (typeof(rulesData.preload) == "undefined") {
  6842. rulesData.preload = true;
  6843. }
  6844. if (typeof(rulesData.customFirst) == "undefined") {
  6845. rulesData.customFirst = false;
  6846. }
  6847. if (typeof(rulesData.manualMode) == "undefined") {
  6848. rulesData.manualMode = false;
  6849. }
  6850. if (typeof(rulesData.clickMode) == "undefined") {
  6851. rulesData.clickMode = false;
  6852. }
  6853. if (typeof(rulesData.pageBarMenu) == "undefined") {
  6854. rulesData.pageBarMenu = true;
  6855. }
  6856. if (typeof(rulesData.arrowToScroll) == "undefined") {
  6857. rulesData.arrowToScroll = false;
  6858. }
  6859. if (typeof(rulesData.hideLoadingIcon) == "undefined") {
  6860. rulesData.hideLoadingIcon = false;
  6861. }
  6862. if (typeof(rulesData.hideBarArrow) == "undefined") {
  6863. rulesData.hideBarArrow = false;
  6864. }
  6865. if (typeof(rulesData.lastPageTips) == "undefined") {
  6866. rulesData.lastPageTips = true;
  6867. }
  6868. if (typeof(rulesData.rate) == "undefined") {
  6869. rulesData.rate = 1;
  6870. }
  6871. rate = rulesData.rate;
  6872. if (rulesData.autoLoadNum && rulesData.initRun) {
  6873. autoLoadNum = parseInt(rulesData.autoLoadNum);
  6874. }
  6875. openInNewTab = rulesData.openInNewTab ? 1 : 0;
  6876. enableDebug = rulesData.enableDebug;
  6877.  
  6878. let _nextSwitch = await getListData("nextSwitch", location.host);
  6879. if (typeof(_nextSwitch) !== "undefined") {
  6880. nextIndex = _nextSwitch || 0;
  6881. }
  6882.  
  6883. let _forceState = await getListData("forceState", location.host);
  6884. if (typeof(_forceState) == "undefined") {
  6885. _forceState = await getData("forceState_" + location.host);
  6886. }
  6887. if (typeof(_forceState) == "undefined") {
  6888. _forceState = (rulesData.enableWhiteList ? 1 : 0);
  6889. }
  6890. forceState = _forceState;
  6891.  
  6892. autoScroll = await getListData("autoScroll", location.host + location.pathname) || 0;
  6893.  
  6894. updateDate = await getData("ruleLastUpdate");
  6895.  
  6896. let _loadNowNum = await getData("loadNowNum");
  6897. if (typeof(_loadNowNum) != "undefined") {
  6898. loadNowNum = _loadNowNum;
  6899. }
  6900. let _autoScrollRate = await getData("autoScrollRate");
  6901. if (_autoScrollRate) {
  6902. autoScrollRate = _autoScrollRate;
  6903. }
  6904.  
  6905. author = await getData("author") || "";
  6906.  
  6907. manualPause = !!await getListData("pauseState", location.host);
  6908.  
  6909. let href = location.href.slice(0, 100);
  6910. try {
  6911. if (_unsafeWindow.initedPagetual) {
  6912. if (ruleImportUrlReg.test(href)) {
  6913. showTips(i18n('duplicate'));
  6914. }
  6915. return;
  6916. }
  6917. _unsafeWindow.initedPagetual = true;
  6918. } catch(e) {showTips(e)}
  6919. listenUrl();
  6920. _GM_registerMenuCommand(i18n("update"), () => {
  6921. showTips(i18n("beginUpdate"), "", 60000);
  6922. updateRules(() => {
  6923. showTips(i18n("updateSucc"));
  6924. location.reload();
  6925. },(rule, err) => {
  6926. showTips(`Failed to update ${rule.url} rules!`);
  6927. debug(err);
  6928. });
  6929. });
  6930. _GM_registerMenuCommand(i18n(forceState == 1 ? "enable" : "disableSite"), () => {
  6931. if (forceState == 1) {
  6932. forceState = 0;
  6933. showTips(i18n("enableSiteTips"));
  6934. changeStop(false, true);
  6935. } else {
  6936. forceState = 1;
  6937. showTips(i18n("disableSiteTips"));
  6938. changeStop(true, true);
  6939. sideController.remove();
  6940. }
  6941. setListData("forceState", location.host, forceState);
  6942. if (!ruleParser.curSiteRule.url) {
  6943. setTimeout(() => {
  6944. location.reload();
  6945. }, 500);
  6946. }
  6947. });
  6948. _GM_registerMenuCommand(i18n("toggleAutoScroll"), () => {
  6949. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  6950. autoScroll = parseInt(autoScroll) || 0;
  6951. if (autoScroll < 0) autoScroll = 0;
  6952. if (autoScroll && autoScroll != autoScrollRate) {
  6953. autoScrollRate = autoScroll;
  6954. storage.setItem("autoScrollRate", autoScrollRate);
  6955. }
  6956. setListData("autoScroll", location.host + location.pathname, autoScroll);
  6957. startAutoScroll();
  6958. });
  6959. startAutoScroll();
  6960.  
  6961.  
  6962. if (initConfig(href)) {
  6963. document.addEventListener("click", e => {
  6964. if (e.target && typeof e.target.dataset.pagetualPicker !== 'undefined') {
  6965. e.preventDefault();
  6966. e.stopPropagation();
  6967. picker.start();
  6968. }
  6969. });
  6970. return;
  6971. }
  6972. pageReady = true;
  6973. if (forceState == 1) return;
  6974. let now = new Date().getTime();
  6975. if (!updateDate || now - updateDate > 2 * 24 * 60 * 60 * 1000) {
  6976. updateRules(() => {
  6977. }, (rule, err) => {}, true);
  6978. storage.setItem("ruleLastUpdate", now);
  6979. }
  6980. callback();
  6981. });
  6982. });
  6983. }
  6984.  
  6985. let xhrFailed = false;
  6986. function requestDoc(url, callback) {
  6987. let postParams = url.match(/#p{(.*)}$/);
  6988. if (postParams) {
  6989. postParams = postParams[1];
  6990. url = url.replace(/#p{.*/, "");
  6991. }
  6992. let ruleHeaders = ruleParser.curSiteRule.headers;
  6993. let headers = {
  6994. 'Referer': location.href,
  6995. 'User-Agent': navigator.userAgent,
  6996. 'accept': 'text/html,application/xhtml+xml,application/xml',
  6997. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + charset,
  6998. };
  6999. if (ruleHeaders) {
  7000. if (ruleHeaders.referer) {
  7001. headers.referer = ruleHeaders.referer;
  7002. }
  7003. if (ruleHeaders.userAgent) {
  7004. headers.userAgent = ruleHeaders.userAgent;
  7005. }
  7006. if (ruleHeaders.accept) {
  7007. headers.accept = ruleHeaders.accept;
  7008. }
  7009. if (ruleHeaders.contentType) {
  7010. headers.contentType = ruleHeaders.contentType;
  7011. let ruleCharset = ruleHeaders.contentType.match(/charset\=([^;]+)/);
  7012. if (ruleCharset) charset = ruleCharset[1];
  7013. }
  7014. if (ruleHeaders.cookie) {
  7015. headers.cookie = ruleHeaders.cookie;
  7016. }
  7017. }
  7018. _GM_xmlhttpRequest({
  7019. url: url,
  7020. method: postParams ? 'POST' : 'GET',
  7021. data: postParams,
  7022. overrideMimeType: 'text/html;charset=' + charset,
  7023. headers: headers,
  7024. timeout: 50000,
  7025. onload: async function(res) {
  7026. if (isPause) return callback(false);
  7027. var doc = null, response = res.response;
  7028. try {
  7029. doc = document.implementation.createHTMLDocument('');
  7030. doc.documentElement.innerHTML = response;
  7031. } catch (e) {
  7032. debug('parse error:' + e.toString());
  7033. }
  7034. let pageElement = null;
  7035. let preCode = ruleParser.curSiteRule.pagePre;
  7036. if (preCode) {
  7037. try {
  7038. let preResult;
  7039. if (typeof preCode == 'function') {
  7040. preResult = await preCode(response, doc);
  7041. } else if (preCode.length == 2) {
  7042. preResult = response.replace(new RegExp(preCode[0], "gi"), preCode[1]);
  7043. } else {
  7044. preResult = await new AsyncFunction("response", "doc", '"use strict";' + preCode)(response, doc);
  7045. }
  7046. if (typeof preResult !== "undefined") {
  7047. if (typeof preResult === "string") {
  7048. doc.documentElement.innerHTML = preResult;
  7049. } else pageElement = preResult;
  7050. }
  7051. } catch(e) {
  7052. debug(e);
  7053. }
  7054. }
  7055. let base = doc.querySelector("base");
  7056. ruleParser.basePath = (base && base.href) || url;
  7057. if (charsetValid && !ruleHeaders) {
  7058. let equiv = doc.querySelector('[http-equiv="Content-Type"]');
  7059. if (equiv && equiv.content) {
  7060. let innerCharSet = equiv.content.match(/charset\=([^;]+)/);
  7061. if (innerCharSet && innerCharSet[1].replace("-", "").toLowerCase() != charset.replace("-", "").toLowerCase()) {
  7062. charset = innerCharSet[1];
  7063. return requestDoc(url, callback);
  7064. }
  7065. }
  7066. }
  7067. if (pageElement === null) {
  7068. pageElement = ruleParser.getPageElement(doc);
  7069. }
  7070. if ((!pageElement || pageElement.length == 0) && res.status >= 400) {
  7071. debug(res.status + " " + url, "Error status");
  7072. if (!ruleParser.curSiteRule.smart || !xhrFailed) {
  7073. xhrFailed = true;
  7074. return callback(false);
  7075. }
  7076. }
  7077. if (inCors && (!pageElement || pageElement.length == 0) && ruleParser.curSiteRule.smart) {
  7078. let article;
  7079. for (let i = 0; i < mainSel.length; i++) {
  7080. article = doc.querySelectorAll(mainSel[i]);
  7081. if (article && article.length === 1) break;
  7082. }
  7083. if (article && article.length == 1) {
  7084. article = article[0];
  7085. ruleParser.curSiteRule.pageElement = article.nodeName.toLowerCase() + (article.id ? "#" + article.id : "") + (article.className ? "." + article.className.replace(/ /g, ".") : "") + ">*";
  7086. pageElement = article.children;
  7087. } else {
  7088. ruleParser.curSiteRule.pageElement = allOfBody;
  7089. pageElement = ruleParser.getPageElement(doc);
  7090. }
  7091. ruleParser.getInsert(true);
  7092. }
  7093. //只有1的話怕不是圖片哦
  7094. if (pageElement && (pageElement.length > 1 || (pageElement.length == 1 && !compareNodeName(pageElement[0], ["img"])))) {
  7095. await ruleParser.insertPage(doc, pageElement, url, callback, false);
  7096. if (ruleParser.curSiteRule.action == 1) {
  7097. isLoading = true;
  7098. requestFromIframe(url, async (doc, eles) => {
  7099. if (eles) {
  7100. await ruleParser.insertPage(doc, eles, url, callback, true);
  7101. } else isLoading = false;
  7102. });
  7103. } else ruleParser.curSiteRule.action = 0;
  7104. } else if ((ruleParser.curSiteRule.smart || curPage == 1) && !inCors) {
  7105. ruleParser.curSiteRule.action = 1;
  7106. requestFromIframe(url, async (doc, eles) => {
  7107. if (eles) {
  7108. await ruleParser.insertPage(doc, eles, url, callback, true);
  7109. } else isLoading = false;
  7110. });
  7111. } else {
  7112. debug("Stop as no page element");
  7113. ruleParser.noValidContent(url);
  7114. changeStop(true);
  7115. callback(false);
  7116. }
  7117. },
  7118. onerror: function(e) {
  7119. debug(e, "NetError");
  7120. callback(false);
  7121. },
  7122. ontimeout: function(e) {
  7123. debug(e, "NetTimeout");
  7124. callback(false);
  7125. }
  7126. });
  7127. }
  7128.  
  7129. function initPage() {
  7130. ruleParser.initPage(() => {
  7131. if (ruleParser.curSiteRule.autoLoadNum) {
  7132. autoLoadNum = ruleParser.curSiteRule.autoLoadNum;
  7133. }
  7134. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  7135. _GM_registerMenuCommand(i18n("nextSwitch"), () => {
  7136. nextSwitch.start();
  7137. });
  7138. }
  7139. if (ruleParser.nextLinkHref) {
  7140. let isJs = ruleParser.hrefIsJs(ruleParser.nextLinkHref);
  7141. if (!isJs) {
  7142. let inForce = (forceState == 2 || forceState == 3);
  7143. _GM_registerMenuCommand(i18n(inForce ? "cancelForceIframe" : "forceIframe"), () => {
  7144. if (inForce) {
  7145. setListData("forceState", location.host, "");
  7146. } else {
  7147. let _state = ruleParser.curSiteRule.action > 0 || confirm(i18n("forceAllBody")) ? 2 : 3;
  7148. setListData("forceState", location.host, _state);
  7149. }
  7150. setTimeout(() => {
  7151. location.reload();
  7152. }, 500);
  7153. });
  7154. }
  7155. _GM_registerMenuCommand(i18n("loadNow"), () => {
  7156. if (autoLoadNum != -1) {
  7157. autoLoadNum = -1;
  7158. return;
  7159. }
  7160. let loadNum = window.prompt(i18n("loadConfirm"), loadNowNum);
  7161. if (loadNum === "" || loadNum === null) return;
  7162. loadNum = Math.abs(parseInt(loadNum)) || 0;
  7163. if (loadNowNum != loadNum) {
  7164. loadNowNum = loadNum;
  7165. storage.setItem("loadNowNum", loadNowNum);
  7166. }
  7167. autoLoadNum = loadNum;
  7168. nextPage();
  7169. });
  7170. }
  7171. initListener();
  7172. });
  7173. }
  7174.  
  7175. var pageBarStyle, mainStyleEle, mainStyleStyle;
  7176. function initView() {
  7177. if (!mainStyleStyle) {
  7178. mainStyleStyle = `
  7179. .pagetual_pageBar{
  7180. -moz-transition:all 0.3s ease-in-out 0s;
  7181. -webkit-transition:all 0.3s ease-in-out 0s;
  7182. transition:all 0.3s ease-in-out 0s;
  7183. font-family: Arial,sans-serif !important;
  7184. text-align: center !important;
  7185. }
  7186. .pagetual_pageBar.stop {
  7187. -webkit-filter: invert(100%);
  7188. filter: invert(100%);
  7189. opacity: 1!important;
  7190. }
  7191. .pagetual_pageBar.hide {
  7192. display: none!important;
  7193. }
  7194. .pagetual-hide {
  7195. display: none!important;
  7196. }
  7197. .pagetual_pageBar:hover {
  7198. opacity: 1!important;
  7199. box-shadow: 0px 0px 10px 0px #000000aa;
  7200. border-radius: 20px;
  7201. background-color: rgb(240 240 240 / 80%);
  7202. border-color: transparent!important;
  7203. }
  7204. .pagetual_pageBar span {
  7205. vertical-align: super;
  7206. }
  7207. .pagetual_pageBar a::before,
  7208. .pagetual_pageBar a::after {
  7209. content: none;
  7210. }
  7211. .pagetual_pageBar a>span {
  7212. margin-top: 0!important;
  7213. pointer-events: none;
  7214. padding: unset;
  7215. opacity: 0;
  7216. -moz-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  7217. -webkit-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  7218. transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  7219. transform: none;
  7220. left: 0;
  7221. margin-left: calc(50% - 20px);
  7222. }
  7223. .pagetual_pageBar a>span:hover {
  7224. color: red;
  7225. }
  7226. .pagetual_pageBar a:hover>span {
  7227. opacity: 1!important;
  7228. }
  7229. .pagetual_pageBar span.prevScreen,
  7230. .pagetual_pageBar span.nextScreen {
  7231. display: block!important;
  7232. top: unset !important;
  7233. padding: unset !important;
  7234. opacity: 0!important;
  7235. }
  7236. .pagetual_pageBar a:hover>span.prevScreen {
  7237. margin-top: -${rulesData.opacity == 1 ? 31 : 30}px!important;
  7238. pointer-events: all;
  7239. }
  7240. .pagetual_pageBar span.refreshRing {
  7241. position: absolute;
  7242. top: 0;
  7243. opacity: 0;
  7244. height: 30px;
  7245. margin-left: calc(50% - 23px);
  7246. display: block!important;
  7247. }
  7248. .pagetual_pageBar span.refreshRing>svg {
  7249. background: white;
  7250. border-radius: 50%;
  7251. }
  7252. .pagetual_pageBar a:hover>span.refreshRing {
  7253. opacity: 0.3;
  7254. -webkit-animation: pagetual_ring 2.0s infinite linear;
  7255. animation: pagetual_ring 2.0s infinite linear;
  7256. }
  7257. @-webkit-keyframes pagetual_ring {
  7258. 0% { -webkit-transform: rotate(0deg) }
  7259. 100% {
  7260. -webkit-transform: rotate(360deg);
  7261. }
  7262. }
  7263. @keyframes pagetual_ring {
  7264. 0% {
  7265. transform: rotate(0deg);
  7266. -webkit-transform: rotate(0deg);
  7267. } 100% {
  7268. transform: rotate(360deg);
  7269. -webkit-transform: rotate(360deg);
  7270. }
  7271. }
  7272. .pagetual_pageBar a:hover>span.nextScreen {
  7273. margin-top: 30px!important;
  7274. pointer-events: all;
  7275. }
  7276. .pagetual_pageBar span>svg {
  7277. -moz-transition:transform 0.5s ease, opacity 0.3s ease;
  7278. -webkit-transition:transform 0.5s ease, opacity 0.3s ease;
  7279. transition:transform 0.5 ease, opacity 0.3s ease;
  7280. opacity: 0;
  7281. }
  7282. .pagetual_pageBar.stop span>svg{
  7283. opacity: 1;
  7284. }
  7285. .pagetual_pageBar.stop span>svg>path{
  7286. transform: scale(.8);
  7287. transform-origin: center;
  7288. -moz-transition:transform 0.3s ease;
  7289. -webkit-transition:transform 0.3s ease;
  7290. transition:transform 0.3 ease;
  7291. }
  7292. .pagetual_pageBar.stop:hover span>svg>path{
  7293. transform: unset;
  7294. }
  7295. .pagetual_pageBar:hover span>svg {
  7296. opacity: 1;
  7297. }
  7298. .pagetual_pageBar span>svg.upSvg:hover {
  7299. transform: rotate(360deg) scale3d(1.2, 1.2, 1.2);
  7300. }
  7301. .pagetual_pageBar span>svg.downSvg:hover {
  7302. transform: rotate(540deg) scale3d(1.2, 1.2, 1.2)!important;
  7303. }
  7304. .pagetual_pageBar .pagetual_pageNum{
  7305. color: #55555f;
  7306. }
  7307. .pagetual_pageBar .pagetual_pageNum:hover{
  7308. color: #ff6464;
  7309. }
  7310. .pagetual_tipsWords {
  7311. font-size: 50px;
  7312. font-weight: bold;
  7313. font-family: "黑体", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
  7314. "Oxygen", "Ubuntu", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
  7315. "Segoe UI Emoji", "Segoe UI Symbol";
  7316. color: #ffffff;
  7317. min-height: 70px;
  7318. max-width: 80%;
  7319. line-height: 1.5;
  7320. position: fixed;
  7321. left: 50%;
  7322. top: 10%;
  7323. margin-left: -99999px;
  7324. padding: 0 15px;
  7325. z-index: 2147483647;
  7326. background-color: #000;
  7327. border: 1px solid #303030;
  7328. border-radius: 10px;
  7329. opacity: 0;
  7330. filter: alpha(opacity=65);
  7331. box-shadow: 5px 5px 20px 0px #000;
  7332. -moz-transition:opacity 0.3s ease-in-out 0s;
  7333. -webkit-transition:opacity 0.3s ease-in-out 0s;
  7334. transition:opacity 0.3s ease-in-out 0s;
  7335. pointer-events: none;
  7336. word-break: break-all;
  7337. }
  7338. .pagetual_tipsWords>a {
  7339. color: #ffffff;
  7340. }
  7341. .pagetual_loading {
  7342. width: 50px;
  7343. height: 50px;
  7344. margin: 10px auto;
  7345. border-radius: 100%;
  7346. display: flex;
  7347. -webkit-animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  7348. animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  7349. }
  7350. @-webkit-keyframes pagetual_loading_scaleout {
  7351. 0% { -webkit-transform: scale(0.0) }
  7352. 100% {
  7353. -webkit-transform: scale(1.0);
  7354. opacity: 0;
  7355. }
  7356. }
  7357. @keyframes pagetual_loading_scaleout {
  7358. 0% {
  7359. transform: scale(0.0);
  7360. -webkit-transform: scale(0.0);
  7361. } 100% {
  7362. transform: scale(1.0);
  7363. -webkit-transform: scale(1.0);
  7364. opacity: 0;
  7365. }
  7366. }
  7367. .pagetual_loading_text {
  7368. white-space: nowrap;
  7369. -webkit-animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  7370. animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  7371. }
  7372. @-webkit-keyframes pagetual_loading_opacity {
  7373. 0% { opacity: 1 }
  7374. 50% { opacity: 0.2 }
  7375. 100% { opacity: 1 }
  7376. }
  7377. @keyframes pagetual_loading_opacity {
  7378. 0% { opacity: 1 }
  7379. 50% { opacity: 0.2 }
  7380. 100% { opacity: 1 }
  7381. }
  7382. `;
  7383. pageBarStyle = `overflow: visible;text-indent: initial;vertical-align: super;line-height:1;opacity:${rulesData.opacity};display:${rulesData.opacity == 0 ? "none" : "inline-flex"};padding:0;font-size: 30px;visibility: visible; position: relative; width: auto; max-width: 100vw; height: 30px; float: none; clear: both; margin: 5px auto; text-align: center;justify-content: center;box-sizing: content-box;${rulesData.opacity == 1 ? "border-top: 1px solid rgb(80, 80, 80);" : "box-shadow: 0px 0px 10px 0px #000000aa;border-radius: 20px;background-color: rgb(240 240 240 / 80%);"}`;
  7384. }
  7385. if (!mainStyleEle || !mainStyleEle.parentNode) {
  7386. mainStyleEle = _GM_addStyle(mainStyleStyle);
  7387. }
  7388. }
  7389. var loadingDiv = document.createElement("div");
  7390. if (loadingDiv.style) loadingDiv.style.cssText = "text-indent: initial;cy: initial;d: initial;dominant-baseline: initial;empty-cells: initial;fill: initial;fill-opacity: initial;fill-rule: initial;filter: initial;flex: initial;flex-flow: initial;float: initial;flood-color: initial;flood-opacity: initial;grid: initial;grid-area: initial;height: initial;hyphens: initial;image-orientation: initial;image-rendering: initial;inline-size: initial;inset-block: initial;inset-inline: initial;isolation: initial;letter-spacing: initial;lighting-color: initial;line-break: initial;list-style: initial;margin-block: initial;margin: 0px auto;margin-inline: initial;marker: initial;mask: initial;mask-type: initial;max-block-size: initial;max-height: initial;max-inline-size: initial;max-width: initial;min-block-size: initial;min-height: initial;min-inline-size: initial;min-width: initial;mix-blend-mode: initial;object-fit: initial;object-position: initial;offset: initial;opacity: initial;order: initial;origin-trial-test-property: initial;orphans: initial;outline: initial;outline-offset: initial;overflow-anchor: initial;overflow-clip-margin: initial;overflow-wrap: initial;overflow: initial;overscroll-behavior-block: initial;overscroll-behavior-inline: initial;overscroll-behavior: initial;padding-block: initial;padding: initial;padding-inline: initial;page: initial;page-orientation: initial;paint-order: initial;perspective: initial;perspective-origin: initial;pointer-events: initial;position: initial;quotes: initial;r: initial;resize: initial;ruby-position: initial;rx: initial;ry: initial;scroll-behavior: initial;scroll-margin-block: initial;scroll-margin: initial;scroll-margin-inline: initial;scroll-padding-block: initial;scroll-padding: initial;scroll-padding-inline: initial;scroll-snap-align: initial;scroll-snap-stop: initial;scroll-snap-type: initial;scrollbar-gutter: initial;shape-image-threshold: initial;shape-margin: initial;shape-outside: initial;shape-rendering: initial;size: initial;speak: initial;stop-color: initial;stop-opacity: initial;stroke: initial;stroke-dasharray: initial;stroke-dashoffset: initial;stroke-linecap: initial;stroke-linejoin: initial;stroke-miterlimit: initial;stroke-opacity: initial;stroke-width: initial;tab-size: initial;table-layout: initial;text-align: initial;text-align-last: initial;text-anchor: initial;text-combine-upright: initial;text-decoration: initial;text-decoration-skip-ink: initial;text-indent: initial;text-overflow: initial;text-shadow: initial;text-size-adjust: initial;text-transform: initial;text-underline-offset: initial;text-underline-position: initial;touch-action: initial;transform: initial;transform-box: initial;transform-origin: initial;transform-style: initial;transition: initial;user-select: initial;vector-effect: initial;vertical-align: initial;visibility: initial;border-spacing: initial;-webkit-border-image: initial;-webkit-box-align: initial;-webkit-box-decoration-break: initial;-webkit-box-direction: initial;-webkit-box-flex: initial;-webkit-box-ordinal-group: initial;-webkit-box-orient: initial;-webkit-box-pack: initial;-webkit-box-reflect: initial;-webkit-highlight: initial;-webkit-hyphenate-character: initial;-webkit-line-break: initial;-webkit-line-clamp: initial;-webkit-mask-box-image: initial;-webkit-mask: initial;-webkit-mask-composite: initial;-webkit-perspective-origin-x: initial;-webkit-perspective-origin-y: initial;-webkit-print-color-adjust: initial;-webkit-rtl-ordering: initial;-webkit-ruby-position: initial;-webkit-tap-highlight-color: initial;-webkit-text-combine: initial;-webkit-text-decorations-in-effect: initial;-webkit-text-emphasis: initial;-webkit-text-emphasis-position: initial;-webkit-text-fill-color: initial;-webkit-text-security: initial;-webkit-text-stroke: initial;-webkit-transform-origin-x: initial;-webkit-transform-origin-y: initial;-webkit-transform-origin-z: initial;-webkit-user-drag: initial;-webkit-user-modify: initial;white-space: initial;widows: initial;width: initial;will-change: initial;word-break: initial;word-spacing: initial;x: initial;y: initial;z-index: 2147483647;";
  7391.  
  7392. const loadingCSS = `font-size: initial; text-indent: unset; display: block; position: initial; margin: auto auto 5px auto; shape-rendering: auto; vertical-align: middle; visibility: visible; width: initial; height: initial; text-align: center; color: #6e6e6e; flex: 0;`;
  7393. function setLoadingDiv(loadingText) {
  7394. loadingDiv.innerHTML = createHTML(`<p class="pagetual_loading_text" style="${loadingCSS}display: inline-block;width: 100%;">${loadingText}</p>${rulesData.hideLoadingIcon ? "" : `<div class="pagetual_loading"><svg width="50" height="50" style="position:relative;cursor: pointer;width: 50px;height: 50px;vertical-align: middle;fill: currentColor;overflow: hidden;" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M296 440c-44.1 0-80 35.9-80 80s35.9 80 80 80 80-35.9 80-80-35.9-80-80-80z" style="fill: #6e6e6e;" fill="#6e6e6e"></path><path d="M960 512c0-247-201-448-448-448S64 265 64 512c0 1.8 0.1 3.5 0.1 5.3 0 0.9-0.1 1.8-0.1 2.7h0.2C68.5 763.3 267.7 960 512 960c236.2 0 430.1-183.7 446.7-415.7 0.1-0.8 0.1-1.6 0.2-2.3 0.4-4.6 0.5-9.3 0.7-13.9 0.1-2.7 0.4-5.3 0.4-8h-0.2c0-2.8 0.2-5.4 0.2-8.1z m-152 8c0 44.1-35.9 80-80 80s-80-35.9-80-80 35.9-80 80-80 80 35.9 80 80zM512 928C284.4 928 99 744.3 96.1 517.3 97.6 408.3 186.6 320 296 320c110.3 0 200 89.7 200 200 0 127.9 104.1 232 232 232 62.9 0 119.9-25.2 161.7-66-66 142.7-210.4 242-377.7 242z" style="fill: #6e6e6e;" fill="#6e6e6e"></path></svg></div>`}`);
  7395. }
  7396.  
  7397. var upSvg = `<svg width="30" height="30" class="upSvg pagetual" style="display:initial;position:relative;cursor: pointer;margin: 0 8px;width: 30px;height: 30px;vertical-align: baseline;fill: currentColor;overflow: hidden;" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M296 440c-44.1 0-80 35.9-80 80s35.9 80 80 80 80-35.9 80-80-35.9-80-80-80z" style="fill: #604b4a;" fill="#604b4a"></path><path d="M960 512c0-247-201-448-448-448S64 265 64 512c0 1.8 0.1 3.5 0.1 5.3 0 0.9-0.1 1.8-0.1 2.7h0.2C68.5 763.3 267.7 960 512 960c236.2 0 430.1-183.7 446.7-415.7 0.1-0.8 0.1-1.6 0.2-2.3 0.4-4.6 0.5-9.3 0.7-13.9 0.1-2.7 0.4-5.3 0.4-8h-0.2c0-2.8 0.2-5.4 0.2-8.1z m-152 8c0 44.1-35.9 80-80 80s-80-35.9-80-80 35.9-80 80-80 80 35.9 80 80zM512 928C284.4 928 99 744.3 96.1 517.3 97.6 408.3 186.6 320 296 320c110.3 0 200 89.7 200 200 0 127.9 104.1 232 232 232 62.9 0 119.9-25.2 161.7-66-66 142.7-210.4 242-377.7 242z" style="fill: #604b4a;" fill="#604b4a"></path></svg>`;
  7398. var upSvgCSS = `text-align: center;display: initial;position: relative;cursor: pointer;margin: 0 8px;width: 30px;height: 30px;vertical-align: baseline;fill: currentColor;overflow: hidden;`;
  7399. var downSvg = `<svg width="30" height="30" class="downSvg pagetual" style="display:initial;position:relative;cursor: pointer;margin: 0 8px;width: 30px;height: 30px;vertical-align: baseline;fill: currentColor;overflow: hidden;transform: rotate(180deg);" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M296 440c-44.1 0-80 35.9-80 80s35.9 80 80 80 80-35.9 80-80-35.9-80-80-80z" style="fill: #604b4a;" fill="#604b4a"></path><path d="M960 512c0-247-201-448-448-448S64 265 64 512c0 1.8 0.1 3.5 0.1 5.3 0 0.9-0.1 1.8-0.1 2.7h0.2C68.5 763.3 267.7 960 512 960c236.2 0 430.1-183.7 446.7-415.7 0.1-0.8 0.1-1.6 0.2-2.3 0.4-4.6 0.5-9.3 0.7-13.9 0.1-2.7 0.4-5.3 0.4-8h-0.2c0-2.8 0.2-5.4 0.2-8.1z m-152 8c0 44.1-35.9 80-80 80s-80-35.9-80-80 35.9-80 80-80 80 35.9 80 80zM512 928C284.4 928 99 744.3 96.1 517.3 97.6 408.3 186.6 320 296 320c110.3 0 200 89.7 200 200 0 127.9 104.1 232 232 232 62.9 0 119.9-25.2 161.7-66-66 142.7-210.4 242-377.7 242z" style="fill: #604b4a;" fill="#604b4a"></path></svg>`;
  7400. var downSvgCSS = `text-align: center;display: initial;position: relative;cursor: pointer;margin: 0 8px;width: 30px;height: 30px;vertical-align: baseline;fill: currentColor;overflow: hidden;transform: rotate(180deg);`;
  7401.  
  7402. const initStyle = `text-indent: initial;display: contents;right: unset;left: unset;top: unset;bottom: unset;inset: unset;clear: both;cy: initial;d: initial;dominant-baseline: initial;empty-cells: initial;fill: initial;fill-opacity: initial;fill-rule: initial;filter: initial;flex: initial;flex-flow: initial;float: initial;flood-color: initial;flood-opacity: initial;grid: initial;grid-area: initial;height: initial;hyphens: initial;image-orientation: initial;image-rendering: initial;inline-size: initial;inset-block: initial;inset-inline: initial;isolation: initial;letter-spacing: initial;lighting-color: initial;line-break: initial;list-style: initial;margin-block: initial;margin: 0px 5px;margin-inline: initial;marker: initial;mask: initial;mask-type: initial;max-block-size: initial;max-height: initial;max-inline-size: initial;max-width: initial;min-block-size: initial;min-height: initial;min-inline-size: initial;min-width: initial;mix-blend-mode: initial;object-fit: initial;object-position: initial;offset: initial;opacity: initial;order: initial;orphans: initial;outline: initial;outline-offset: initial;overflow-anchor: initial;overflow-clip-margin: initial;overflow-wrap: initial;overflow: initial;overscroll-behavior-block: initial;overscroll-behavior-inline: initial;overscroll-behavior: initial;padding-block: initial;padding: initial;padding-inline: initial;page: initial;page-orientation: initial;paint-order: initial;perspective: initial;perspective-origin: initial;pointer-events: initial;position: relative;quotes: initial;r: initial;resize: initial;ruby-position: initial;rx: initial;ry: initial;scroll-behavior: initial;scroll-margin-block: initial;scroll-margin: initial;scroll-margin-inline: initial;scroll-padding-block: initial;scroll-padding: initial;scroll-padding-inline: initial;scroll-snap-align: initial;scroll-snap-stop: initial;scroll-snap-type: initial;scrollbar-gutter: initial;shape-image-threshold: initial;shape-margin: initial;shape-outside: initial;shape-rendering: initial;size: initial;speak: initial;stop-color: initial;stop-opacity: initial;stroke: initial;stroke-dasharray: initial;stroke-dashoffset: initial;stroke-linecap: initial;stroke-linejoin: initial;stroke-miterlimit: initial;stroke-opacity: initial;stroke-width: initial;tab-size: initial;table-layout: initial;text-align: initial;text-align-last: initial;text-anchor: initial;text-combine-upright: initial;text-decoration: initial;text-decoration-skip-ink: initial;text-indent: initial;text-overflow: initial;text-shadow: initial;text-size-adjust: initial;text-transform: initial;text-underline-offset: initial;text-underline-position: initial;touch-action: initial;transform: initial;transform-box: initial;transform-origin: initial;transform-style: initial;transition: initial;user-select: initial;vector-effect: initial;vertical-align: initial;visibility: initial;border-spacing: initial;-webkit-border-image: initial;-webkit-box-align: initial;-webkit-box-decoration-break: initial;-webkit-box-direction: initial;-webkit-box-flex: initial;-webkit-box-ordinal-group: initial;-webkit-box-orient: initial;-webkit-box-pack: initial;-webkit-box-reflect: initial;-webkit-highlight: initial;-webkit-hyphenate-character: initial;-webkit-line-break: initial;-webkit-line-clamp: initial;-webkit-mask-box-image: initial;-webkit-mask: initial;-webkit-mask-composite: initial;-webkit-perspective-origin-x: initial;-webkit-perspective-origin-y: initial;-webkit-print-color-adjust: initial;-webkit-rtl-ordering: initial;-webkit-ruby-position: initial;-webkit-tap-highlight-color: initial;-webkit-text-combine: initial;-webkit-text-decorations-in-effect: initial;-webkit-text-emphasis: initial;-webkit-text-emphasis-position: initial;-webkit-text-fill-color: initial;-webkit-text-security: initial;-webkit-text-stroke: initial;-webkit-transform-origin-x: initial;-webkit-transform-origin-y: initial;-webkit-transform-origin-z: initial;-webkit-user-drag: initial;-webkit-user-modify: initial;white-space: initial;widows: initial;width: initial;will-change: initial;word-break: initial;word-spacing: initial;x: initial;y: initial;`;
  7403. const pageTextStyle = `opacity: 1!important;text-indent: initial;padding: unset;border: none;background: unset!important;line-height: 30px;text-decoration: none;user-select: none;visibility: visible;position: initial;width: auto;max-width: 80%; white-space: nowrap; text-overflow: ellipsis;overflow: hidden;height: auto;float: none;clear: both;margin: 0px;text-align: center;display: inline-block;font-weight: bold;font-style: normal;font-size: 16px;letter-spacing: initial;vertical-align: top;color: rgb(85, 85, 95)!important;`;
  7404. var sideControllerIcon = '';
  7405.  
  7406. var tipsWords = document.createElement("div");
  7407. tipsWords.className = "pagetual_tipsWords";
  7408.  
  7409. function changeStop(stop, save) {
  7410. isPause = stop;
  7411. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar,#pagetual-sideController"), bar => {
  7412. if (isPause) {
  7413. bar.classList.add("stop");
  7414. } else {
  7415. bar.classList.remove("stop");
  7416. }
  7417. });
  7418. if (!isPause) ruleParser.showAddedElements();
  7419. manualPause = isPause;
  7420. if (save && sideController.inited) setListData("pauseState", location.host, isPause ? true : "");
  7421. }
  7422.  
  7423. function changeHideBar(hide) {
  7424. isHideBar = hide;
  7425. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar"), bar => {
  7426. if (isHideBar) {
  7427. bar.classList.add("hide");
  7428. } else {
  7429. bar.classList.remove("hide");
  7430. }
  7431. });
  7432. }
  7433.  
  7434. function isInViewPort(element) {
  7435. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  7436. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  7437. const {
  7438. top,
  7439. right,
  7440. bottom,
  7441. left,
  7442. } = element.getBoundingClientRect();
  7443.  
  7444. return (
  7445. top >= 0 &&
  7446. left >= 0 &&
  7447. right <= viewWidth + 1 &&
  7448. top <= viewHeight * rate &&
  7449. isVisible(element, _unsafeWindow)
  7450. );
  7451. }
  7452.  
  7453. function getPageBar() {
  7454. let preBar = null, nextBar = null;
  7455. let pageBars = [].slice.call(document.querySelectorAll(".pagetual_pageBar"));
  7456. for (let i = 0; i < pageBars.length; i++) {
  7457. let pageBar = pageBars[i];
  7458. if (!pageBar || !getBody(document).contains(pageBar)) continue;
  7459. let {
  7460. top,
  7461. right,
  7462. bottom,
  7463. left,
  7464. } = pageBar.getBoundingClientRect();
  7465. if (top > 500) {
  7466. nextBar = pageBar;
  7467. preBar = (i - 1 >= 0 ? pageBars[i - 1] : null);
  7468. if (pageBar && getBody(document).contains(pageBar)) {
  7469. let {
  7470. top,
  7471. right,
  7472. bottom,
  7473. left,
  7474. } = pageBar.getBoundingClientRect();
  7475. if (top < -500) {
  7476. preBar = pageBar;
  7477. } else preBar = (i - 2 >= 0 ? pageBars[i - 2] : null);
  7478. }
  7479. break;
  7480. }
  7481. }
  7482. if (!nextBar) preBar = pageBars[pageBars.length - 2];
  7483. return {preBar: preBar, nextBar: nextBar};
  7484. }
  7485.  
  7486. var urlChanged = false;
  7487. var urlChanging = false;
  7488. var urlchangeHandler = e => {
  7489. if (ruleParser && ruleParser.curSiteRule && ruleParser.curSiteRule.listenUrlChange == false) return;
  7490. isPause = true;
  7491. setTimeout(() => {
  7492. lastActiveUrl = location.href;
  7493. if (urlChanging) return;
  7494. urlChanging = true;
  7495. let href = location.href.slice(0, 60);
  7496. if (href == configPage[1]) {
  7497. setTimeout(() => {
  7498. initConfig(href);
  7499. urlChanging = false;
  7500. }, 1000);
  7501. } else {
  7502. setTimeout(() => {
  7503. if (guidePage.test(href)) {
  7504. setTimeout(() => {
  7505. initConfig(href);
  7506. urlChanging = false;
  7507. }, 1000);
  7508. } else {
  7509. ruleParser.urlChanged();
  7510. if (!ruleParser.nextLinkHref) {
  7511. isLoading = false;
  7512. }
  7513. urlChanging = false;
  7514. //if (!pageReady && !ruleImportUrlReg.test(href)) location.reload();
  7515. }
  7516. }, 500);
  7517. }
  7518. }, 1);
  7519. };
  7520. window.addEventListener('pagetual_pushState', urlchangeHandler);
  7521. /*var _wr = function(type) {
  7522. var orig = history[type];
  7523. return function() {
  7524. var rv = orig.apply(this, arguments);
  7525. var e = new Event('pagetual_' + type);
  7526. e.arguments = arguments;
  7527. window.dispatchEvent(e);
  7528. return rv;
  7529. };
  7530. };
  7531. history.pushState = _wr('pushState');*/
  7532.  
  7533. function listenUrl() {
  7534. var prevPathname = window.location.pathname;
  7535. var prevSearch = window.location.search;
  7536. var checkUrlTime = 100;
  7537. var checkUrlTimer;
  7538. var checkClickedEle = null;
  7539. var checkFunc = () => {
  7540. if (forceState == 1) return;
  7541. if (checkClickedEle) {
  7542. if (!clickedSth && checkClickedEle && checkClickedEle.nodeName) {
  7543. if (compareNodeName(checkClickedEle, ["a", "button"])) {
  7544. clickedSth = true;
  7545. } else {
  7546. let targetStyle = _unsafeWindow.getComputedStyle(checkClickedEle);
  7547. if (targetStyle.cursor == "pointer") clickedSth = true;
  7548. }
  7549. }
  7550. checkClickedEle = null;
  7551. }
  7552. if (checkUrlTime < 5000) {
  7553. checkUrlTime += checkUrlTime>>1;
  7554. }
  7555. clearTimeout(checkUrlTimer);
  7556. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7557. if (document.hidden) return;
  7558. if (!ruleParser.canListenUrlChange()) {
  7559. return;
  7560. }
  7561. if ((prevPathname !== window.location.pathname || prevSearch !== window.location.search) && window.location.href != ruleParser.historyUrl) {
  7562. checkUrlTime = 2000;
  7563. urlWillChange = true;
  7564. var e = new Event('pagetual_pushState');
  7565. e.arguments = arguments;
  7566. window.dispatchEvent(e);
  7567. clickedSth = false;
  7568. }
  7569. prevPathname = window.location.pathname;
  7570. prevSearch = window.location.search;
  7571. };
  7572. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7573.  
  7574. document.addEventListener("click", e => {
  7575. if (!checkClickedEle) {
  7576. checkClickedEle = e.target;
  7577. checkUrlTime = 300;
  7578. clearTimeout(checkUrlTimer);
  7579. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7580. }
  7581. });
  7582. }
  7583.  
  7584. let scrollContainer;
  7585. function distToBottom () {
  7586. let scrolly = window.scrollY;
  7587. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  7588. if (!scrollContainer || !document.documentElement.contains(scrollContainer)) {
  7589. if (curPage > 1 || ruleParser.nextLinkHref) {
  7590. let pageEle = ruleParser.getPageElement(document);
  7591. if (pageEle && pageEle.length) {
  7592. let parent = pageEle[0].parentNode, pageScrollY = parent.scrollTop;
  7593. while (parent && pageScrollY == 0) {
  7594. parent = parent.parentNode;
  7595. pageScrollY = parent.scrollTop;
  7596. }
  7597. if (pageScrollY) {
  7598. scrollContainer = parent;
  7599. return scrollContainer.scrollHeight - pageScrollY - windowHeight;
  7600. }
  7601. }
  7602. }
  7603. }
  7604. if (scrollContainer) {
  7605. return scrollContainer.scrollHeight - scrollContainer.scrollTop - windowHeight;
  7606. }
  7607.  
  7608. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7609. return scrollH - scrolly - windowHeight;
  7610. }
  7611.  
  7612. let scrollHandler, clickToResetHandler, dblclickHandler, keydownHandler, hashchangeHandler, manualModeKeyHandler, pagetualNextHandler, keyupHandler, messageHandler;
  7613. function initListener () {
  7614. document.removeEventListener('scroll', scrollHandler, true);
  7615. document.removeEventListener('wheel', scrollHandler, true);
  7616. document.removeEventListener('dblclick', dblclickHandler);
  7617. document.removeEventListener('keydown', keydownHandler);
  7618. window.removeEventListener('hashchange', hashchangeHandler, false);
  7619. document.removeEventListener('keydown', manualModeKeyHandler);
  7620. document.removeEventListener('pagetual.next', pagetualNextHandler, false);
  7621. document.removeEventListener('keyup', keyupHandler);
  7622. _unsafeWindow.removeEventListener('message', messageHandler, true);
  7623. let loadmoreBtn, loadingMore = true, lastScroll = 0, checkLoadMoreTimes = 0, loadMoreInv;
  7624. if (ruleParser.curSiteRule.smart) {
  7625. loadingMore = false;
  7626. } else if (ruleParser.curSiteRule.loadMore) {
  7627. loadingMore = false;
  7628. }
  7629. clickMode = typeof ruleParser.curSiteRule.clickMode == 'undefined' ? rulesData.clickMode : ruleParser.curSiteRule.clickMode;
  7630. let clickingNext = false;
  7631. let clickNext = async () => {
  7632. if (clickingNext) return;
  7633. clickingNext = true;
  7634. setTimeout(() => {
  7635. clickingNext = false;
  7636. }, 1500);
  7637. let nextLink = ruleParser.nextLinkHref;
  7638. if (!nextLink) return;
  7639. let isJs = ruleParser.hrefIsJs(nextLink);
  7640. if (isJs) {
  7641. let nextBtn = ruleParser.nextLinkEle;
  7642. if (!nextBtn || !nextBtn.offsetParent) nextBtn = await ruleParser.getNextLink(document, true);
  7643. if (nextBtn) emuClick(nextBtn);
  7644. } else {
  7645. window.location.href = nextLink;
  7646. }
  7647. };
  7648. let checkScrollReach = () => {
  7649. let dist = distToBottom();
  7650. if (clickMode) {
  7651. if (dist < 10) {
  7652. clickNext();
  7653. }
  7654. } else if (dist < bottomGap) {
  7655. nextPage();
  7656. }
  7657. };
  7658. messageHandler = e => {
  7659. if (e.data.command === 'pagetual') {
  7660. let action = e.data.action;
  7661. let detail = e.data.detail;
  7662. switch (action) {
  7663. case "config":
  7664. if (!detail || typeof detail !== 'object') return;
  7665. rulesData = {
  7666. ...rulesData,
  7667. ...detail
  7668. }
  7669. storage.setItem("rulesData", rulesData);
  7670. break;
  7671. case "nextPage":
  7672. if (detail === "" || detail === null) return;
  7673. detail = parseInt(detail) || 0;
  7674. if (loadNowNum != detail) {
  7675. loadNowNum = detail;
  7676. }
  7677. autoLoadNum = detail;
  7678. nextPage();
  7679. break;
  7680. case "loadMore":
  7681. clearInterval(loadMoreInv);
  7682. if (detail === -1) return;
  7683. loadmoreBtn = getLoadMore(document, loadmoreBtn);
  7684. loadmoreBtn && emuClick(loadmoreBtn);
  7685. if (detail === 0) {
  7686. loadMoreInv = setInterval(() => {
  7687. loadmoreBtn = getLoadMore(document, loadmoreBtn);
  7688. loadmoreBtn && emuClick(loadmoreBtn);
  7689. }, 500);
  7690. }
  7691. break;
  7692. }
  7693. }
  7694. return true;
  7695. }
  7696. _unsafeWindow.addEventListener('message', messageHandler, true);
  7697. scrollHandler = e => {
  7698. if (urlChanged && !isLoading) {
  7699. ruleParser.initPage(() => {});
  7700. urlChanged = false;
  7701. loadingMore = false;
  7702. return;
  7703. }
  7704. if (isPause) return;
  7705. if (!loadingMore) {
  7706. loadmoreBtn = getLoadMore(document, loadmoreBtn);
  7707. if (loadmoreBtn) {
  7708. if (isInViewPort(loadmoreBtn)) {
  7709. emuClick(loadmoreBtn);
  7710. loadingMore = true;
  7711. setTimeout(() => {loadingMore = false}, 200);
  7712. }
  7713. } else {
  7714. loadingMore = true;
  7715. if (!ruleParser.curSiteRule.smart || checkLoadMoreTimes++ < 3) {
  7716. setTimeout(() => {loadingMore = false}, 200);
  7717. }
  7718. }
  7719. }
  7720. if (!isLoading && !stopScroll) {
  7721. checkScrollReach();
  7722. }
  7723. ruleParser.changeVisibility();
  7724. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  7725. if (ruleParser.curSiteRule.lockScroll) {
  7726. if (isLoading && Math.abs(lastScroll - curScroll) > 350) {
  7727. getBody(document).scrollTop = lastScroll;
  7728. document.documentElement.scrollTop = lastScroll;
  7729. } else {
  7730. lastScroll = curScroll;
  7731. }
  7732. }
  7733. if (targetY >= 0) {
  7734. if (Math.abs(targetY - curScroll) < 100) {
  7735. targetY = -1;
  7736. }
  7737. }
  7738. };
  7739. dblclickHandler = e => {
  7740. if (forceState == 1 || compareNodeName(e.target, ["input", "textarea", "select", "a", "button", "svg", "use", "img", "path"])) return;
  7741. if (!rulesData.dbClick2StopKey) {
  7742. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  7743. (rulesData.dbClick2StopAlt && !e.altKey) ||
  7744. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  7745. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  7746. return;
  7747. }
  7748. }
  7749. if (!compareNodeName(e.target, ["body"]) && !e.target.classList.contains('pagetual_pageBar')) {
  7750. try {
  7751. let selection = window.getSelection();
  7752. let selStr = selection.toString().trim();
  7753. if (!selStr) {
  7754. selection = selection.getRangeAt(0);
  7755. selStr = selection && selection.cloneContents().children[0];
  7756. if (selStr && !compareNodeName(selStr, ["img"])) selStr = false;
  7757. }
  7758. if (selStr) {
  7759. return;
  7760. }
  7761. } catch (e) {}
  7762. }
  7763. if (rulesData.dbClick2Stop && (ruleParser.nextLinkHref || loadmoreBtn)) {
  7764. setTimeout(() => {
  7765. if (rulesData.hideBarButNoStop || rulesData.hideBar) {
  7766. changeHideBar(!isHideBar);
  7767. }
  7768. if (!rulesData.hideBarButNoStop) {
  7769. changeStop(!isPause, true);
  7770. showTips(i18n(isPause ? "disable" : "enable"));
  7771. }
  7772. if (!isPause) {
  7773. checkScrollReach();
  7774. }
  7775. }, 10);
  7776. }
  7777. };
  7778. document.addEventListener('dblclick', dblclickHandler);
  7779. clickToResetHandler = e => {
  7780. if (!ruleParser.nextLinkHref) isLoading = false;
  7781. };
  7782. document.addEventListener('click', clickToResetHandler);
  7783. if (rulesData.dbClick2StopKey) {
  7784. keydownHandler = e => {
  7785. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  7786. (rulesData.dbClick2StopAlt && !e.altKey) ||
  7787. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  7788. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  7789. return;
  7790. }
  7791. if (document.activeElement &&
  7792. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  7793. document.activeElement.contentEditable == 'true')) {
  7794. return;
  7795. }
  7796. var key = e.key.toLowerCase();
  7797. if (rulesData.dbClick2StopKey.toLowerCase() == key) {
  7798. if (forceState == 1) {
  7799. forceState = 0;
  7800. showTips(i18n("enableSiteTips"));
  7801. changeStop(false, true);
  7802. } else {
  7803. forceState = 1;
  7804. showTips(i18n("disableSiteTips"));
  7805. changeStop(true, true);
  7806. sideController.remove();
  7807. }
  7808. if (!ruleParser.curSiteRule.url) {
  7809. setListData("forceState", location.host, forceState);
  7810. setTimeout(() => {
  7811. location.reload();
  7812. }, 500);
  7813. }
  7814. }
  7815. };
  7816. document.addEventListener('keydown', keydownHandler);
  7817. }
  7818. if (ruleParser.curSiteRule.listenHashChange) {
  7819. hashchangeHandler = () => {
  7820. isPause = true;
  7821. ruleParser.urlChanged();
  7822. if (!ruleParser.nextLinkHref) isLoading = false;
  7823. };
  7824. window.addEventListener('hashchange', hashchangeHandler, false);
  7825. }
  7826. let manualMode = typeof ruleParser.curSiteRule.manualMode == 'undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode;
  7827. if (manualMode) {
  7828. manualModeKeyHandler = e => {
  7829. if (document.activeElement &&
  7830. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  7831. document.activeElement.contentEditable == 'true')) {
  7832. return;
  7833. }
  7834. if (e.keyCode == 39) {
  7835. clickNext();
  7836. } else if (e.keyCode == 37) {
  7837. history.back();
  7838. }
  7839. };
  7840. document.addEventListener('keydown', manualModeKeyHandler);
  7841. pagetualNextHandler = () => {
  7842. clickNext();
  7843. };
  7844. document.addEventListener('pagetual.next', pagetualNextHandler, false);
  7845. return;
  7846. }
  7847. if (rulesData.arrowToScroll) {
  7848. keyupHandler = e => {
  7849. if (document.activeElement &&
  7850. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  7851. document.activeElement.contentEditable == 'true')) {
  7852. return;
  7853. }
  7854. if (e.keyCode == 39) {
  7855. let nextPageBar=getPageBar().nextBar;
  7856. if (nextPageBar) {
  7857. scrollToPageBar(nextPageBar);
  7858. } else {
  7859. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  7860. window.scrollTo({ top: scrollTop + (window.innerHeight || document.documentElement.clientHeight), behavior: 'instant'});
  7861. }
  7862. } else if (e.keyCode == 37) {
  7863. let prePageBar = getPageBar().preBar;
  7864. if (prePageBar) {
  7865. scrollToPageBar(prePageBar);
  7866. } else {
  7867. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  7868. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'instant'});
  7869. }
  7870. }
  7871. };
  7872. document.addEventListener('keyup', keyupHandler);
  7873. }
  7874. if (!ruleParser.curSiteRule.wheel) {
  7875. document.addEventListener('scroll', scrollHandler, true);
  7876. }
  7877. document.addEventListener('wheel', scrollHandler, true);
  7878. }
  7879.  
  7880. let hideTipsTimeout;
  7881. function showTips(content, href, time, wordColor, backColor) {
  7882. initView();
  7883. document.documentElement.appendChild(tipsWords);
  7884. tipsWords.style.color = wordColor || 0xFFFFFF;
  7885. tipsWords.style.backgroundColor = backColor || 0x000;
  7886. let _time = 1500;
  7887. if (href) {
  7888. _time = 3500;
  7889. tipsWords.innerHTML = createHTML(`<a href='${href}' target='_blank'>${content}</a>`);
  7890. tipsWords.style.pointerEvents = 'all';
  7891. } else {
  7892. tipsWords.innerHTML = createHTML(content);
  7893. }
  7894. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  7895. setTimeout(() => {
  7896. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  7897. }, 0);
  7898. setTimeout(() => {
  7899. tipsWords.style.opacity = 0.8;
  7900. clearTimeout(hideTipsTimeout);
  7901. hideTipsTimeout = setTimeout(() => {
  7902. tipsWords.style.opacity = 0;
  7903. tipsWords.style.pointerEvents = '';
  7904. }, time || _time);
  7905. }, 1);
  7906. }
  7907.  
  7908. const loadmoreReg = /^\s*((点击)?加载更多|(點擊)?加載更多|(load|view)\s*more( comments)?|もっと読み込む)[\.…▼\s]*$/i;
  7909. const defaultLoadmoreSel = ".loadMore,.LoadMore,[class*='load-more'],button.show_more,.button-show-more,button[data-testid='more-results-button'],#btn_preview_remain,.view-more-btn";
  7910. function getLoadMore(doc, loadmoreBtn) {
  7911. if (!loadmoreBtn || !getBody(doc).contains(loadmoreBtn) || /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  7912. if (!ruleParser.curSiteRule.smart && !ruleParser.curSiteRule.loadMore) return null;
  7913. if (loadmoreBtn) return loadmoreBtn;
  7914. let btnSel = ruleParser.curSiteRule.loadMore || defaultLoadmoreSel;
  7915. if (btnSel) {
  7916. loadmoreBtn = getElement(btnSel, doc, null, true);
  7917. }
  7918. if (!loadmoreBtn) {
  7919. let buttons = getBody(doc).querySelectorAll("input,button,a,div[onclick]");
  7920. for (let i = 0; i < buttons.length; i++) {
  7921. let button = buttons[i];
  7922. if (!button.innerText || button.innerText.length > 20) continue;
  7923. if (button && loadmoreReg.test(button.innerText)) {
  7924. loadmoreBtn = button;
  7925. break;
  7926. }
  7927. }
  7928. }
  7929. if (loadmoreBtn && !ruleParser.curSiteRule.loadMore && loadmoreBtn.dataset.ajax !== "true") {
  7930. let href = loadmoreBtn.getAttribute("href");
  7931. if (href && href != "/" && !ruleParser.hrefIsJs(href)) {
  7932. loadmoreBtn = null;
  7933. }
  7934. }
  7935. if (loadmoreBtn && /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  7936. if (loadmoreBtn) debug(loadmoreBtn, 'Load more button');
  7937. return loadmoreBtn;
  7938. }
  7939.  
  7940. var targetY = -1;
  7941. function scrollToPageBar(bar) {
  7942. if (window.pageYOffset == 0) {
  7943. bar.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" });
  7944. } else {
  7945. let yOffset = -20;
  7946. if (typeof ruleParser.curSiteRule.pageBarTop !== 'undefined') {
  7947. yOffset = -ruleParser.curSiteRule.pageBarTop;
  7948. }
  7949. targetY = bar.getBoundingClientRect().top + window.pageYOffset + yOffset;
  7950. window.scrollTo({ top: targetY, behavior: 'smooth'});
  7951. }
  7952. }
  7953.  
  7954. const pageNumReg=/[&\/\?](p=|page[=\/_-]?)\d+|[_-]\d+\./;
  7955. function createPageBar(url) {
  7956. curPage++;
  7957. sideController.setup();
  7958. let posEle = null;
  7959. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7960. let insert = ruleParser.getInsert();
  7961. if (!insert || !insert.parentNode) return;
  7962. if (forceState == 2) {
  7963. posEle = getBody(document);
  7964. posEle = posEle.children[posEle.children.length - 1];
  7965. } else {
  7966. posEle = insert;
  7967. }
  7968. while (posEle && !posEle.offsetParent) {
  7969. posEle = posEle.previousElementSibling || posEle.parentNode;
  7970. }
  7971. if (posEle) {
  7972. let actualBottom = getElementBottom(posEle);
  7973. bottomGap = scrollH - actualBottom + (window.innerHeight || document.documentElement.clientHeight) * rate;
  7974. if (bottomGap < 100) bottomGap = 100;
  7975. } else {
  7976. bottomGap = 1000;
  7977. }
  7978. if (rulesData.opacity == 0 || ruleParser.curSiteRule.pageBar === 0) return null;
  7979. url = url.replace(/#p{.*/, "");
  7980. let example = (ruleParser.curSiteRule.insertPos == 2 || ruleParser.curSiteRule.insertPos == "in") ? insert.children[0] : (insert.parentNode.children[0] || insert);
  7981. while (example && (compareNodeName(example, ["script", "style"]) || example.className == "pagetual_pageBar")) {
  7982. example = example.nextElementSibling;
  7983. }
  7984. if (!example || !example.parentNode) example = insert;
  7985. if (example.nodeType != 1) {
  7986. example = example.previousElementSibling || example.parentNode;
  7987. if (!example || example.nodeType != 1) return;
  7988. }
  7989. let exampleStyle = _unsafeWindow.getComputedStyle(example);
  7990. let inTable, inLi;
  7991. if (forceState == 2) {
  7992. inTable = inLi = false;
  7993. } else {
  7994. inTable = compareNodeName(example.parentNode, ["table", "tbody"]) ||
  7995. compareNodeName(example, ["tr", "tbody"]) ||
  7996. exampleStyle.display == "table-row" ||
  7997. (example.nextElementSibling && compareNodeName(example.nextElementSibling, ["tr", "tbody"]));
  7998. inLi = compareNodeName(example, ["li"]) || (example.nextElementSibling && compareNodeName(example.nextElementSibling, ["li"]));
  7999. }
  8000. let pageBar = document.createElement(inTable ? "tr" : (inLi ? "li" : "div"));
  8001. let upSpan = document.createElement("span");
  8002. let downSpan = document.createElement("span");
  8003. let pageText = document.createElement("a");
  8004. let pageNum;
  8005. pageBar.className = isHideBar ? "pagetual_pageBar hide" : "pagetual_pageBar";
  8006. pageBar.id = "pagetual_pageBar" + curPage;
  8007. pageBar.setAttribute("translate", "no");
  8008. if (isPause) {
  8009. pageBar.classList.add("stop");
  8010. }
  8011. pageBar.style.cssText = pageBarStyle;
  8012. pageBar.title = i18n(isPause ? "enable" : "disable");
  8013. upSpan.innerHTML = createHTML(upSvg);
  8014. upSpan.children[0].style.cssText = upSvgCSS;
  8015. upSpan.title = i18n("toTop");
  8016. downSpan.innerHTML = createHTML(downSvg);
  8017. downSpan.children[0].style.cssText = downSvgCSS;
  8018. downSpan.title = i18n("toBottom");
  8019. upSpan.style.cssText = initStyle;
  8020. downSpan.style.cssText = initStyle;
  8021. pageText.href = url;
  8022. pageText.style.cssText = pageTextStyle;
  8023. pageText.title = i18n("current");
  8024. if (openInNewTab == 1) pageText.target = "_blank";
  8025. pageBar.appendChild(upSpan);
  8026. pageBar.appendChild(pageText);
  8027. let touched = false;
  8028. let touchBodyHandler = e => {
  8029. touched = false;
  8030. getBody(document).removeEventListener('touchstart', touchBodyHandler, { passive: false, capture: false });
  8031. };
  8032. pageText.addEventListener("touchstart", e => {
  8033. if (touched) return;
  8034. touched = true;
  8035. pageText.style.pointerEvents = 'none';
  8036. setTimeout(() => {
  8037. pageText.style.pointerEvents = 'all';
  8038. }, 250);
  8039. getBody(document).addEventListener("touchstart", touchBodyHandler, { passive: false, capture: false });
  8040. }, { passive: false, capture: false });
  8041. if (ruleParser.nextTitle) {
  8042. pageText.innerHTML = createHTML(ruleParser.nextTitle + " ");
  8043. pageText.title = ruleParser.nextTitle;
  8044. }
  8045. if (ruleParser.curSiteRule.pageNum || pageNumReg.test(url)) {
  8046. pageText.innerHTML = createHTML(pageText.innerHTML + i18n("page"));
  8047. pageNum = document.createElement("span");
  8048. let num = ruleParser.getPageNumFromUrl(url, curPage);
  8049. pageNum.innerHTML = createHTML(num + "<i style='font-size: 0;'>&nbsp;</i>");
  8050. pageNum.className = "pagetual_pageNum";
  8051. pageNum.title = i18n("inputPageNum");
  8052. pageNum.style.cssText = pageTextStyle;
  8053. pageNum.style.cursor = "pointer";
  8054. pageNum.style.color = "";
  8055. pageNum.style.marginLeft = "5px";
  8056. pageNum.addEventListener("click", e => {
  8057. let pageInput = prompt(i18n("inputPageNum"), num || "1");
  8058. if (pageInput) {
  8059. let localPageBar = document.querySelector("#pagetual_pageBar" + pageInput);
  8060. if (localPageBar) {
  8061. scrollToPageBar(localPageBar);
  8062. } else {
  8063. let pageLink = ruleParser.getLinkByPage(url, pageInput);
  8064. if (pageLink) {
  8065. _GM_openInTab(pageLink, {active:true});
  8066. }
  8067. }
  8068. }
  8069. e.preventDefault();
  8070. e.stopPropagation();
  8071. });
  8072. pageBar.appendChild(pageNum);
  8073. } else {
  8074. pageText.innerHTML = createHTML(pageText.innerHTML + i18n("page") + curPage + "<i style='font-size: 0;'>&nbsp;</i>");
  8075. }
  8076. let preBtn = document.createElement("span");
  8077. preBtn.innerHTML = createHTML("∧");
  8078. preBtn.title = i18n("prevPage");
  8079. preBtn.className = "prevScreen";
  8080. preBtn.style.cssText = "display: none;text-align: center;right: unset; float: left; width: 40px; background: rgba(240, 240, 240, 0.8); position: absolute; z-index: 9999999; box-shadow: rgb(0 0 0 / 50%) 0px -5px 5px; border-radius: 20px 20px 0 0; margin-top: -30px; ";
  8081. let nextBtn = document.createElement("span");
  8082. nextBtn.innerHTML = createHTML("∨");
  8083. nextBtn.title = i18n("nextPage");
  8084. nextBtn.className = "nextScreen";
  8085. nextBtn.style.cssText = "display: none;text-align: center;right: unset; float: left; width: 40px; background: rgba(240, 240, 240, 0.8); position: absolute; z-index: 9999999; box-shadow: rgb(0 0 0 / 50%) 0px 5px 5px; border-radius: 0 0 20px 20px; margin-top: 30px; ";
  8086. let localPage = curPage;
  8087. preBtn.addEventListener("click", e => {
  8088. e.stopPropagation();
  8089. e.preventDefault();
  8090. let prePageBar = document.querySelector("#pagetual_pageBar" + (localPage - 1));
  8091. if (prePageBar) {
  8092. scrollToPageBar(prePageBar);
  8093. } else {
  8094. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  8095. targetY = scrollTop - (window.innerHeight || document.documentElement.clientHeight);
  8096. window.scrollTo({ top: targetY, behavior: 'smooth'});
  8097. }
  8098. });
  8099. nextBtn.addEventListener("click", e => {
  8100. e.stopPropagation();
  8101. e.preventDefault();
  8102. let nextPageBar = document.querySelector("#pagetual_pageBar" + (localPage + 1));
  8103. if (nextPageBar) {
  8104. scrollToPageBar(nextPageBar);
  8105. } else {
  8106. scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  8107. targetY = scrollH || 9999999;
  8108. window.scrollTo({ top: targetY, behavior: 'smooth'});
  8109. }
  8110. });
  8111. if (!rulesData.hideBarArrow) {
  8112. pageText.insertBefore(preBtn, pageText.firstChild);
  8113. pageText.insertBefore(nextBtn, pageText.firstChild);
  8114. }
  8115. if (curForceIframe) {
  8116. let bgRing = document.createElement("span");
  8117. bgRing.className = "refreshRing";
  8118. bgRing.style.display = "none";
  8119. bgRing.innerHTML = createHTML(upSvg);
  8120. pageText.title = "Refresh";
  8121. pageText.appendChild(bgRing);
  8122. pageText.addEventListener("click", e => {
  8123. e.stopPropagation();
  8124. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  8125. e.preventDefault();
  8126. let nextEle = pageBar && pageBar.nextElementSibling;
  8127. if (nextEle && nextEle.name == 'pagetual-iframe') {
  8128. if (curForceIframe == nextEle) {
  8129. nextEle.setAttribute("loaded", "refresh");
  8130. }
  8131. nextEle.src = nextEle.src;
  8132. }
  8133. });
  8134. } else if (rulesData.pageBarMenu) {
  8135. pageText.addEventListener("click", e => {
  8136. e.stopPropagation();
  8137. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  8138. e.preventDefault();
  8139. picker.start();
  8140. });
  8141. }
  8142. pageBar.appendChild(downSpan);
  8143. if (forceState == 2) {
  8144. pageBar.style.width = "99%";
  8145. } else {
  8146. let parentStyle = _unsafeWindow.getComputedStyle(example.parentNode);
  8147. let parentWidth = example.parentNode.offsetWidth || parseInt(parentStyle.width);
  8148. pageBar.style.width = parentWidth - parseInt(parentStyle.paddingLeft) - parseInt(parentStyle.paddingRight) - 10 + "px";
  8149. pageBar.style.margin = '10px 5px';
  8150. if (parentStyle.display == "grid" || parentStyle.display == "inline-grid") {
  8151. pageBar.style.gridColumn = "1/-1";
  8152. }
  8153. if (inTable) {
  8154. example = compareNodeName(example, ["tr", "tbody"]) ? example : example.nextElementSibling || example;
  8155. if (compareNodeName(example, ["tbody"])) example = example.querySelector("tr");
  8156. let nextTr = example;
  8157. while (nextTr && nextTr.children.length == 0) nextTr = nextTr.nextElementSibling;
  8158. if (nextTr) example = nextTr;
  8159. let tdNum = 0;
  8160. if (exampleStyle.display == "table-row") {
  8161. [].forEach.call(example.children, el => {
  8162. tdNum += el.colSpan || 1;
  8163. });
  8164. } else {
  8165. [].forEach.call(example.children, el => {
  8166. if (compareNodeName(el, ["td", "th"])) {
  8167. tdNum += el.colSpan || 1;
  8168. }
  8169. });
  8170. }
  8171. pageBar.style.cssText = "";
  8172. pageBar.style.display = "table-row";
  8173. pageBar.style.backgroundColor = "unset";
  8174. pageBar.style.lineHeight = "20px";
  8175. pageBar.style.boxShadow = "";
  8176. let td = document.createElement("td");
  8177. td.colSpan = tdNum || 1;
  8178. let inTd = document.createElement("div");
  8179. inTd.style.cssText = pageBarStyle;
  8180. inTd.style.display = "";
  8181. inTd.className = pageBar.className;
  8182. pageBar.className = "";
  8183. inTd.appendChild(upSpan);
  8184. inTd.appendChild(pageText);
  8185. if (pageNum) inTd.appendChild(pageNum);
  8186. inTd.appendChild(downSpan);
  8187. td.appendChild(inTd);
  8188. pageBar.appendChild(td);
  8189. } else if (inLi) {
  8190. example = compareNodeName(example, ["li"]) ? example : example.nextElementSibling || example;
  8191. pageBar.style.opacity = 1;
  8192. pageBar.style.display = getComputedStyle(example).display;
  8193. pageBar.style.backgroundColor = "unset";
  8194. pageBar.style.lineHeight = "20px";
  8195. pageBar.style.boxShadow = "";
  8196. pageBar.style.border = "";
  8197. pageBar.style.width = "";
  8198. pageBar.style.maxWidth = "unset";
  8199. pageBar.style.flex = "auto";
  8200. let inTd = document.createElement("div");
  8201. inTd.style.cssText = pageBarStyle;
  8202. inTd.style.display = "";
  8203. inTd.style.margin = "0"
  8204. inTd.style.padding = "0 0";
  8205. inTd.style.textAlign = "center";
  8206. inTd.style.minWidth = "150px";
  8207. inTd.style.width = 'calc(100% - 20px)';
  8208. inTd.className = pageBar.className;
  8209. pageBar.className = "";
  8210. inTd.appendChild(upSpan);
  8211. inTd.appendChild(pageText);
  8212. if (pageNum) inTd.appendChild(pageNum);
  8213. inTd.appendChild(downSpan);
  8214. if (pageBar.style.display === 'table-row') {
  8215. let td = document.createElement("td");
  8216. td.colSpan = example.children.length;
  8217. td.style.width = '100%';
  8218. td.appendChild(inTd);
  8219. pageBar.appendChild(td);
  8220. } else {
  8221. inTd.style.width = '100%';
  8222. pageBar.appendChild(inTd);
  8223. }
  8224. }
  8225. }
  8226.  
  8227. upSpan.addEventListener("click", e => {
  8228. getBody(document).scrollTop = 0;
  8229. document.documentElement.scrollTop = 0;
  8230. e.preventDefault();
  8231. e.stopPropagation();
  8232. });
  8233. downSpan.addEventListener("click", e => {
  8234. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  8235. changeStop(true, true);
  8236. }
  8237. pageBar.title = i18n(isPause ? "enable" : "disable");
  8238. scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  8239. getBody(document).scrollTop = scrollH || 9999999;
  8240. document.documentElement.scrollTop = scrollH || 9999999;
  8241. e.preventDefault();
  8242. e.stopPropagation();
  8243. });
  8244. pageBar.addEventListener("click", e => {
  8245. changeStop(!isPause, true);
  8246. pageBar.title = i18n(isPause ? "enable" : "disable");
  8247. });
  8248. ruleParser.insertElement(pageBar);
  8249. ruleParser.runPageBar(pageBar);
  8250.  
  8251. return pageBar;
  8252. }
  8253.  
  8254. async function waitForElement(sel, doc) {
  8255. if (!sel) return null;
  8256. return new Promise((resolve) => {
  8257. let checkInv = setInterval(() => {
  8258. let result = getElement(sel, doc, null, true);
  8259. if (result) {
  8260. clearInterval(checkInv);
  8261. resolve(result);
  8262. }
  8263. }, 100);
  8264. });
  8265. }
  8266.  
  8267. async function clickAction(sel, doc) {
  8268. let btn = await waitForElement(sel, doc);
  8269. emuClick(btn, doc);
  8270. }
  8271.  
  8272. async function enterAction(sel, doc) {
  8273. let btn = await waitForElement(sel, doc);
  8274. let eventParam = { key: "Enter", keyCode: 13, bubbles: true };
  8275. let event = new KeyboardEvent('keydown', eventParam);
  8276. btn.dispatchEvent(event);
  8277. event = new KeyboardEvent('keyup', eventParam);
  8278. btn.dispatchEvent(event);
  8279. event = new KeyboardEvent('keypress', eventParam);
  8280. btn.dispatchEvent(event);
  8281. }
  8282.  
  8283. async function inputAction(sel, v, doc) {
  8284. let input = await waitForElement(sel, doc);
  8285. let event = new Event('focus', { bubbles: true });
  8286. input.dispatchEvent(event);
  8287. let lastValue = input.value;
  8288. if (input.nodeName.toUpperCase() == "INPUT") {
  8289. var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
  8290. nativeInputValueSetter.call(input, v);
  8291. } else if (input.nodeName.toUpperCase() == "TEXTAREA") {
  8292. var nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
  8293. nativeTextareaValueSetter.call(input, v);
  8294. } else {
  8295. input.innerHTML = createHTML(v);
  8296. }
  8297. event = new Event('input', { bubbles: true });
  8298. let tracker = input._valueTracker;
  8299. if (tracker) {
  8300. tracker.setValue(lastValue);
  8301. }
  8302. input.dispatchEvent(event);
  8303. event = new Event('change', { bubbles: true });
  8304. input.dispatchEvent(event);
  8305. debug(input, `input ${sel}`);
  8306. }
  8307.  
  8308. function emuClick(btn, doc) {
  8309. if (!doc) doc = document;
  8310. let curScroll = getBody(doc).scrollTop || doc.documentElement.scrollTop;
  8311. let orgHref = btn.getAttribute('href');
  8312. if (orgHref && orgHref.replace(location.origin + location.pathname, "").indexOf("#") === 0) {
  8313. let hashAction = e => {
  8314. e.preventDefault();
  8315. getBody(doc).scrollTop = curScroll;
  8316. doc.documentElement.scrollTop = curScroll;
  8317. btn.removeEventListener('click', hashAction, false);
  8318. };
  8319. btn.addEventListener('click', hashAction, false);
  8320. }
  8321. if (!PointerEvent) return btn.click();
  8322. let eventParam = {
  8323. isTrusted: true,
  8324. altKey: false,
  8325. azimuthAngle: 0,
  8326. bubbles: true,
  8327. button: 0,
  8328. buttons: 0,
  8329. clientX: 1,
  8330. clientY: 1,
  8331. cancelBubble: false,
  8332. cancelable: true,
  8333. composed: true,
  8334. ctrlKey: false,
  8335. defaultPrevented: false,
  8336. detail: 1,
  8337. eventPhase: 2,
  8338. fromElement: null,
  8339. height: 1,
  8340. isPrimary: false,
  8341. metaKey: false,
  8342. pointerId: 1,
  8343. pointerType: "mouse",
  8344. pressure: 0,
  8345. relatedTarget: null,
  8346. returnValue: true,
  8347. shiftKey: false,
  8348. toElement: null,
  8349. twist: 0,
  8350. which: 1
  8351. };
  8352. let mouseEvent = new PointerEvent("mousedown", eventParam);
  8353. btn.dispatchEvent(mouseEvent);
  8354. mouseEvent = new PointerEvent("mouseup", eventParam);
  8355. btn.dispatchEvent(mouseEvent);
  8356. let dispatchTouchEvent = (ele, type) => {
  8357. let touchEvent;
  8358. try {
  8359. touchEvent = document.createEvent('TouchEvent')
  8360. touchEvent.initTouchEvent(type, true, true)
  8361. } catch (err) {
  8362. try {
  8363. touchEvent = document.createEvent('UIEvent')
  8364. touchEvent.initUIEvent(type, true, true)
  8365. } catch (err) {
  8366. touchEvent = document.createEvent('Event')
  8367. touchEvent.initEvent(type, true, true)
  8368. }
  8369. }
  8370. if (touchEvent) {
  8371. try {
  8372. touchEvent.targetTouches = [{
  8373. pageX: 1,
  8374. pageY: 1,
  8375. clientX: 1,
  8376. clientY: 1,
  8377. target: btn
  8378. }];
  8379. touchEvent.touches = [{
  8380. pageX: 1,
  8381. pageY: 1,
  8382. clientX: 1,
  8383. clientY: 1,
  8384. target: btn
  8385. }];
  8386. touchEvent.changedTouches = [{
  8387. pageX: 1,
  8388. pageY: 1,
  8389. clientX: 1,
  8390. clientY: 1,
  8391. target: btn
  8392. }];
  8393. } catch (err) {}
  8394. ele.dispatchEvent(touchEvent);
  8395. }
  8396. }
  8397. dispatchTouchEvent(btn, "touchstart");
  8398. dispatchTouchEvent(btn, "touchend");
  8399.  
  8400. btn.click();
  8401. }
  8402.  
  8403. function emuInput(input, v) {
  8404. let result = false;
  8405. if (!input) return true;
  8406. let event = new Event('focus', { bubbles: true });
  8407. input.dispatchEvent(event);
  8408. let lastValue = input.value;
  8409. if (input.type == 'file') {
  8410. let file = v;
  8411. let blob = new Blob([file], {
  8412. type: 'text/plain'
  8413. });
  8414. file = new File([blob], 'noname.txt', { type: blob.type });
  8415. let dataTransfer = new DataTransfer();
  8416. dataTransfer.items.add(file);
  8417. input.files = dataTransfer.files;
  8418. v = "c:/fakepath/fakefile";
  8419. } else if (/INPUT/i.test(input.nodeName)) {
  8420. var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
  8421. nativeInputValueSetter.call(input, v);
  8422. } else if (/SELECT/i.test(input.nodeName)) {
  8423. var nativeSelectValueSetter = Object.getOwnPropertyDescriptor(window.HTMLSelectElement.prototype, "value").set;
  8424. nativeSelectValueSetter.call(input, v);
  8425. } else if (input.nodeName.toUpperCase() == "TEXTAREA") {
  8426. var nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
  8427. nativeTextareaValueSetter.call(input, v);
  8428. } else {
  8429. input.innerHTML = createHTML(v);
  8430. }
  8431. event = new Event('input', { bubbles: true });
  8432. let tracker = input._valueTracker;
  8433. if (tracker) {
  8434. tracker.setValue(lastValue);
  8435. }
  8436. input.dispatchEvent(event);
  8437. event = new Event('change', { bubbles: true });
  8438. input.dispatchEvent(event);
  8439. return result;
  8440. }
  8441.  
  8442. var failFromIframe = 0;
  8443. var inCors = false;
  8444. var checkRemoveIntv;
  8445. function requestFromIframe(url, callback){
  8446. if (location.protocol === 'https:' && !/^https:/.test(url)) {
  8447. ruleParser.noValidContent(url);
  8448. }
  8449. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  8450. let iframe = document.createElement('iframe');
  8451. iframe.name = 'pagetual-iframe';
  8452. iframe.width = '100%';
  8453. iframe.height = '1000';
  8454. iframe.frameBorder = '0';
  8455. if (ruleParser.curSiteRule.sandbox != false) {
  8456. iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  8457. }
  8458. iframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;flex:0;opacity:0!important;pointer-events:none!important;position:fixed;top:0px;left:0px;z-index:-2147483647;';
  8459. let waitTime = 100, checkEval;
  8460. ruleParser.runWait((_checkEval, _waitTime) => {
  8461. if (_checkEval) {
  8462. checkEval = _checkEval;
  8463. }
  8464. if (_waitTime) {
  8465. waitTime = _waitTime;
  8466. }
  8467. });
  8468. if (checkRemoveIntv) clearInterval(checkRemoveIntv);
  8469. checkRemoveIntv = setInterval(() => {
  8470. if (!iframe || !getBody(document).contains(iframe)) {
  8471. clearInterval(checkRemoveIntv);
  8472. loadPageOver();
  8473. }
  8474. }, 500);
  8475. let loadedHandler = async e => {
  8476. if (e.data != 'pagetual-iframe:DOMLoaded' && e.type != 'load') return;
  8477. clearInterval(checkRemoveIntv);
  8478. window.removeEventListener('message', loadedHandler, false);
  8479. iframe.removeEventListener('load', loadedHandler, false);
  8480. let pageEleTryTimes = 0;
  8481. async function checkIframe() {
  8482. if (urlChanged || isPause) {
  8483. return callback(false, false);
  8484. }
  8485. try {
  8486. let doc = iframe.contentDocument || iframe.contentWindow.document;
  8487. if (checkEval && !await checkEval(doc)) {
  8488. setTimeout(() => {
  8489. checkIframe();
  8490. }, waitTime);
  8491. return;
  8492. } else {
  8493. let preCode = ruleParser.curSiteRule.pagePre, eles = null;
  8494. if (preCode) {
  8495. try {
  8496. let preResult;
  8497. if (typeof preCode == 'function') {
  8498. preResult = await preCode(doc.documentElement.innerHTML, doc);
  8499. } else if (preCode.length == 2) {
  8500. preResult = doc.documentElement.innerHTML.replace(new RegExp(preCode[0], "gi"), preCode[1]);
  8501. } else {
  8502. preResult = await new AsyncFunction("response", "doc", '"use strict";' + preCode)(doc.documentElement.innerHTML, doc);
  8503. }
  8504. if (typeof preResult !== "undefined") {
  8505. if (typeof preResult === "string") {
  8506. doc.documentElement.innerHTML = preResult;
  8507. } else eles = preResult;
  8508. }
  8509. } catch(e) {
  8510. debug(e);
  8511. }
  8512. }
  8513. let base = doc.querySelector("base");
  8514. ruleParser.basePath = (base && base.href) || url;
  8515. if (eles === null) eles = ruleParser.getPageElement(doc, iframe.contentWindow, pageEleTryTimes < 25);
  8516. if (eles && eles.length > 0) {
  8517. await ruleParser.hookUrl(doc);
  8518. await callback(doc, eles);
  8519. } else if (pageEleTryTimes++ < 100) {
  8520. getBody(doc).scrollTop = 9999999;
  8521. doc.documentElement.scrollTop = 9999999;
  8522. setTimeout(() => {
  8523. checkIframe();
  8524. }, waitTime);
  8525. return;
  8526. } else {
  8527. if (failFromIframe++ > 2) {
  8528. failFromIframe = 0;
  8529. debug("Stop as failFromIframe");
  8530. changeStop(true);
  8531. callback(false, false);
  8532. } else {
  8533. ruleParser.noValidContent(url);
  8534. callback(false, false);
  8535. }
  8536. }
  8537. }
  8538. } catch(e) {
  8539. inCors = true;
  8540. if (forceState === 3) {
  8541. debug("Stop as cors");
  8542. isPause = true;
  8543. }
  8544. if (!ruleParser.curSiteRule.pageElement) {
  8545. ruleParser.curSiteRule.pageElement = allOfBody;
  8546. ruleParser.getInsert(true);
  8547. }
  8548. ruleParser.curSiteRule.action = 0;
  8549. ruleParser.nextLinkHref = url;
  8550. callback(false, false);
  8551. nextPage();
  8552. }
  8553. if (iframe && iframe.parentNode) iframe.parentNode.removeChild(iframe);
  8554. }
  8555. setTimeout(() => {
  8556. checkIframe();
  8557. }, waitTime);
  8558. };
  8559. let code = ruleParser.curSiteRule.iframeInit;
  8560. if (code) {
  8561. let checkReady = setInterval(() => {
  8562. let doc;
  8563. try {
  8564. doc = iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document);
  8565. } catch(e) {
  8566. clearInterval(checkReady);
  8567. return;
  8568. }
  8569. if (doc) {
  8570. clearInterval(checkReady);
  8571. try {
  8572. Function('win', 'iframe', '"use strict";' + code)(iframe.contentWindow, iframe);
  8573. } catch(e) {
  8574. debug(e);
  8575. }
  8576. }
  8577. }, 50);
  8578. }
  8579. window.addEventListener('message', loadedHandler, false);
  8580. iframe.addEventListener('load', loadedHandler, false);
  8581. iframe.src = url;
  8582. try {
  8583. getBody(document).appendChild(iframe);
  8584. } catch (e) {
  8585. return callback(false, false);
  8586. }
  8587. }
  8588.  
  8589. var emuIframe, lastActiveUrl, orgContent, meetCors = false;
  8590. function emuPage(callback) {
  8591. let orgPage = null, preContent = null, iframeDoc, checkTimes = 0, loadmoreBtn, pageEle, nextLink, loadmoreEnd = false, waitTimes = 80, changed = false;
  8592. function returnFalse(log) {
  8593. if (curPage > 1) {
  8594. if (rulesData.lastPageTips) showTips(i18n("lastPage"), "", 800);
  8595. _unsafeWindow.postMessage({
  8596. action: "lastPage",
  8597. command: 'pagetual'
  8598. }, '*');
  8599. } else {
  8600. sideController.remove();
  8601. }
  8602. debug(log);
  8603. isPause = true;
  8604. callback(false, false);
  8605. if (emuIframe && emuIframe.parentNode) {
  8606. emuIframe.parentNode.removeChild(emuIframe);
  8607. emuIframe = null;
  8608. }
  8609. }
  8610. function cloneStatus() {
  8611. if (!iframeDoc) return;
  8612. let inputs = document.querySelectorAll("input:not([type=button],[type=image],[type=reset],[type=submit])");
  8613. let selectOptions = document.querySelectorAll("select>option");
  8614. [...inputs].forEach(input => {
  8615. let sel = geneSelector(input, true, true);
  8616. let mirrorEle = iframeDoc.querySelector(sel);
  8617. if (!mirrorEle) return;
  8618. emuInput(mirrorEle, input.value);
  8619. });
  8620. [...selectOptions].forEach(option => {
  8621. let sel = geneSelector(option, true, true);
  8622. let mirrorEle = iframeDoc.querySelector(sel);
  8623. if (!mirrorEle) return;
  8624. let selected = option.selected;
  8625. mirrorEle.selected = !!selected;
  8626. mirrorEle.parentNode.dispatchEvent(new Event('change'));
  8627. });
  8628. }
  8629. async function checkPage() {
  8630. if (isPause) return loadPageOver();
  8631. try {
  8632. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  8633. } catch(e) {
  8634. returnFalse("Stop as cors");
  8635. return;
  8636. }
  8637.  
  8638. let waitTime = 200, checkEval;
  8639. ruleParser.runWait((_checkEval, _waitTime) => {
  8640. if (_checkEval) {
  8641. checkEval = _checkEval;
  8642. }
  8643. if (_waitTime) {
  8644. waitTime = _waitTime;
  8645. }
  8646. });
  8647.  
  8648. if (!orgPage) {
  8649. if (!loadmoreEnd) {
  8650. loadmoreBtn = getLoadMore(iframeDoc);
  8651. if (loadmoreBtn && isVisible(loadmoreBtn, emuIframe.contentWindow)) {
  8652. emuClick(loadmoreBtn, iframeDoc);
  8653. let intv = setInterval(() => {
  8654. loadmoreBtn = getLoadMore(iframeDoc);
  8655. if (!loadmoreBtn || !getBody(document).contains(loadmoreBtn) || !isVisible(loadmoreBtn, emuIframe.contentWindow)) {
  8656. clearInterval(intv);
  8657. loadmoreEnd = true;
  8658. setTimeout(() => {
  8659. checkPage();
  8660. }, 500);
  8661. } else if (isInViewPort(loadmoreBtn)) {
  8662. emuClick(loadmoreBtn, iframeDoc);
  8663. }
  8664. }, 200);
  8665. return;
  8666. } else {
  8667. loadmoreEnd = true;
  8668. }
  8669. }
  8670. if (checkEval && !await checkEval(iframeDoc)) {
  8671. waitTimes = 50;
  8672. setTimeout(() => {
  8673. checkPage();
  8674. }, waitTime);
  8675. return;
  8676. } else {
  8677. if (!nextLink || !nextLink.offsetParent) nextLink = await ruleParser.getNextLink(iframeDoc, true);
  8678. if (nextLink) pageEle = ruleParser.getPageElement(iframeDoc, emuIframe.contentWindow, true);
  8679. if (!pageEle || pageEle.length == 0 || !nextLink) {
  8680. getBody(iframeDoc).scrollTop = 9999999;
  8681. iframeDoc.documentElement.scrollTop = 9999999;
  8682. if (waitTimes-- > 0) {
  8683. setTimeout(() => {
  8684. checkPage();
  8685. }, waitTime);
  8686. return;
  8687. }
  8688. }
  8689. }
  8690. if (!pageEle || pageEle.length == 0) {
  8691. returnFalse("Stop as no page when emu");
  8692. return;
  8693. }
  8694. pageEle = [].filter.call(pageEle, ele => {return ele && !compareNodeName(ele, ["style", "script", "meta"])});
  8695. if (compareNodeName(pageEle[0], ["ul"]) || pageEle.length == 1) pageEle = pageEle[0];
  8696. else if (pageEle[0].parentNode == pageEle[1].parentNode) {
  8697. pageEle = pageEle[0].parentNode;
  8698. } else {
  8699. pageEle = pageEle[0];
  8700. }
  8701. if (ruleParser.curSiteRule.smart && orgContent != pageEle.innerHTML) {
  8702. orgContent = pageEle.innerHTML;
  8703. if (waitTimes-- > 0) {
  8704. setTimeout(() => {
  8705. checkPage();
  8706. }, 500);
  8707. return;
  8708. }
  8709. }
  8710. orgPage = pageEle;
  8711. if (nextLink) {
  8712. if (compareNodeName(orgPage, ["img"])) {
  8713. if (!ruleParser.curSiteRule.lazyImgSrc) ruleParser.curSiteRule.lazyImgSrc = "0";
  8714. if (orgPage.src) {
  8715. orgContent = orgPage.src;
  8716. } else {
  8717. setTimeout(() => {
  8718. checkPage();
  8719. }, 500);
  8720. return;
  8721. }
  8722. } else {
  8723. orgContent = orgPage.innerHTML;
  8724. }
  8725. preContent = orgContent;
  8726. if (!isVisible(nextLink, emuIframe.contentWindow)) {
  8727. returnFalse("Stop as next hide when emu");
  8728. } else {
  8729. emuClick(nextLink, iframeDoc);
  8730. setTimeout(() => {
  8731. checkPage();
  8732. }, 500);
  8733. }
  8734. } else {
  8735. returnFalse("Stop as no next when emu");
  8736. }
  8737. return;
  8738. }
  8739. if (!ruleParser.checkStopSign(nextLink, iframeDoc)) {
  8740. return returnFalse("Stop as stopSign");
  8741. }
  8742. if (checkTimes++ > 200) {
  8743. returnFalse("Stop as timeout when emu");
  8744. return;
  8745. }
  8746. if (checkEval && !await checkEval(iframeDoc)) {
  8747. checkTimes = 0;
  8748. setTimeout(() => {
  8749. checkPage();
  8750. }, waitTime);
  8751. return;
  8752. }
  8753. let eles = ruleParser.getPageElement(iframeDoc, emuIframe.contentWindow, true), checkItem;
  8754. if (eles && eles.length > 0) {
  8755. eles = [].filter.call(eles, ele => {return ele && !compareNodeName(ele, ["style", "script", "meta"])});
  8756. if (compareNodeName(eles[0], ["ul"]) || eles.length == 1) checkItem = eles[0];
  8757. else if (eles[0].parentNode == eles[1].parentNode) {
  8758. checkItem = eles[0].parentNode;
  8759. } else {
  8760. checkItem = eles[0];
  8761. }
  8762. }
  8763. if (!checkItem) {
  8764. setTimeout(() => {
  8765. checkPage();
  8766. }, waitTime);
  8767. } else {
  8768. let checkInner;
  8769. if (compareNodeName(checkItem, ["img"])) {
  8770. if (checkItem.src) {
  8771. checkInner = checkItem.src;
  8772. } else {
  8773. setTimeout(() => {
  8774. checkPage();
  8775. }, waitTime);
  8776. return;
  8777. }
  8778. } else {
  8779. checkInner = checkItem.innerHTML;
  8780. }
  8781. if (orgPage != checkItem || checkInner != preContent) {
  8782. changed = true;
  8783. orgPage = checkItem;
  8784. preContent = checkInner;
  8785. setTimeout(() => {
  8786. checkPage();
  8787. }, 500);
  8788. } else if (changed) {
  8789. checkTimes = 0;
  8790. if (orgContent == preContent && (ruleParser.curSiteRule.smart || ruleParser.curSiteRule.stopSame)) {
  8791. returnFalse("Stop as same content");
  8792. } else {
  8793. orgContent = preContent;
  8794. await ruleParser.hookUrl(iframeDoc);
  8795. callback(iframeDoc, eles);
  8796. }
  8797. } else {
  8798. if (checkTimes % 10 === 5) {
  8799. if (!nextLink || !nextLink.offsetParent) {
  8800. nextLink = await ruleParser.getNextLink(iframeDoc, true);
  8801. }
  8802. if (nextLink) {
  8803. emuClick(nextLink, iframeDoc);
  8804. }
  8805. }
  8806. setTimeout(() => {
  8807. checkPage();
  8808. }, waitTime);
  8809. }
  8810. }
  8811. }
  8812. if (!emuIframe) {
  8813. let loaded = false;
  8814. emuIframe = document.createElement('iframe');
  8815. emuIframe.name = 'pagetual-iframe';
  8816. let notSetSandbox = typeof ruleParser.curSiteRule.sandbox == 'undefined';
  8817. if (notSetSandbox || ruleParser.curSiteRule.sandbox == true) {
  8818. emuIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  8819. } else if (ruleParser.curSiteRule.sandbox) {
  8820. emuIframe.sandbox = ruleParser.curSiteRule.sandbox;
  8821. }
  8822. emuIframe.width = '100%';
  8823. emuIframe.height = '100%';
  8824. emuIframe.frameBorder = '0';
  8825. emuIframe.style.cssText = 'margin:0!important;padding:0!important;flex:0;opacity:0!important;pointer-events:none!important;position:fixed;top:0px;left:0px;z-index:-2147483647;';
  8826. emuIframe.addEventListener("load", e => {
  8827. try {
  8828. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  8829. } catch(e) {
  8830. if (e.message && e.message.indexOf("cross-origin") != -1 && notSetSandbox && emuIframe.hasAttribute("sandbox")) {
  8831. emuIframe.removeAttribute("sandbox");
  8832. meetCors = true;
  8833. callback(false, false);
  8834. if (ruleParser.curSiteRule.smart) {
  8835. ruleParser.findNoNext();
  8836. }
  8837. } else {
  8838. returnFalse("Stop as cors");
  8839. }
  8840. return;
  8841. }
  8842. setTimeout(async () => {
  8843. if (meetCors && ruleParser.curSiteRule.smart) {
  8844. ruleParser.smartRules = ruleParser.smartRules.filter(item => {return item && item.url !== ruleParser.curSiteRule.url;});
  8845. storage.setItem("smartRules", ruleParser.smartRules);
  8846. }
  8847. meetCors = false;
  8848. let code = ruleParser.curSiteRule.init;
  8849. if (code) {
  8850. try {
  8851. await new AsyncFunction('doc','win','iframe','click', 'enter', 'input', 'sleep', '"use strict";' + code)(iframeDoc, emuIframe.contentWindow, emuIframe, async sel => {await clickAction(sel, iframeDoc)}, async sel => {await enterAction(sel, iframeDoc)}, async (sel, v) =>{await inputAction(sel, v, iframeDoc)}, async time => {await sleep(time)});
  8852. } catch(e) {
  8853. debug(e);
  8854. }
  8855. } else {
  8856. let refreshByClickSel = ruleParser.curSiteRule.refreshByClick;
  8857. if (iframeDoc && refreshByClickSel) {
  8858. let clickBtn = await waitForElement(refreshByClickSel, iframeDoc);
  8859. await sleep(500);
  8860. cloneStatus();
  8861. emuClick(clickBtn, iframeDoc);
  8862. await sleep(500);
  8863. }
  8864. }
  8865. if (loaded) return;
  8866. loaded = true;
  8867. checkPage();
  8868. }, 500);
  8869. });
  8870. let code = ruleParser.curSiteRule.iframeInit;
  8871. if (code) {
  8872. let checkReady = setInterval(() => {
  8873. try {
  8874. iframeDoc = emuIframe.contentDocument || (emuIframe.contentWindow && emuIframe.contentWindow.document);
  8875. } catch(e) {
  8876. clearInterval(checkReady);
  8877. return;
  8878. }
  8879. if (iframeDoc) {
  8880. clearInterval(checkReady);
  8881. try {
  8882. Function('win', 'iframe', '"use strict";' + code)(emuIframe.contentWindow, emuIframe);
  8883. } catch(e) {
  8884. debug(e);
  8885. }
  8886. }
  8887. }, 50);
  8888. }
  8889. if (!lastActiveUrl) lastActiveUrl = location.href;
  8890. emuIframe.src = lastActiveUrl;
  8891. getBody(document).appendChild(emuIframe);
  8892. } else {
  8893. if (emuIframe.src != lastActiveUrl || meetCors) {
  8894. emuIframe.src = lastActiveUrl;
  8895. return;
  8896. }
  8897. checkPage();
  8898. }
  8899. }
  8900.  
  8901. var scrollToResizeInited = false;
  8902. var resizePool = [];
  8903. var scrollingToResize = false;
  8904.  
  8905. function isTouchViewPort(element) {
  8906. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  8907. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  8908. const {
  8909. top,
  8910. right,
  8911. bottom,
  8912. left,
  8913. } = element.getBoundingClientRect();
  8914.  
  8915. return (
  8916. top < viewHeight &&
  8917. left < viewWidth &&
  8918. right > 0 &&
  8919. bottom > 0
  8920. );
  8921. }
  8922.  
  8923. function resizeIframe(iframe, frameDoc, pageEle) {
  8924. if (targetY >= 0) {
  8925. window.scrollTo({ top: targetY, behavior: 'instant'});
  8926. targetY = -1;
  8927. }
  8928. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  8929. if (ruleParser.curSiteRule.smart || forceState === 2) {
  8930. let height = (getBody(frameDoc).scrollHeight || getBody(frameDoc).offsetHeight || 500);
  8931. if (!iframe.style.height || parseInt(iframe.style.height) === 0 || height - parseInt(iframe.style.height) > window.innerHeight) {
  8932. iframe.style.height = height + "px";
  8933. iframe.style.minHeight = iframe.style.height;
  8934. }
  8935. iframe.style.width = "100%";
  8936. frameDoc.documentElement.scrollTop = 0;
  8937. frameDoc.documentElement.scrollLeft = 0;
  8938. } else {
  8939. if (pageEle) {
  8940. if (document.body.scrollWidth) frameDoc.documentElement.style.width = document.body.scrollWidth + "px";
  8941. let fitWidth = ruleParser.curSiteRule.fitWidth !== false;
  8942. let targetElement = pageEle[0];
  8943. if (!targetElement) return;
  8944. if (pageEle.length > 1) {
  8945. targetElement = targetElement.parentNode;
  8946. }
  8947. let scrollHeight = targetElement.scrollHeight || targetElement.offsetHeight || 500;
  8948. iframe.style.height = scrollHeight + "px";
  8949. let scrollTop = 0, scrollLeft = 0;
  8950. getBody(frameDoc).scrollTop = 0;
  8951. getBody(frameDoc).scrollLeft = 0;
  8952. while (targetElement && targetElement.offsetParent) {
  8953. targetElement.offsetParent.scrollTop = targetElement.offsetTop;
  8954. if (targetElement.offsetParent.scrollTop == 0) {
  8955. scrollTop += targetElement.offsetTop;
  8956. }
  8957. if (fitWidth) {
  8958. targetElement.offsetParent.scrollLeft = targetElement.offsetLeft;
  8959. if (targetElement.offsetParent.scrollLeft == 0) {
  8960. scrollLeft += targetElement.offsetLeft;
  8961. }
  8962. }
  8963. targetElement = targetElement.offsetParent;
  8964. }
  8965. frameDoc.documentElement.scrollTop = scrollTop;
  8966. frameDoc.documentElement.scrollLeft = scrollLeft;
  8967. if (frameDoc.documentElement.scrollTop == 0 && frameDoc.documentElement.scrollLeft == 0) {
  8968. getBody(frameDoc).scrollTop += scrollTop;
  8969. getBody(frameDoc).scrollLeft += scrollLeft;
  8970. }
  8971. if (!fitWidth && iframe.style.marginLeft == '0px') {
  8972. iframe.style.width = "100vw";
  8973. iframe.style.maxWidth = "100vw";
  8974. iframe.style.minWidth = "100vw";
  8975. var cWidth = document.body.clientWidth || document.documentElement.clientWidth;
  8976. var iWidth = window.innerWidth;
  8977. iframe.style.marginLeft = -iframe.getBoundingClientRect().left - (iWidth - cWidth) / 2 + "px";
  8978. }
  8979. }
  8980. }
  8981. let newScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  8982. if (newScroll != curScroll) {
  8983. getBody(document).scrollTop = curScroll;
  8984. document.documentElement.scrollTop = curScroll;
  8985. }
  8986. }
  8987.  
  8988. function scrollToResize(e) {
  8989. if (scrollingToResize) return;
  8990. else {
  8991. scrollingToResize = true;
  8992. let resizeHandler = () => {
  8993. let touched = 0;
  8994. for (let i = 0; i < resizePool.length; i++) {
  8995. let resizeArr = resizePool[i];
  8996. let iframe = resizeArr[1]();
  8997. if (isTouchViewPort(iframe)) {
  8998. touched++;
  8999. let pageEle = resizeArr[0]();
  9000. let frameDoc = resizeArr[2]();
  9001. resizeIframe(iframe, frameDoc, pageEle);
  9002. } else if (touched) {
  9003. if (touched == 1) {
  9004. let pageEle = resizeArr[0]();
  9005. let frameDoc = resizeArr[2]();
  9006. resizeIframe(iframe, frameDoc, pageEle);
  9007. }
  9008. break;
  9009. } else if (!iframe.parentNode) {
  9010. resizePool.splice(i, 1);
  9011. break;
  9012. }
  9013. }
  9014. };
  9015. setTimeout(() => {
  9016. scrollingToResize = false;
  9017. }, 300);
  9018. resizeHandler();
  9019. }
  9020. }
  9021.  
  9022. var curForceIframe;
  9023. function forceIframe(url, callback) {
  9024. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  9025. let curIframe = document.createElement('iframe'), iframeDoc, pageElement = null, inAction = true;
  9026. let loadedHandler = () => {
  9027. let getPageEle = () => {
  9028. if (ruleParser.curSiteRule.smart) {
  9029. return null;
  9030. } else {
  9031. if (!pageElement || pageElement.length === 0 || !pageElement[0].offsetParent) {
  9032. pageElement = ruleParser.getPageElement(iframeDoc, curIframe.contentWindow);
  9033. }
  9034. return pageElement;
  9035. }
  9036. };
  9037. resizeIframe(curIframe, iframeDoc, getPageEle());
  9038. let loaded = curIframe.getAttribute("loaded");
  9039. if (loaded == "true") {
  9040. return;
  9041. }
  9042. curIframe.setAttribute("loaded", "true");
  9043. let getIframe = () => {
  9044. return curIframe;
  9045. };
  9046. let getFrameDoc = () => {
  9047. return iframeDoc;
  9048. };
  9049. ruleParser.insertPage(iframeDoc, [], url, ele => {
  9050. callback(curIframe, loaded == "refresh");
  9051. inAction = false;
  9052. }, true);
  9053. if (!loaded) {
  9054. resizePool.push([getPageEle, getIframe, getFrameDoc]);
  9055. }
  9056. };
  9057. let checkIframeTimer = setInterval(() => {
  9058. if (!curIframe.parentNode) {
  9059. clearInterval(checkIframeTimer);
  9060. return curIframe.getAttribute("loaded") == "true" || callback(false);
  9061. }
  9062. }, 500);
  9063. let code = ruleParser.curSiteRule.iframeInit;
  9064. if (code) {
  9065. let checkReady = setInterval(() => {
  9066. try {
  9067. iframeDoc = curIframe.contentDocument || (curIframe.contentWindow && curIframe.contentWindow.document);
  9068. } catch(e) {
  9069. clearInterval(checkReady);
  9070. return;
  9071. }
  9072. if (iframeDoc) {
  9073. clearInterval(checkReady);
  9074. try {
  9075. Function('win', 'iframe', '"use strict";' + code)(curIframe.contentWindow, curIframe);
  9076. } catch(e) {
  9077. debug(e);
  9078. }
  9079. }
  9080. }, 50);
  9081. }
  9082. let waitTime = 300, checkEval;
  9083. ruleParser.runWait((_checkEval, _waitTime) => {
  9084. if (_checkEval) {
  9085. checkEval = _checkEval;
  9086. }
  9087. if (_waitTime) {
  9088. waitTime = _waitTime;
  9089. }
  9090. });
  9091. async function checkIframe() {
  9092. if (checkEval && !await checkEval(iframeDoc)) {
  9093. setTimeout(() => {
  9094. checkIframe();
  9095. }, waitTime);
  9096. return;
  9097. }
  9098. loadedHandler();
  9099. }
  9100. curIframe.name = 'pagetual-iframe';
  9101. curIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  9102. curIframe.frameBorder = '0';
  9103. curIframe.scrolling = "no";
  9104. curIframe.style.cssText = 'display: block; visibility: visible; float: none; clear: both; width: 100%; height: 0; background: initial; border: 0px; border-radius: 0px; margin: 0px; padding: 0px; z-index: 2147483645;content-visibility: auto;contain-intrinsic-size: auto 300px;';
  9105. curIframe.addEventListener("load", async e => {
  9106. clearInterval(checkIframeTimer);
  9107. if (isPause) return callback(false);
  9108. try {
  9109. iframeDoc = curIframe.contentDocument || curIframe.contentWindow.document;
  9110. } catch(e) {
  9111. debug("Stop as cors");
  9112. isPause = true;
  9113. callback(false);
  9114. return;
  9115. }
  9116. let css = ruleParser.curSiteRule.css || rulesData.customCss;
  9117. if (css) {
  9118. let cssArr = css.split("inIframe:");
  9119. if (cssArr && cssArr.length > 1) {
  9120. let styleEle = iframeDoc.createElement("style");
  9121. styleEle.innerHTML = cssArr[1];
  9122. iframeDoc.head.appendChild(styleEle);
  9123. }
  9124. }
  9125. curIframe.style.height = "";
  9126. checkIframe();
  9127. iframeDoc.addEventListener('wheel', e => {
  9128. document.dispatchEvent(new Event('wheel'));
  9129. }, true);
  9130. });
  9131. let checkTimes = 0, findPageEle = false;
  9132. let forceRefresh = e => {
  9133. if (inAction || !iframeDoc) return;
  9134. inAction = true;
  9135. let foundNext = () => {
  9136. document.removeEventListener("scroll", forceRefresh);
  9137. }
  9138. setTimeout(async () => {
  9139. inAction = false;
  9140. if (!ruleParser.nextLinkHref && !isPause) {
  9141. checkTimes++;
  9142. await ruleParser.getNextLink(iframeDoc, true);
  9143. if (ruleParser.nextLinkHref) {
  9144. foundNext();
  9145. if (isLoading) isLoading = false;
  9146. } else if (checkTimes >= 10) {
  9147. foundNext();
  9148. } else if (checkTimes >= 3 && !findPageEle) {
  9149. if (!pageElement) pageElement = ruleParser.getPageElement(iframeDoc, curIframe.contentWindow);
  9150. if (!pageElement) {
  9151. inAction = true;
  9152. curIframe.contentWindow.location.reload();
  9153. } else {
  9154. findPageEle = true;
  9155. }
  9156. }
  9157. } else {
  9158. foundNext();
  9159. }
  9160. }, 100);
  9161. };
  9162. document.addEventListener("scroll", forceRefresh);
  9163. curIframe.src = url;
  9164. curForceIframe = curIframe;
  9165. let insert = ruleParser.getInsert();
  9166. let body = getBody(document);
  9167. let curScroll = body.scrollTop || document.documentElement.scrollTop;
  9168. if (forceState == 2) {
  9169. document.documentElement.appendChild(loadingDiv);
  9170. body.appendChild(curIframe);
  9171. let bodyStyle = getComputedStyle(body);
  9172. if (bodyStyle.display == "flex" || bodyStyle.display == "inline-flex") {
  9173. body.style.flexDirection = "column";
  9174. }
  9175. } else {
  9176. ruleParser.insertElement(curIframe);
  9177. }
  9178. body.scrollTop = curScroll;
  9179. document.documentElement.scrollTop = curScroll;
  9180.  
  9181. if (!scrollToResizeInited) {
  9182. scrollToResizeInited = true;
  9183. document.addEventListener("scroll", scrollToResize);
  9184. }
  9185. return curIframe;
  9186. }
  9187.  
  9188. function loadPageOver() {
  9189. isLoading = false;
  9190. stopScroll = true;
  9191. setTimeout(() => {stopScroll = false;}, 300);
  9192. if (loadingDiv.parentNode) {
  9193. loadingDiv.parentNode.removeChild(loadingDiv);
  9194. }
  9195. if (rate !== 1 && !clickMode) {
  9196. setTimeout(() => {
  9197. if (distToBottom() < bottomGap) {
  9198. nextPage();
  9199. }
  9200. }, 1);
  9201. }
  9202. }
  9203.  
  9204. function checkAutoLoadNum() {
  9205. if (autoLoadNum >= 0) {
  9206. if (autoLoadNum !== 0 && --autoLoadNum === 0) {
  9207. autoLoadNum = -1;
  9208. } else {
  9209. setTimeout(() => nextPage(), 1);
  9210. }
  9211. }
  9212. }
  9213.  
  9214. async function nextPage() {
  9215. if (isPause || isLoading || forceState === 1) return;
  9216. if (ruleParser.curSiteRule.delay) {
  9217. try {
  9218. let checkDelay = ((typeof ruleParser.curSiteRule.delay === 'function') ? ruleParser.curSiteRule.delay : Function('"use strict";' + ruleParser.curSiteRule.delay))();
  9219. if (!checkDelay) return;
  9220. } catch(e) {
  9221. debug(e);
  9222. }
  9223. }
  9224. let nextLink = ruleParser.nextLinkHref;
  9225. if (!nextLink) {
  9226. isLoading = true;
  9227. if (curPage === 1) {
  9228. await ruleParser.getNextLink(document, true);
  9229. nextLink = ruleParser.nextLinkHref;
  9230. }
  9231. if (!nextLink) {
  9232. if (curPage === 1) {
  9233. if (ruleParser.curSiteRule.pinUrl) {
  9234. setTimeout(() => {isLoading = false;}, 500);
  9235. } else if (tryTimes++ < 5) {
  9236. setTimeout(() => {isLoading = false;}, 1000);
  9237. } else {
  9238. ruleParser.findNoNext();
  9239. }
  9240. } else if (!showedLastPageTips) {
  9241. if (rulesData.lastPageTips) {
  9242. showTips(i18n("lastPage"), "", 800);
  9243. }
  9244. showedLastPageTips = true;
  9245. _unsafeWindow.postMessage({
  9246. action: "lastPage",
  9247. command: 'pagetual'
  9248. }, '*');
  9249. }
  9250. return;
  9251. }
  9252. isLoading = false;
  9253. }
  9254. showedLastPageTips = false;
  9255. let pvGallery = document.querySelector("span.pv-gallery-container");
  9256. if (pvGallery && pvGallery.style.display !== "none") return;
  9257. let insert = ruleParser.getInsert();
  9258. if (insert) {
  9259. if (curPage === 1) initView();
  9260. /*if (curPage == 1) {
  9261. window.postMessage({
  9262. command: 'pagetual.insert'
  9263. }, '*');
  9264. }*/
  9265. let isJs = ruleParser.curSiteRule.action == 3 || ruleParser.hrefIsJs(nextLink);
  9266. if (!isJs) {
  9267. emuIframe = null;
  9268. lastActiveUrl = nextLink;
  9269. if (location.protocol === "https:" && /^http:/.test(nextLink)) {
  9270. nextLink = nextLink.replace(/^http/, "https");
  9271. }
  9272. }
  9273. isLoading = true;
  9274. if (curPage !== 1 || !isJs || !ruleParser.curSiteRule.smart) {
  9275. ruleParser.beginLoading(loadingDiv);
  9276. }
  9277. let sleep = ruleParser.curSiteRule.sleep || 0;
  9278. setTimeout(() => {
  9279. if (ruleParser.curSiteRule.pageElementByJs) {
  9280. var over = eles => {
  9281. if (urlChanged || isPause) {
  9282. loadPageOver();
  9283. return;
  9284. }
  9285. if (eles) {
  9286. ruleParser.insertPage(document, eles, nextLink, () => {
  9287. createPageBar(nextLink);
  9288. checkAutoLoadNum();
  9289. }, true);
  9290. } else {
  9291. debug("Stop as no page when get by js");
  9292. isPause = true;
  9293. loadPageOver();
  9294. }
  9295. };
  9296. try {
  9297. ((typeof ruleParser.curSiteRule.pageElementByJs === 'function') ? ruleParser.curSiteRule.pageElementByJs : Function("over", "pageNum",'"use strict";' + ruleParser.curSiteRule.pageElementByJs))(over, curPage);
  9298. } catch(e) {
  9299. debug(e);
  9300. }
  9301. } else if ((forceState === 2 || ruleParser.curSiteRule.action == 2) && !isJs) {
  9302. forceIframe(nextLink, (iframe, refresh) => {
  9303. if (urlChanged || isPause) {
  9304. loadPageOver();
  9305. return;
  9306. }
  9307. if (!refresh) {
  9308. let pageBar = createPageBar(nextLink);
  9309. if (pageBar && iframe && iframe.parentNode) iframe.parentNode.insertBefore(pageBar, iframe);
  9310. }
  9311. loadPageOver();
  9312. checkAutoLoadNum();
  9313. });
  9314. } else if ((forceState === 3 || ruleParser.curSiteRule.action == 1) && !isJs) {
  9315. requestFromIframe(nextLink, async (doc, eles) => {
  9316. if (urlChanged || isPause) {
  9317. loadPageOver();
  9318. return;
  9319. }
  9320. if (eles) {
  9321. await ruleParser.insertPage(doc, eles, nextLink, () => {
  9322. createPageBar(nextLink);
  9323. checkAutoLoadNum();
  9324. }, true);
  9325. } else {
  9326. loadPageOver();
  9327. if (autoLoadNum >= 0) {
  9328. setTimeout(() => nextPage(), 2000);
  9329. }
  9330. }
  9331. });
  9332. } else {
  9333. if (!isJs) {
  9334. requestDoc(nextLink, (eles) => {
  9335. if (urlChanged || isPause) {
  9336. loadPageOver();
  9337. return;
  9338. }
  9339. if (eles) {
  9340. createPageBar(nextLink);
  9341. checkAutoLoadNum();
  9342. } else {
  9343. loadPageOver();
  9344. if (autoLoadNum >= 0) {
  9345. setTimeout(() => nextPage(), 2000);
  9346. }
  9347. }
  9348. });
  9349. } else {
  9350. emuPage((doc, eles) => {
  9351. if (urlChanged || isPause) {
  9352. loadPageOver();
  9353. return;
  9354. }
  9355. if (eles) {
  9356. ruleParser.insertPage(doc, eles, "", () => {
  9357. createPageBar(nextLink);
  9358. checkAutoLoadNum();
  9359. }, true);
  9360. } else {
  9361. loadPageOver();
  9362. if (autoLoadNum >= 0) {
  9363. setTimeout(() => nextPage(), 2000);
  9364. }
  9365. }
  9366. });
  9367. }
  9368. }
  9369. }, sleep);
  9370. }
  9371. }
  9372.  
  9373. function init() {
  9374. if (document.readyState === 'loading' || document.readyState === 'uninitialized') {
  9375. let domReady = e => {
  9376. initRules(() => {
  9377. initPage();
  9378. });
  9379. document.removeEventListener("DOMContentLoaded", domReady, false);
  9380. };
  9381. document.addEventListener("DOMContentLoaded", domReady, false);
  9382. } else {
  9383. initRules(() => {
  9384. initPage();
  9385. });
  9386. }
  9387. }
  9388.  
  9389. function visibilitychangeHandler() {
  9390. document.removeEventListener('visibilitychange', visibilitychangeHandler);
  9391. init();
  9392. }
  9393.  
  9394. setTimeout(() => {
  9395. if (document.hidden) {
  9396. document.addEventListener('visibilitychange', visibilitychangeHandler);
  9397. } else {
  9398. init();
  9399. }
  9400. }, 300);
  9401. })();