東方永頁機

終極自動翻頁 - 加載並拼接下一分頁內容至當前頁尾,智能適配任意網頁

目前為 2024-06-26 提交的版本,檢視 最新版本

  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.64
  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. // @supportURL https://github.com/hoothin/UserScripts/issues
  49. // @connect wedata.net
  50. // @connect githubusercontent.com
  51. // @connect ghproxy.com
  52. // @connect hoothin.github.io
  53. // @run-at document-idle
  54. // @connect *
  55. // @contributionURL https://ko-fi.com/hoothin
  56. // @contributionAmount 1
  57. // ==/UserScript==
  58.  
  59. (function() {
  60. 'use strict';
  61.  
  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. name: "English",
  114. match: ["en"],
  115. lang: {
  116. enableDebug: "Enable debug output",
  117. updateNotification: "Notification after rules updated",
  118. disable: "Disable",
  119. disableSite: "Toggle disabled state",
  120. disableSiteTips: "Disabled on this site",
  121. enableSiteTips: "Enabled on this site",
  122. enable: "Enable",
  123. toTop: "To Top",
  124. toBottom: "To Bottom",
  125. current: "Current Page",
  126. forceIframe: "Force to join next page",
  127. cancelForceIframe: "Cancel Force join",
  128. configure: "Configure",
  129. firstUpdate: "Click here to initialize the rules",
  130. update: "Update online rules",
  131. click2update: "Click to update rules from url now",
  132. loadNow: "Load next automatically",
  133. loadConfirm: "How much pages do you want to load? (0 means infinite)",
  134. noNext: "No next link found, please create a new rule",
  135. passSec: "Updated #t# seconds ago",
  136. passMin: "Updated #t# minutes ago",
  137. passHour: "Updated #t# hours ago",
  138. passDay: "Updated #t# days ago",
  139. cantDel: "Can't delete buildin rules",
  140. confirmDel: "Are you sure you want to delete this rule?",
  141. updateSucc: "Update succeeded",
  142. beginUpdate: "Begin update, wait a minute please",
  143. customUrls: "Import Pagetual or AutoPagerize rule url, One url per line",
  144. customRules: "Input custom rules. <a href='#t#'>✍️Contribute rules</a>",
  145. save: "Save",
  146. loadingText: "Shojo Now Loading...",
  147. opacity: "Opacity",
  148. opacityPlaceholder: "0: hide spacer",
  149. hideBar: "Hide the paging spacer",
  150. hideBarButNoStop: "Hide but not stop",
  151. dbClick2Stop: "Double-click on the blank space to pause",
  152. sortTitle: "Sorting takes effect after the next rule update",
  153. autoRun: "Auto enable (blacklist mode)",
  154. autoLoadNum: "Amount for preload pages",
  155. turnRate: "Turn the next page when it's less than 【X】 times page height from the footer",
  156. inputPageNum: "Enter page number to jump",
  157. enableHistory: "Write browsing history after page turning",
  158. enableHistoryAfterInsert: "Write browsing history immediately after splicing, otherwise write after browsing",
  159. contentVisibility: "Automatically switch contentVisibility to improve rendering performance",
  160. initRun: "Turn pages immediately after opening",
  161. preload: "Preload next page for speeding up",
  162. click2ImportRule: "Click to import base rules link, then wait until the update is complete: ",
  163. forceAllBody: "Join full body of page?",
  164. openInNewTab: "Open urls of additions in new tab",
  165. importSucc: "Import completed",
  166. import: "Import",
  167. editCurrent: "Edit rule for current",
  168. editBlacklist: "Edit the blacklist urls, line by line, Support ? * for wildcard",
  169. upBtnImg: "Icon of back to top",
  170. downBtnImg: "Icon of go to footer",
  171. sideControllerIcon: "Icon of sidebar",
  172. loadingTextTitle: "Loading text",
  173. dbClick2StopCtrl: "Ctrl key",
  174. dbClick2StopAlt: "Alt key",
  175. dbClick2StopShift: "Shift key",
  176. dbClick2StopMeta: "Meta key",
  177. dbClick2StopKey: "Shortcut key",
  178. pageElementCss: "Custom style for main page elements",
  179. customCss: "Custom complete css",
  180. firstAlert: "You have not imported the base rule, please select the appropriate rule to import",
  181. picker: "Pagetual page element picker",
  182. closePicker: "Close Pagetual picker",
  183. pickerPlaceholder: "Element selector, Leave empty if you have no idea",
  184. pickerCheck: "Check selector and copy",
  185. switchSelector: "Click to switch element",
  186. gotoEdit: "Go to edit rule with current selector",
  187. manualMode: "Disable splicing, manually turn pages with the right arrow keys (or dispatch event 'pagetual.next')",
  188. clickMode: "Disable splicing, automatically click the next page when scrolling to the end of the page",
  189. pageBarMenu: "Click the center of the page bar to open the picker menu",
  190. nextSwitch: "Switch next link",
  191. arrowToScroll: "Press left arrow key to scroll prev and right arrow key to scroll next",
  192. sideController: "Display the paging control bar in the sidebar",
  193. sideControllerScroll: "Scroll toggle",
  194. sideControllerAlways: "Always show",
  195. hideLoadingIcon: "Hide loading animation",
  196. hideBarArrow: "Hide arrow for page bar",
  197. duplicate: "Duplicate Pagetual have been installed, check your script manager!",
  198. forceStateIframe: "Embed full page as iframe",
  199. forceStateDynamic: "Load dynamic content via iframe",
  200. forceStateDisable: "Disable page turning on this site",
  201. autoScrollRate: "Scroll speed (1~1000)",
  202. disableAutoScroll: "Stop Auto Scroll",
  203. enableAutoScroll: "Enable Auto Scroll",
  204. toggleAutoScroll: "Toggle Auto Scroll",
  205. ruleRequest: "Rule Request",
  206. page: "Page ",
  207. prevPage: "Prev page",
  208. nextPage: "Next page",
  209. errorRulesMustBeArray: "Rules must be a Array!",
  210. errorJson: "JSON error, check again!",
  211. editSuccess: "Edit successfully",
  212. errorWrongUrl: "Wrong url, check again!",
  213. errorAlreadyExists: "Already exists!",
  214. settingsSaved: "The settings are saved, refresh to view",
  215. iframe: "Iframe",
  216. dynamic: "Dynamic",
  217. reloadPage: "Edit completed, reload page now?",
  218. copied: "Copied",
  219. noValidContent: "No valid content detected, Captcha action may be required, click to view",
  220. outOfDate: "The script is outdated, update to the latest version in time!",
  221. hideBarTips: "Hide the pagination bar, toggle immersive experience",
  222. setConfigPage: "Set current page as the default configuration page",
  223. wedata2github: "Change the wedata address to the mirror address in the github repository",
  224. addOtherProp: "Add rule property",
  225. addNextSelector: "Add selector content as nextLink",
  226. addPageSelector: "Add selector content as pageElement",
  227. propName: "Enter rule property name",
  228. propValue: "Enter rule property value",
  229. customFirst: "Ignore cache for local custom rules",
  230. rulesExample: "Rules Example",
  231. lastPage: "Reached the last page",
  232. lastPageTips: "Show tips when reaching the last page"
  233. }
  234. },
  235. {
  236. //Translated by SrKalopsia (srkalopsia@gmail.com).
  237. name: "Español",
  238. match: ["es", "es-ES"],
  239. lang: {
  240. enableDebug: "Habilitar salida de depuración",
  241. updateNotification: "Notificación después de actualizar las reglas",
  242. disable: "Desactivar",
  243. disableSite: "Alternar estado desactivado",
  244. disableSiteTips: "Desactivado en este sitio",
  245. enableSiteTips: "Activado en este sitio",
  246. enable: "Habilitar",
  247. toTop: "Ir al inicio",
  248. toBottom: "Ir al final",
  249. current: "Página actual",
  250. forceIframe: "Forzar para unirse a la siguiente página",
  251. cancelForceIframe: "Cancelar unión forzada",
  252. configure: "Configurar",
  253. firstUpdate: "Haga clic aquí para inicializar las reglas",
  254. update: "Actualizar reglas en línea",
  255. click2update: "Haga clic para actualizar las reglas desde la URL ahora",
  256. loadNow: "Cargar el siguiente automáticamente",
  257. loadConfirm: "¿Cuántas páginas desea cargar? (0 significa infinito)",
  258. noNext: "No se encontró el enlace siguiente, por favor cree una nueva regla",
  259. passSec: "Actualizado hace #t# segundos",
  260. passMin: "Actualizado hace #t# minutos",
  261. passHour: "Actualizado hace #t# horas",
  262. passDay: "Actualizado hace #t# días",
  263. cantDel: "No se pueden eliminar las reglas incorporadas",
  264. confirmDel: "¿Está seguro de que desea eliminar esta regla?",
  265. updateSucc: "Actualización exitosa",
  266. beginUpdate: "Comenzar actualización, espere un momento por favor",
  267. customUrls: "Importar URL de reglas de Pagetual o AutoPagerize, una URL por línea",
  268. customRules: "Introduzca reglas personalizadas. <a href='#t#'>✍️Contribuir reglas</a>",
  269. save: "Guardar",
  270. loadingText: "Shojo Cargando...",
  271. opacity: "Opacidad",
  272. opacityPlaceholder: "0: ocultar espaciador",
  273. hideBar: "Ocultar el espaciador de paginación",
  274. hideBarButNoStop: "Ocultar pero no detener",
  275. dbClick2Stop: "Haga doble clic en el espacio en blanco para pausar",
  276. sortTitle: "La ordenación surtirá efecto después de la próxima actualización de reglas",
  277. autoRun: "Habilitar automáticamente (modo lista negra)",
  278. autoLoadNum: "Cantidad de páginas para precargar",
  279. 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",
  280. inputPageNum: "Ingrese el número de página para saltar",
  281. enableHistory: "Escribir historial de navegación después de pasar la página",
  282. enableHistoryAfterInsert: "Escribir historial de navegación inmediatamente después de unir, de lo contrario escribir después de navegar",
  283. contentVisibility: "Cambiar automáticamente la visibilidad del contenido para mejorar el rendimiento de renderización",
  284. initRun: "Pasar páginas inmediatamente después de abrir",
  285. preload: "Precargar la siguiente página para acelerar",
  286. click2ImportRule: "Haga clic para importar el enlace de reglas base, luego espere hasta que la actualización esté completa: ",
  287. forceAllBody: "¿Unir el cuerpo completo de la página?",
  288. openInNewTab: "Abrir URLs de adiciones en una nueva pestaña",
  289. importSucc: "Importación completada",
  290. import: "Importar",
  291. editCurrent: "Editar regla para la actual",
  292. editBlacklist: "Editar URLs de la lista negra, una por línea, admite ? * para comodín",
  293. upBtnImg: "Icono de volver al inicio",
  294. downBtnImg: "Icono de ir al pie de página",
  295. sideControllerIcon: "Icono de la barra lateral",
  296. loadingTextTitle: "Texto de carga",
  297. dbClick2StopCtrl: "Tecla Ctrl",
  298. dbClick2StopAlt: "Tecla Alt",
  299. dbClick2StopShift: "Tecla Shift",
  300. dbClick2StopMeta: "Tecla Meta",
  301. dbClick2StopKey: "Tecla de acceso rápido",
  302. pageElementCss: "Estilo personalizado para los elementos principales de la página",
  303. customCss: "CSS completo personalizado",
  304. firstAlert: "No ha importado la regla base, por favor seleccione la regla adecuada para importar",
  305. picker: "Selector de elementos de página de Pagetual",
  306. closePicker: "Cerrar selector de Pagetual",
  307. pickerPlaceholder: "Selector de elementos, déjelo vacío si no tiene idea",
  308. pickerCheck: "Comprobar selector y copiar",
  309. switchSelector: "Haga clic para cambiar el elemento",
  310. gotoEdit: "Ir a editar la regla con el selector actual",
  311. manualMode: "Deshabilitar unión, pasar páginas manualmente con las teclas de flecha derecha (o despachar evento 'pagetual.next')",
  312. clickMode: "Deshabilitar unión, hacer clic automáticamente en la siguiente página al desplazarse al final de la página",
  313. pageBarMenu: "Haga clic en el centro de la barra de página para abrir el menú del selector",
  314. nextSwitch: "Cambiar al siguiente enlace",
  315. arrowToScroll: "Presione la tecla de flecha izquierda para desplazarse anterior y la tecla de flecha derecha para desplazarse siguiente",
  316. sideController: "Mostrar la barra de control de paginación en la barra lateral",
  317. sideControllerScroll: "Alternar desplazamiento",
  318. sideControllerAlways: "Mostrar siempre",
  319. hideLoadingIcon: "Ocultar animación de carga",
  320. hideBarArrow: "Ocultar flecha para la barra de página",
  321. duplicate: "Pagetual duplicado ha sido instalado, ¡revise su gestor de scripts!",
  322. forceStateIframe: "Incrustar página completa como iframe",
  323. forceStateDynamic: "Cargar contenido dinámico a través de iframe",
  324. forceStateDisable: "Deshabilitar pasar páginas en este sitio",
  325. autoScrollRate: "Velocidad de desplazamiento (1~1000)",
  326. disableAutoScroll: "Detener desplazamiento automático",
  327. enableAutoScroll: "Habilitar desplazamiento automático",
  328. toggleAutoScroll: "Alternar desplazamiento automático",
  329. ruleRequest: "Solicitud de regla",
  330. page: "Página ",
  331. prevPage: "Página anterior",
  332. nextPage: "Página siguiente",
  333. errorRulesMustBeArray: "¡Las reglas deben ser un array!",
  334. errorJson: "Error JSON, ¡verifique de nuevo!",
  335. editSuccess: "Editado exitosamente",
  336. errorWrongUrl: "URL incorrecta, ¡verifique de nuevo!",
  337. errorAlreadyExists: "¡Ya existe!",
  338. settingsSaved: "La configuración se ha guardado, actualice para ver",
  339. iframe: "Iframe",
  340. dynamic: "Dinámico",
  341. reloadPage: "Edición completada, ¿recargar página ahora?",
  342. copied: "Copiado",
  343. noValidContent: "No se detectó contenido válido, puede ser necesario realizar una acción de Captcha, haga clic para ver",
  344. outOfDate: "El script está desactualizado, ¡actualice a la última versión a tiempo!",
  345. hideBarTips: "Ocultar la barra de paginación, alternar experiencia inmersiva",
  346. setConfigPage: "Establecer la página actual como la página de configuración predeterminada",
  347. wedata2github: "Cambiar la dirección de wedata a la dirección espejo en el repositorio de GitHub",
  348. addOtherProp: "Agregar propiedad de regla",
  349. addNextSelector: "Agregar contenido del selector como nextLink",
  350. addPageSelector: "Agregar contenido del selector como pageElement",
  351. propName: "Ingrese el nombre de la propiedad de la regla",
  352. propValue: "Ingrese el valor de la propiedad de la regla",
  353. customFirst: "Ignorar caché para reglas personalizadas locales",
  354. rulesExample: "Ejemplo de reglas",
  355. lastPage: "Llegó a la última página",
  356. lastPageTips: "Mostrar consejos al llegar a la última página"
  357. }
  358. },
  359. {
  360. //Translated by Prankster 199 (vfggf95565).
  361. name: "Arabic",
  362. 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"],
  363. lang: {
  364. enableDebug: "تمكين تصحيح الأخطاء",
  365. updateNotification: "إشعار بعد تحديث القواعد",
  366. disable: "معطل",
  367. disableSite: "تبديل حالة التعطيل/التفعيل للموقع",
  368. disableSiteTips: "معطل على هذا الموقع",
  369. enableSiteTips: "مفعل على هذا الموقع",
  370. enable: "مفعل",
  371. toTop: "إلى الأعلى",
  372. toBottom: "إلى الأسفل",
  373. current: "الصفحة الحالية",
  374. forceIframe: "إجبار على الانضمام للصفحة التالية",
  375. cancelForceIframe: "إلغاء الانضمام القسري",
  376. configure: "إعداد",
  377. firstUpdate: "انقر هنا لتفعيل القواعد لأول مرة",
  378. update: "تحديث القواعد عبر الإنترنت",
  379. click2update: "انقر لتحديث القواعد من الرابط الآن",
  380. loadNow: "تحميل التالي تلقائيًا",
  381. loadConfirm: "كم عدد الصفحات التي ترغب تحميلها؟ (0 يعني لانهائي)",
  382. noNext: "لم يتم العثور على رابط الصفحة التالية، يرجى إنشاء قاعدة جديدة",
  383. passSec: "تم التحديث منذ #t# ثانية",
  384. passMin: "تم التحديث منذ #t# دقيقة",
  385. passHour: "تم التحديث منذ #t# ساعة",
  386. passDay: "تم التحديث منذ #t# يوم",
  387. cantDel: "لا يمكن حذف القواعد المدمجة",
  388. confirmDel: "هل أنت متأكد من حذف هذه القاعدة؟",
  389. updateSucc: "تم التحديث بنجاح",
  390. beginUpdate: "بدأ التحديث، يرجى الانتظار لحظة",
  391. customUrls: "استيراد رابط قاعدة Pagetual أو AutoPagerize، رابط واحد لكل سطر",
  392. customRules: "إدخال القواعد المخصصة. <a href='#t#'>✍️ساهم بالقواعد</a>",
  393. save: "حفظ",
  394. /* From the creator hoothin :
  395. "Shojo Now Loading..." is a meme that refers to the game loading text in the Japanese Touhou (東方) game series. */
  396. loadingText: "جارٍ التحميل...",
  397. opacity: "الشفافية",
  398. opacityPlaceholder: "0: إخفاء الفاصل",
  399. hideBar: "إخفاء الفاصل التصفحي",
  400. hideBarButNoStop: "إخفاء، لكن لا تتوقف",
  401. dbClick2Stop: "انقر مزدوج على المساحة الفارغة للإيقاف",
  402. sortTitle: "يتم تفعيل الفرز بعد التحديث التالي للقواعد",
  403. autoRun: "تمكين تلقائي (وضع القائمة السوداء)",
  404. autoLoadNum: "عدد صفحات التحميل المسبق",
  405. turnRate: "الانتقال للصفحة التالية عندما تكون المسافة أقل من 【X】 مرات ارتفاع الصفحة من التذييل",
  406. inputPageNum: "أدخل رقم الصفحة للانتقال",
  407. enableHistory: "كتابة سجل التصفح بعد تحويل الصفحة",
  408. enableHistoryAfterInsert: "كتابة سجل التصفح فورًا بعد الدمج، أو بعد التصفح",
  409. contentVisibility: "التنقل التلقائي لرؤية المحتوى, لتحسين أداء العرض",
  410. initRun: "الانتقال بين الصفحات فور الفتح",
  411. preload: "تحميل الصفحة التالية مسبقًا لتسريع الأداء",
  412. click2ImportRule: "انقر لاستيراد رابط القواعد الأساسية، ثم انتظر حتى يكتمل التحديث",
  413. forceAllBody: "دمج كامل الصفحة كإطار؟",
  414. openInNewTab: "فتح الروابط الإضافية في علامة تبويب جديدة",
  415. importSucc: "تم الاستيراد بنجاح",
  416. import: "استيراد",
  417. editCurrent: "تحرير القاعدة للحالية",
  418. editBlacklist: "تحرير عناوين القائمة السوداء، سطر بسطر، دعم؟ * للرموز المتحركة",
  419. upBtnImg: "أيقونة العودة إلى الأعلى",
  420. downBtnImg: "أيقونة الانتقال إلى الأسفل",
  421. sideControllerIcon: "أيقونة الشريط الجانبي",
  422. loadingTextTitle: "تحميل النص",
  423. dbClick2StopCtrl: "مفتاح Ctrl",
  424. dbClick2StopAlt: "مفتاح Alt",
  425. dbClick2StopShift: "مفتاح Shift",
  426. dbClick2StopMeta: "مفتاح Meta",
  427. dbClick2StopKey: "مفاتيح الاختصار",
  428. pageElementCss: "نمط مخصص لعناصر الصفحة الرئيسية",
  429. customCss: "مخصص بالكامل CSS نمط",
  430. firstAlert: "لم تستورد القاعدة الأساسية بعد، يرجى اختيار القاعدة المناسبة للاستيراد",
  431. picker: "محدد عناصر الصفحة Pagetual",
  432. closePicker: "إغلاق محدد Pagetual",
  433. pickerPlaceholder: "محدد العناصر، اتركه فارغًا إذا كنت لا تعرف",
  434. pickerCheck: "تحقق من المحدد ونسخ",
  435. switchSelector: "انقر للتبديل بين العناصر",
  436. gotoEdit: "اذهب لتحرير القاعدة بالمحدد الحالي",
  437. manualMode: "تعطيل الدمج/الربط، واستخدام مفتاح الاتجاه الأيمن يدويًا للتمرير، واستخدام مفتاح السهم الأيسر للرجوع",
  438. clickMode: "تعطيل الدمج/الربط، عند التمرير إلى نهاية الصفحة، سيتم النقر تلقائيًا على الصفحة التالية",
  439. pageBarMenu: "انقر على مركز شريط الصفحة لفتح قائمة التحديد",
  440. nextSwitch: "تبديل الرابط التالي",
  441. arrowToScroll: "انقر على مفتاح السهم الأيمن للتمرير التالي ومفتاح السهم الأيسر للتمرير السابق",
  442. sideController: "عرض شريط التحكم في التصفح الترقيم في الشريط الجانبي",
  443. sideControllerScroll: "تبديل التمرير",
  444. sideControllerAlways: "عرض دائمًا",
  445. hideLoadingIcon: "إخفاء رمز التحميل",
  446. hideBarArrow: "إخفاء سهم شريط الصفحة",
  447. duplicate: "تم تثبيت Pagetual مكرر، تحقق من مدير النصوص البرمجية الخاص بك!",
  448. forceStateIframe: "تضمين الصفحة بالكامل كإطار",
  449. forceStateDynamic: "تحميل المحتوى الديناميكي عبر الإطار",
  450. forceStateDisable: "تعطيل تحويل الصفحات على هذا الموقع",
  451. autoScrollRate: "سرعة التمرير (1~1000)",
  452. disableAutoScroll: "إيقاف التمرير التلقائي",
  453. enableAutoScroll: "تمكين التمرير التلقائي",
  454. toggleAutoScroll: "تبديل التمرير التلقائي",
  455. ruleRequest: "طلب قاعدة",
  456. page: "صفحة ",
  457. prevPage: "الصفحة السابقة",
  458. nextPage: "الصفحة التالية",
  459. errorRulesMustBeArray: "يجب أن تكون القواعد مصفوفة!",
  460. errorJson: "خطأ في JSON، تحقق مرة أخرى!",
  461. editSuccess: "تم التحرير بنجاح",
  462. errorWrongUrl: "عنوان URL خاطئ، تحقق مرة أخرى!",
  463. errorAlreadyExists: "موجود بالفعل!",
  464. settingsSaved: "تم حفظ الإعدادات، قم بالتحديث لعرض",
  465. iframe: "إطار",
  466. dynamic: "ديناميكي",
  467. reloadPage: "اكتمل التحرير، إعادة تحميل الصفحة الآن؟",
  468. copied: "تم النسخ",
  469. noValidContent: "لم يتم الكشف عن محتوى صالح، قد يكون الإجراء Captcha مطلوبًا، انقر لعرض",
  470. outOfDate: "النص البرمجي قديم، قم بالتحديث إلى الإصدار الأحدث في الوقت المناسب!",
  471. hideBarTips: "إخفاء شريط التحكم في التصفح الترقيم ، والتبديل لوضع كامل الصفحة",
  472. setConfigPage: "تعيين الصفحة الحالية كصفحة الإعداد الافتراضية",
  473. wedata2github: "تغيير عنوان الويب داتا إلى العنوان البديل المرآة, في مستودع جيت هاب",
  474. addOtherProp: "إضافة خاصية قاعدة",
  475. addNextSelector: "إضافة محتوى المحدد كـ nextLink",
  476. addPageSelector: "إضافة محتوى المحدد كـ pageElement",
  477. propName: "أدخل اسم خاصية القاعدة",
  478. propValue: "أدخل قيمة خاصية القاعدة",
  479. customFirst: "تجاهل ذاكرة التخزين المؤقت للقواعد المخصصة المحلية",
  480. rulesExample: "مثال على القواعد",
  481. lastPage: "تم الوصول إلى الصفحة الأخيرة",
  482. lastPageTips: "عرض تلميحات عند الوصول إلى الصفحة الأخيرة"
  483. }
  484. },
  485. {
  486. name: "简体中文",
  487. match: ["zh-CN", "zh-SG"],
  488. lang: {
  489. enableDebug: "调试模式,输出信息至控制台",
  490. updateNotification: "规则更新后提示",
  491. disable: "暂时禁用",
  492. disableSite: "站点禁用开关",
  493. disableSiteTips: "已在此站禁用",
  494. enableSiteTips: "已在此站启用",
  495. enable: "启用自动翻页",
  496. toTop: "回到顶部",
  497. toBottom: "前往页尾",
  498. current: "当前页",
  499. forceIframe: "强制拼接",
  500. cancelForceIframe: "取消强制拼接",
  501. configure: "打开配置页面",
  502. firstUpdate: "点击此处初始化规则",
  503. update: "更新在线规则",
  504. click2update: "点击立即更新规则",
  505. loadNow: "立即翻页",
  506. loadConfirm: "要翻几页?(0为不间断)",
  507. noNext: "没有找到下一页,请新建规则",
  508. passSec: "更新于 #t# 秒前",
  509. passMin: "更新于 #t# 分钟前",
  510. passHour: "更新于 #t# 小时前",
  511. passDay: "更新于 #t# 天前",
  512. cantDel: "无法删除内置规则",
  513. confirmDel: "是否确认要删除此规则?",
  514. updateSucc: "更新成功",
  515. beginUpdate: "正在更新,请耐心等待,不要关闭页面",
  516. customUrls: "导入 Pagetual 或 AutoPagerize 规则 url,一行一条",
  517. customRules: "输入【东方永页机】格式的自定义规则 <a href='#t#'>✍️贡献规则</a>",
  518. save: "保存设置",
  519. loadingText: "少女祈祷中...",
  520. opacity: "不透明值",
  521. opacityPlaceholder: "0: 隐藏分隔条",
  522. hideBar: "隐藏分页隔条",
  523. hideBarButNoStop: "隐藏但不停止",
  524. dbClick2Stop: "空白处双击暂停翻页",
  525. sortTitle: "排序在下次更新规则后生效",
  526. autoRun: "自动启用,否则为白名单模式",
  527. autoLoadNum: "自动加载指定页数",
  528. turnRate: "距离页尾【X】倍页面高度时就开始翻页",
  529. inputPageNum: "输入页码跳转",
  530. enableHistory: "翻页后写入历史记录",
  531. enableHistoryAfterInsert: "拼接后立即写入历史记录,否则浏览完毕后再行写入",
  532. contentVisibility: "自动切换 contentVisibility,提升渲染性能",
  533. initRun: "打开页面后立即尝试翻页,否则滚动至页尾再翻页",
  534. preload: "翻页前预读下一页,加速浏览",
  535. click2ImportRule: "点击下方任意一条添加规则库,并静待更新成功,请预先打开链接确认能正常访问再行导入:",
  536. forceAllBody: "是否拼接整个页面?",
  537. openInNewTab: "使拼接页面的内容在新页面打开",
  538. importSucc: "导入成功",
  539. import: "导入",
  540. editCurrent: "编辑此站规则",
  541. editBlacklist: "编辑黑名单网址,一行一条,支持? *通配符与正则",
  542. upBtnImg: "回到页首图标",
  543. downBtnImg: "前往页尾图标",
  544. sideControllerIcon: "侧边栏图标",
  545. loadingTextTitle: "加载中文字",
  546. dbClick2StopCtrl: "Ctrl",
  547. dbClick2StopAlt: "Alt",
  548. dbClick2StopShift: "Shift",
  549. dbClick2StopMeta: "Meta",
  550. dbClick2StopKey: "快捷键",
  551. pageElementCss: "页面主体框架的样式",
  552. customCss: "自定义 css",
  553. firstAlert: "你还未导入规则库,请选择合适的规则库导入哦",
  554. picker: "东方永页机主体元素抓取器",
  555. closePicker: "关闭东方永页机抓取器",
  556. pickerPlaceholder: "元素选择器,没想法建议留空",
  557. pickerCheck: "检查你编辑的选择器并复制",
  558. switchSelector: "点击切换元素",
  559. gotoEdit: "使用当前的选择器前往编辑规则",
  560. manualMode: "禁用拼接,手动用右方向键翻页,可使用左方向键返回",
  561. clickMode: "禁用拼接,滚动至页尾时自动点击下一页",
  562. pageBarMenu: "点击分隔条中间弹出菜单",
  563. nextSwitch: "切换其他页码",
  564. arrowToScroll: "左方向键滚动至上一页,右方向键滚动至下一页",
  565. sideController: "在侧边显示翻页控制栏",
  566. sideControllerScroll: "滚动开关",
  567. sideControllerAlways: "始终显示",
  568. hideLoadingIcon: "隐藏加载动画",
  569. hideBarArrow: "隐藏分隔条定位箭头",
  570. duplicate: "检测到永页机重复安装,请删除其他脚本管理器中的永页机!",
  571. forceStateIframe: "以 iframe 嵌入整页",
  572. forceStateDynamic: "通过 iframe 加载动态内容后取出",
  573. forceStateDisable: "在此站禁用",
  574. autoScrollRate: "滚动速度(1~1000)",
  575. disableAutoScroll: "停止自动滚动",
  576. enableAutoScroll: "开启自动滚动",
  577. toggleAutoScroll: "自动滚动开关",
  578. ruleRequest: "适配请求",
  579. page: "Page ",
  580. prevPage: "上一页",
  581. nextPage: "下一页",
  582. errorRulesMustBeArray: "规则必须为数组形式!",
  583. errorJson: "JSON 格式有错,请重新检查!",
  584. editSuccess: "编辑成功",
  585. errorWrongUrl: "URL 错误, 请重新检查!",
  586. errorAlreadyExists: "已经存在!",
  587. settingsSaved: "设置已保存,刷新后生效",
  588. iframe: "强制拼接",
  589. dynamic: "动态加载",
  590. reloadPage: "编辑完成,是否立即刷新页面?",
  591. copied: "已复制",
  592. noValidContent: "没有检测到有效内容,可能需要人机校验,点击查看",
  593. outOfDate: "脚本已过时,请及时更新到最新版本!",
  594. hideBarTips: "隐藏分页隔条,沉浸式体验",
  595. setConfigPage: "将当前页面设为默认配置页",
  596. wedata2github: "将 wedata 地址更改为 github 仓库内的镜像地址",
  597. addOtherProp: "添加规则属性",
  598. addNextSelector: "添加选择器内容为 nextLink",
  599. addPageSelector: "添加选择器内容为 pageElement",
  600. propName: "输入规则属性名",
  601. propValue: "输入规则属性值",
  602. customFirst: "为本地自定义规则忽略缓存",
  603. rulesExample: "自定义规则详解",
  604. lastPage: "已到达最后一页",
  605. lastPageTips: "到达最后一页时进行提示"
  606. }
  607. },
  608. {
  609. name: "正體中文",
  610. match: ["zh", "zh-TW", "zh-HK"],
  611. lang: {
  612. enableDebug: "調試模式,輸出信息至控制台",
  613. updateNotification: "規則更新后提示",
  614. disable: "暫時禁用",
  615. disableSite: "站點禁用開關",
  616. disableSiteTips: "已在此站禁用",
  617. enableSiteTips: "已在此站啟用",
  618. enable: "啟用自動翻頁",
  619. toTop: "回到頂部",
  620. toBottom: "前往頁尾",
  621. current: "當前頁",
  622. forceIframe: "強制拼接",
  623. cancelForceIframe: "取消强制拼接",
  624. configure: "打開配置頁面",
  625. firstUpdate: "點擊此處初始化規則",
  626. update: "更新在綫規則",
  627. click2update: "點擊立即更新規則",
  628. loadNow: "立即翻頁",
  629. loadConfirm: "要翻几頁?(0為不間斷)",
  630. noNext: "沒有找到下一頁,請新建規則",
  631. passSec: "更新于 #t# 秒前",
  632. passMin: "更新于 #t# 分鐘前",
  633. passHour: "更新于 #t# 小時前",
  634. passDay: "更新于 #t# 天前",
  635. cantDel: "無法刪除内置規則",
  636. confirmDel: "是否確認要刪除此規則?",
  637. updateSucc: "更新成功",
  638. beginUpdate: "正在更新,請稍候",
  639. customUrls: "導入 Pagetual 或 AutoPagerize 規則 url,一行一條",
  640. customRules: "輸入【東方永頁機】格式的自定義規則 <a href='#t#'>✍️貢獻規則</a>",
  641. save: "存儲設置",
  642. loadingText: "少女祈禱中...",
  643. opacity: "不透明值",
  644. opacityPlaceholder: "0: 隱藏分隔條",
  645. hideBar: "隱藏分頁隔條",
  646. hideBarButNoStop: "隱藏但不停止",
  647. dbClick2Stop: "空白處雙擊暫停翻頁",
  648. sortTitle: "排序在下次更新規則後生效",
  649. autoRun: "自動啓用,否則為白名單模式",
  650. autoLoadNum: "自動加載指定頁數",
  651. turnRate: "距離頁尾【X】倍頁面高度時就開始翻頁",
  652. inputPageNum: "輸入頁碼跳轉",
  653. enableHistory: "翻頁后寫入歷史記錄",
  654. enableHistoryAfterInsert: "拼接後立即寫入歷史記錄,否則瀏覽完畢後再行寫入",
  655. contentVisibility: "自動切換 contentVisibility,提升渲染性能",
  656. initRun: "打開頁面后立即嘗試翻頁,否則滾動至頁尾再翻頁",
  657. preload: "翻頁前預讀下一頁,加速瀏覽",
  658. click2ImportRule: "點擊下方添加特殊規則庫,并靜待更新成功:",
  659. forceAllBody: "是否拼接整個頁面?",
  660. openInNewTab: "使拼接頁面的内容在新頁面打開",
  661. importSucc: "導入成功",
  662. import: "導入",
  663. editCurrent: "編輯此站規則",
  664. editBlacklist: "編輯黑名單網址,一行一條,支持? *通配符與正則",
  665. upBtnImg: "回到頁首圖標",
  666. downBtnImg: "前往頁尾圖標",
  667. sideControllerIcon: "側邊欄圖標",
  668. loadingTextTitle: "加載中文字",
  669. dbClick2StopCtrl: "Ctrl",
  670. dbClick2StopAlt: "Alt",
  671. dbClick2StopShift: "Shift",
  672. dbClick2StopMeta: "Meta",
  673. dbClick2StopKey: "快捷鍵",
  674. pageElementCss: "頁面主體框架的樣式",
  675. customCss: "自定義 css",
  676. firstAlert: "你還未導入規則庫,請選擇合適的規則庫導入哦",
  677. picker: "東方永頁機主體元素抓取器",
  678. closePicker: "關閉東方永頁機抓取器",
  679. pickerPlaceholder: "元素選擇器,沒想法建議留空",
  680. pickerCheck: "檢查你編輯的選擇器並複製",
  681. switchSelector: "點擊切換元素",
  682. gotoEdit: "使用當前的選擇器前往編輯規則",
  683. manualMode: "禁用拼接,手動用右方向鍵翻頁,左方向鍵返回",
  684. clickMode: "禁用拼接,滾動至頁尾時自動點擊下一頁",
  685. pageBarMenu: "點擊分隔條中間彈出菜單",
  686. nextSwitch: "切換其他頁碼",
  687. arrowToScroll: "左方向鍵滾動至上一頁,右方向鍵滾動至下一頁",
  688. sideController: "在側邊顯示翻頁控制欄",
  689. sideControllerScroll: "滾燈開關",
  690. sideControllerAlways: "始終顯示",
  691. hideLoadingIcon: "隱藏加載動畫",
  692. hideBarArrow: "隱藏分隔條定位箭頭",
  693. duplicate: "檢測到永頁機重複安裝,請刪除其他腳本管理器中的永頁機!",
  694. forceStateIframe: "以 iframe 嵌入整頁",
  695. forceStateDynamic: "通過 iframe 加載動態內容後取出",
  696. forceStateDisable: "在此站禁用",
  697. autoScrollRate: "滾動速度(1~1000)",
  698. disableAutoScroll: "停止自動滾動",
  699. enableAutoScroll: "開啟自動滾動",
  700. toggleAutoScroll: "自動滾動開關",
  701. ruleRequest: "適配請求",
  702. page: "Page ",
  703. prevPage: "上一頁",
  704. nextPage: "下一頁",
  705. errorRulesMustBeArray: "規則必須為陣列形式!",
  706. errorJson: "JSON 格式有錯,請重新檢查!",
  707. editSuccess: "編輯成功",
  708. errorWrongUrl: "URL 錯誤, 請重新檢查!",
  709. errorAlreadyExists: "已經存在!",
  710. settingsSaved: "設置已保存,刷新後生效",
  711. iframe: "強制拼接",
  712. dynamic: "動態加載",
  713. reloadPage: "編輯完成,是否立即刷新頁面?",
  714. copied: "已復制",
  715. noValidContent: "沒有檢測到有效内容,可能需要人機校驗,點擊查看",
  716. outOfDate: "脚本已過時,請及時更新到最新版本!",
  717. hideBarTips: "隱藏分頁隔條,沉浸式體驗",
  718. setConfigPage: "將當前頁面設為默認配置頁",
  719. wedata2github: "將 wedata 地址更改為 github 倉庫內的鏡像地址",
  720. addOtherProp: "添加規則屬性",
  721. addNextSelector: "添加選擇器內容為 nextLink",
  722. addPageSelector: "添加選擇器內容為 pageElement",
  723. propName: "輸入規則屬性名",
  724. propValue: "輸入規則屬性值",
  725. customFirst: "為本地自定義規則忽略緩存",
  726. rulesExample: "自定義規則詳解",
  727. lastPage: "已到達最後一頁",
  728. lastPageTips: "到達最後一頁時進行提示"
  729. }
  730. },
  731. {
  732. name: "日本語",
  733. match: ["ja"],
  734. lang: {
  735. enableDebug: "デバッグモード",
  736. updateNotification: "ルール更新後の通知",
  737. disable: "一時的に無効",
  738. disableSite: "無効状態の切り替え",
  739. disableSiteTips: "このサイトで既に無効になっています",
  740. enableSiteTips: "このサイトで既に有効になっています",
  741. enable: "ページめくりを有効にする",
  742. toTop: "トップに戻る",
  743. toBottom: "ページの下部に移動",
  744. current: "現在のページ",
  745. forceIframe: "強制ステッチ",
  746. cancelForceIframe: "強制ステッチをキャンセル",
  747. configure: "設定ページを開く",
  748. firstUpdate: "ここをクリックしてルールを初期化します",
  749. update: "更新ルール",
  750. click2update: "今すぐルールを更新してください",
  751. loadNow: "今すぐページをめくる",
  752. loadConfirm: "数ページめくりたいですか?(0は途切れない)",
  753. noNext: "次のページが見つかりません、新しいルールを作成してください",
  754. passSec: "#t#秒前に更新",
  755. passMin: "#t#分前に更新",
  756. passHour: "#t#時間前に更新",
  757. passDay: "#t#日前に更新",
  758. cantDel: "組み込みルールを削除できません",
  759. confirmDel: "このルールを削除してもよろしいですか?",
  760. updateSucc: "更新に成功しました",
  761. beginUpdate: "更新中、お待ちください",
  762. customUrls: "インポートルールのURL、1行に1つ",
  763. customRules: "【東方永頁機】の形式でカスタムルールを入力してください <a href='#t#'>✍️寄稿ルール</a>",
  764. save: "設定を保存",
  765. loadingText: "少女祈祷中...",
  766. opacity: "不透明値",
  767. opacityPlaceholder: "0: 隠す",
  768. hideBar: "ページ区切り文字を非表示にします",
  769. hideBarButNoStop: "非表示にするが停止しない",
  770. dbClick2Stop: "空白部分をダブルクリックしてページめくりを一時停止します",
  771. sortTitle: "並べ替えは、次のルールの更新後に有効になります",
  772. autoRun: "自動的に有効",
  773. autoLoadNum: "指定したページ数を自動的に読み込みます",
  774. turnRate: "ページの端からページの高さの【X】倍になったらページをめくる",
  775. inputPageNum: "ジャンプするページ番号を入力",
  776. enableHistory: "ページめくり後の履歴を書く",
  777. enableHistoryAfterInsert: "スプライシングの直後に履歴レコードを書き込みます。それ以外の場合は、閲覧後に書き込みます",
  778. contentVisibility: "contentVisibility を自動的に切り替えてレンダリング パフォーマンスを向上させる",
  779. initRun: "Webページを開いた直後にページをめくる",
  780. preload: "事前に次のページを読む",
  781. click2ImportRule: "以下をクリックして、ルールベースを追加します:",
  782. forceAllBody: "フルページ埋め込み?",
  783. openInNewTab: "スプライスされたページのコンテンツを新しいページで開きます",
  784. importSucc: "インポート完了",
  785. import: "インポート",
  786. editCurrent: "現在のルールの編集",
  787. editBlacklist: "ブラックリストのURLを編集し、1行ずつ、サポート? *ワイルドカード",
  788. upBtnImg: "トップアイコンに戻る",
  789. downBtnImg: "フッターアイコンに移動",
  790. sideControllerIcon: "サイドバー アイコン",
  791. loadingTextTitle: "テキストをロード",
  792. dbClick2StopCtrl: "Ctrlキー",
  793. dbClick2StopAlt: "Altキー",
  794. dbClick2StopShift: "Shiftキー",
  795. dbClick2StopMeta: "Metaキー",
  796. dbClick2StopKey: "Shortcutキー",
  797. pageElementCss: "ページ本文フレームの STYLE",
  798. customCss: "カスタム css",
  799. firstAlert: "ルールベースをインポートしていないため、インポートする適切なルールベースを選択してください",
  800. picker: "Pagetualページ要素ピッカー",
  801. closePicker: "Pagetualピッカーを閉じる",
  802. pickerPlaceholder: "わからない場合は空のままにしてください",
  803. pickerCheck: "セレクターをチェックしてコピー",
  804. switchSelector: "クリックして要素を切り替えます",
  805. gotoEdit: "現在のセレクターでルールを編集する",
  806. manualMode: "スプライシングを無効にします。手動で右の矢印キーを使用してページをめくります",
  807. clickMode: "スティッチングを無効にします。ページの最後までスクロールすると、次のページが自動的にクリックされます",
  808. pageBarMenu: "ページバーの中央をクリックしてメニューをポップアップ表示",
  809. nextSwitch: "次のページに切り替え",
  810. arrowToScroll: "左矢印キーで前へ、右矢印キーで次へ",
  811. sideController: "サイドバーにページング コントロール バーを表示する",
  812. sideControllerScroll: "スクロール スイッチ",
  813. sideControllerAlways: "常に表示",
  814. hideLoadingIcon: "読み込み中のアニメーションを隠す",
  815. hideBarArrow: "分割線の位置矢印を隠す",
  816. duplicate: "Pagetual の重複インストールが検出されました。他のスクリプト マネージャで永続的なページ マシンを削除してください!",
  817. forceStateIframe: "iframe にページ全体を埋め込む",
  818. forceStateDynamic: "iframe 経由で動的コンテンツを読み込む",
  819. forceStateDisable: "このステーションでのページめくりを無効にする",
  820. autoScrollRate: "スクロール速度 (1~1000)",
  821. disableAutoScroll: "自動スクロールを停止します",
  822. EnableAutoScroll: "自動スクロールを有効にする",
  823. toggleAutoScroll: "自動スクロールの切り替え",
  824. ruleRequest: "ルール要求",
  825. page: "Page ",
  826. prevPage: "Prev page",
  827. nextPage: "Next page",
  828. errorRulesMustBeArray: "Rules must be a Array!",
  829. errorJson: "JSON error, check again!",
  830. editSuccess: "Edit successfully",
  831. errorWrongUrl: "Wrong url, check again!",
  832. errorAlreadyExists: "Already exists!",
  833. settingsSaved: "The settings are saved, refresh to view",
  834. iframe: "Iframe",
  835. dynamic: "Dynamic",
  836. reloadPage: "Edit completed, reload page now?",
  837. copied: "Copied",
  838. noValidContent: "有効なコンテンツが検出されませんでした。クリックして表示",
  839. outOfDate: "スクリプトが古くなっています。最新バージョンに更新してください。",
  840. hideBarTips: "ページネーション バーを非表示にします。没入型エクスペリエンス",
  841. setConfigPage: "現在のページをデフォルト設定ページとして設定",
  842. wedata2github: "wedata アドレスを github ウェアハウスのミラー アドレスに変更",
  843. addOtherProp: "ルールプロパティを追加",
  844. addNextSelector: "セレクターのコンテンツを nextLink として追加",
  845. addPageSelector: "セレクタ コンテンツを pageElement として追加",
  846. propName: "ルールのプロパティ名を入力してください",
  847. propValue: "ルールのプロパティ値を入力してください",
  848. customFirst: "ローカルカスタムルールのキャッシュを無視する",
  849. rulesExample: "カスタムルールの詳しい説明",
  850. lastPage: "最後のページに到達しました",
  851. lastPageTips: "最後のページに到達した時にヒントを表示する"
  852. }
  853. },
  854. {
  855. name: "Русский",
  856. match: ["ru", "ru-RU"],
  857. lang: {
  858. enableDebug: "Включить отладку",
  859. updateNotification: "Уведомление после обновления правила",
  860. disable: "Выключить",
  861. disableSite: "Включить/выключить на сайте",
  862. disableSiteTips: "Выключено для этого сайта",
  863. enableSiteTips: "Включено для этого сайта",
  864. enable: "Включить",
  865. toTop: "Наверх",
  866. toBottom: "Вниз",
  867. current: "Текущая страница",
  868. forceIframe: "Подгрузить ещё страницу",
  869. cancelForceIframe: "Отменить подгрузку",
  870. configure: "Настройки",
  871. firstUpdate: "Нажмите здесь, чтобы инициализировать правила",
  872. update: "Обновить правила",
  873. click2update: "Нажмите, чтобы обновить правила",
  874. loadNow: "Загрузить следующую страницу",
  875. loadConfirm: "Сколько страниц вы хотите загрузить? (0 означает бесконечность)",
  876. noNext: "Ссылка на следующую страницу не найдена. Пожалуйста, создайте новое правило",
  877. passSec: "Обновлено #t# секунд назад",
  878. passMin: "Обновлено #t# минут назад",
  879. passHour: "Обновлено #t# часов назад",
  880. passDay: "Обновлено #t# дней назад",
  881. cantDel: "Нельзя удалить правила по умолчанию",
  882. confirmDel: "Вы уверены, что хотите удалить эту ссылку?",
  883. updateSucc: "Правила обновлены",
  884. beginUpdate: "Обновление. Пожалуйста, немного подождите",
  885. customUrls: "Ссылки с правилами для импорта. Одна ссылка на строку",
  886. customRules: "Введите пользовательские правила в формате Pagetual. <a href='#t#'>✍️Улучшить встроенные правила</a>",
  887. save: "Сохранить настройки",
  888. loadingText: "Следующая страница подгружается…",
  889. opacity: "Прозрачность",
  890. opacityPlaceholder: "0 - скрыть",
  891. hideBar: "Скрыть разделитель страниц",
  892. hideBarButNoStop: "Скрыть, но не останавливать",
  893. dbClick2Stop: "Двойной клик на странице для выключения",
  894. sortTitle: "Правило сортировки применится после следующего обновления правил",
  895. autoRun: "Автозапуск (режим черного списка)",
  896. autoLoadNum: "Количество страниц для предзагрузки",
  897. turnRate: "Подгрузить страницу, когда она будет в 【X】 раз больше высоты страницы от конца страницы",
  898. inputPageNum: "Введите номер страницы для перехода",
  899. enableHistory: "Записать историю после переключения страниц",
  900. enableHistoryAfterInsert: "Записать запись истории сразу после вставки, иначе записать после просмотра",
  901. contentVisibility: "Автоматически переключать contentVisibility для повышения производительности рендеринга",
  902. initRun: "Подгружать страницы сразу после открытия",
  903. preload: "Предзагрузка следующей страницы",
  904. click2ImportRule: "Нажмите, чтобы импортировать базовые правила: ",
  905. forceAllBody: "Присоединить страницу целиком?",
  906. openInNewTab: "Открыть дополнительные ссылки в новой вкладке",
  907. importSucc: "Импорт завершен",
  908. import: "Импорт",
  909. editCurrent: "Изменить правило для текущего сайта",
  910. editBlacklist: "Изменить черный список. Одна ссылка на строку. Поддерживаются метасимволы: ? и *",
  911. upBtnImg: "Иконка перехода к началу",
  912. downBtnImg: "Иконка перехода к концу",
  913. sideControllerIcon: "Значок боковой панели",
  914. loadingTextTitle: "Текст во время загрузки",
  915. dbClick2StopCtrl: "Ctrl",
  916. dbClick2StopAlt: "Alt",
  917. dbClick2StopShift: "Shift",
  918. dbClick2StopMeta: "Meta",
  919. dbClick2StopKey: "Клавиша",
  920. pageElementCss: "Пользовательский стиль для основных элементов страницы",
  921. customCss: "Полный пользовательский CSS",
  922. firstAlert: "Вы не импортировали базовое правило. Пожалуйста, выберите соответствующее правило для импорта",
  923. picker: "Pagetual: выбор элемента страницы",
  924. closePicker: "Закрыть окно Pagetual",
  925. pickerPlaceholder: "Если не знаете, что тут писать — оставьте поле пустым",
  926. pickerCheck: "Проверить и скопировать селектор",
  927. switchSelector: "Нажмите для выбора элемента",
  928. gotoEdit: "Перейти к редактированию правила с текущим селектором",
  929. manualMode: "Отключить автоматическую загрузку страниц. Загружать вручную с помощью стрелки вправо (или вызова события 'pagetual.next')",
  930. clickMode: "Отключить \"сшивание\" страниц. При прокрутке до конца автоматически переходить на следующую страницу",
  931. pageBarMenu: "Открывать меню кликом на середину панели страниц",
  932. nextSwitch: "Переключить ссылку на следующую страницу",
  933. arrowToScroll: "Листать страницы клавишами со стрелками влево и вправо",
  934. sideController: "Показать справа панель перемещения по вкладке",
  935. sideControllerScroll: "Переключатель прокрутки",
  936. sideControllerAlways: "Всегда показывать",
  937. hideLoadingIcon: "Скрыть анимацию загрузки",
  938. hideBarArrow: "Скрыть кнопки перемещения на разделителе",
  939. duplicate: "Похоже, Pagetual установлен несколько раз. Пожалуйста, удалите Pagetual из других менеджеров скриптов!",
  940. forceStateIframe: "Вставить полную страницу как iframe",
  941. forceStateDynamic: "Загружать динамический контент через iframe",
  942. forceStateDisable: "Отключить перелистывание страниц на этой станции",
  943. autoScrollRate: "Скорость прокрутки (1~1000)",
  944. disableAutoScroll: "Остановить автоматическую прокрутку",
  945. enableAutoScroll: "Включить автопрокрутку",
  946. toggleAutoScroll: "Переключить автопрокрутку",
  947. ruleRequest: "Запрос правил",
  948. page: "Страница ",
  949. prevPage: "Предыдущая страница",
  950. nextPage: "Следующая страница",
  951. errorRulesMustBeArray: "Правила должны быть массивом!",
  952. errorJson: "Ошибка разбора JSON. Пожалуйста, исправьте его",
  953. editSuccess: "Редактирование успешно",
  954. errorWrongUrl: "Ссылка некорректна. Пожалуйста, исправьте её",
  955. errorAlreadyExists: "Уже существует!",
  956. settingsSaved: "Настройки сохранены. Обновите страницы",
  957. iframe: "iframe",
  958. dynamic: "Динамически",
  959. reloadPage: "Редактирование завершено. Обновить страницу?",
  960. copied: "Скопировано",
  961. noValidContent: "Действительный контент не обнаружен, нажмите для просмотра",
  962. outOfDate: "Скрипт устарел, своевременно обновляйте до последней версии!",
  963. hideBarTips: "Скрыть панель разбиения на страницы, иммерсивный опыт",
  964. setConfigPage: "Установить текущую страницу в качестве страницы конфигурации по умолчанию",
  965. wedata2github: "Изменить адрес wedata на зеркальный адрес на складе github",
  966. addOtherProp: "Добавить свойство правила",
  967. addNextSelector: "Добавить содержимое селектора как nextLink",
  968. addPageSelector: "Добавить содержимое селектора как pageElement",
  969. propName: "Введите имя свойства правила",
  970. propValue: "Введите значение свойства правила",
  971. customFirst: "Игнорировать кеш для локальных пользовательских правил",
  972. rulesExample: "Подробное объяснение настраиваемых правил",
  973. lastPage: "Достигнута последняя страница",
  974. lastPageTips: "Показывать подсказки при достижении последней страницы"
  975. }
  976. }
  977. ];
  978. var langList = {};
  979. langData.forEach(lang => {
  980. langList[lang.match[0]] = lang.name;
  981. });
  982. var i18nData = langData[0].lang;
  983. function setLang(la) {
  984. for (let i = 0; i < langData.length; i++) {
  985. let lang = langData[i];
  986. if (lang && lang.match.indexOf(la) !== -1) {
  987. i18nData = lang.lang;
  988. break;
  989. }
  990. }
  991. }
  992. setLang(lang);
  993. var enableDebug = true;
  994. var _GM_xmlhttpRequest, _GM_registerMenuCommand, _GM_notification, _GM_addStyle, _GM_openInTab, _GM_info, _GM_setClipboard;
  995. function i18n(name, param) {
  996. return i18nData[name] ? i18nData[name].replace("#t#", param) : name;
  997. }
  998.  
  999. function debug(str, title) {
  1000. if (enableDebug) {
  1001. console.log(
  1002. `%cPagetual v.${_GM_info.script.version}】 ${title ? title : 'debug'}:`,
  1003. 'color: yellow;font-size: large;font-weight: bold;background-color: darkblue;',
  1004. str
  1005. );
  1006. }
  1007. }
  1008.  
  1009. if (typeof GM_xmlhttpRequest !== 'undefined') {
  1010. _GM_xmlhttpRequest = GM_xmlhttpRequest;
  1011. } else if (typeof GM !== 'undefined' && typeof GM.xmlHttpRequest !== 'undefined') {
  1012. _GM_xmlhttpRequest = GM.xmlHttpRequest;
  1013. } else {
  1014. _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())};
  1015. }
  1016. if (typeof GM_registerMenuCommand !== 'undefined') {
  1017. _GM_registerMenuCommand = GM_registerMenuCommand;
  1018. } else if (typeof GM !== 'undefined' && typeof GM.registerMenuCommand !== 'undefined') {
  1019. _GM_registerMenuCommand = GM.registerMenuCommand;
  1020. } else {
  1021. _GM_registerMenuCommand = (s, f) => {debug(s); debug(f);};
  1022. }
  1023. if (typeof GM_info !== 'undefined') {
  1024. _GM_info = GM_info;
  1025. } else if (typeof GM !== 'undefined' && typeof GM.info !== 'undefined') {
  1026. _GM_info = GM.info;
  1027. } else {
  1028. _GM_info = {script: {}};
  1029. }
  1030. if (typeof GM_notification !== 'undefined') {
  1031. _GM_notification = GM_notification;
  1032. } else if (typeof GM !== 'undefined' && typeof GM.notification !== 'undefined') {
  1033. _GM_notification = GM.notification;
  1034. } else {
  1035. _GM_notification = (s) => {showTips(String(s.text || s));};
  1036. }
  1037. if (typeof GM_openInTab !== 'undefined') {
  1038. _GM_openInTab = GM_openInTab;
  1039. } else if (typeof GM !== 'undefined' && typeof GM.openInTab !== 'undefined') {
  1040. _GM_openInTab = GM.openInTab;
  1041. } else {
  1042. _GM_openInTab = (s,t) => {window.open(s); debug(t);};
  1043. }
  1044. if (typeof GM_addStyle !== 'undefined') {
  1045. _GM_addStyle = GM_addStyle;
  1046. } else if (typeof GM !== 'undefined' && typeof GM.addStyle !== 'undefined') {
  1047. _GM_addStyle = GM.addStyle;
  1048. } else {
  1049. _GM_addStyle = cssStr => {
  1050. let styleEle = document.createElement("style");
  1051. styleEle.innerHTML = cssStr;
  1052. document.head.appendChild(styleEle);
  1053. return styleEle;
  1054. };
  1055. }
  1056. if (typeof GM_setClipboard !== 'undefined') {
  1057. _GM_setClipboard = GM_setClipboard;
  1058. } else if (typeof GM !== 'undefined' && typeof GM.setClipboard !== 'undefined') {
  1059. _GM_setClipboard = GM.setClipboard;
  1060. } else {
  1061. _GM_setClipboard = (s, i) => {debug(s); debug(i);};
  1062. }
  1063. const _unsafeWindow = (typeof unsafeWindow === 'undefined') ? window : unsafeWindow;//兼容 ios userscripts 的寫法
  1064. const storage = {
  1065. supportGM: typeof GM_getValue === 'function' && typeof GM_getValue('a', 'b') !== 'undefined',
  1066. supportGMPromise: typeof GM !== 'undefined' && typeof GM.getValue === 'function' && typeof GM.getValue('a', 'b') !== 'undefined' && typeof GM.getValue('a', 'b').then === 'function',
  1067. supportCrossSave: function() {
  1068. return this.supportGM || this.supportGMPromise;
  1069. },
  1070. mxAppStorage: (function() {
  1071. try {
  1072. return window.external.mxGetRuntime().storage;
  1073. } catch(e) {
  1074. }
  1075. })(),
  1076. operaUJSStorage: (function() {
  1077. try {
  1078. return window.opera.scriptStorage;
  1079. } catch(e) {
  1080. }
  1081. })(),
  1082. setItem: function(key, value) {
  1083. if (this.supportGMPromise) {
  1084. GM.setValue(key, value);
  1085. if (value === "" && typeof GM !== 'undefined' && typeof GM.deleteValue !== 'undefined') {
  1086. GM.deleteValue(key);
  1087. }
  1088. } else if (this.supportGM) {
  1089. GM_setValue(key, value);
  1090. if (value === "" && typeof GM_deleteValue !== 'undefined') {
  1091. GM_deleteValue(key);
  1092. }
  1093. } else if (this.operaUJSStorage) {
  1094. this.operaUJSStorage.setItem(key, value);
  1095. } else if (this.mxAppStorage) {
  1096. this.mxAppStorage.setConfig(key, value);
  1097. } else if (window.localStorage) {
  1098. window.localStorage.setItem(key, value);
  1099. }
  1100. },
  1101. getItem: function(key, cb) {
  1102. var value;
  1103. if (this.supportGMPromise) {
  1104. value = GM.getValue(key).then(v => {cb(v);});
  1105. return;
  1106. } else if (this.supportGM) {
  1107. value = GM_getValue(key);
  1108. } else if (this.operaUJSStorage) {
  1109. value = this.operaUJSStorage.getItem(key);
  1110. } else if (this.mxAppStorage) {
  1111. value = this.mxAppStorage.getConfig(key);
  1112. } else if (window.localStorage) {
  1113. value = window.localStorage.getItem(key);
  1114. }
  1115. cb(value);
  1116. }
  1117. };
  1118. async function getData(key) {
  1119. return new Promise((resolve) => {
  1120. storage.getItem(key, value => {
  1121. resolve(value);
  1122. });
  1123. });
  1124. }
  1125. async function getListData(list, key) {
  1126. return new Promise((resolve) => {
  1127. storage.getItem(list, listData => {
  1128. let value;
  1129. if (listData) {
  1130. for(var i = 0; i < listData.length; i++) {
  1131. let data = listData[i];
  1132. if (data.k === key) {
  1133. value = data.v;
  1134. break;
  1135. }
  1136. }
  1137. }
  1138. resolve(value);
  1139. });
  1140. });
  1141. }
  1142. function setListData(list, key, value, length) {
  1143. storage.getItem(list, listData => {
  1144. if (!listData) {
  1145. listData = [];
  1146. }
  1147. listData = listData.filter(data => data && data.k !== key);
  1148. if (value !== "") {
  1149. listData.unshift({k: key, v: value});
  1150. if (listData.length > (length || 100)) {
  1151. listData.pop();
  1152. }
  1153. }
  1154. storage.setItem(list, listData);
  1155. });
  1156. }
  1157. const isMobile = ('ontouchstart' in document.documentElement);
  1158. const configPage = [`https://pagetual.hoothin.com/${lang === 'zh-CN' ? 'cn/' : ''}rule.html`,
  1159. "https://github.com/hoothin/UserScripts/tree/master/Pagetual",
  1160. "https://hoothin.github.io/UserScripts/Pagetual/"];
  1161. const firstRunPage = "https://pagetual.hoothin.com/firstRun";
  1162. const guidePage = /^https?:\/\/.*pagetual.*rule\.html/i;
  1163. const ruleImportUrlReg = /greasyfork\.org\/.*scripts\/438684(\-[^\/]*)?(\/discussions|\/?$|\/feedback)|github\.com\/hoothin\/UserScripts\/(tree\/master\/Pagetual|issues)/i;
  1164. const allOfBody = "body>*";
  1165. const mainSel = ["article,.article","[role=main],main,.main,#main","#results"];
  1166. 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");
  1167. 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");
  1168. 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"];
  1169. var rulesData = {uninited: true, firstRun: true, sideController: !isMobile}, ruleUrls, updateDate, clickedSth = false, loadNowNum = 5, autoScrollRate = 50;
  1170. 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;
  1171. var tryTimes = 0, showedLastPageTips = false, rate = 1, author = '';
  1172.  
  1173. function getBody(doc) {
  1174. return doc.body || doc.querySelector('body') || doc;
  1175. }
  1176.  
  1177. function getElementByXpath(xpath, doc, contextNode) {
  1178. if (doc && doc.ownerDocument) doc = doc.ownerDocument;
  1179. doc = (doc && doc.evaluate) ? doc : document;
  1180. contextNode = contextNode || doc;
  1181. try {
  1182. let result = doc.evaluate(xpath, contextNode, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  1183. return result.singleNodeValue && result.singleNodeValue.nodeType === 1 && result.singleNodeValue;
  1184. } catch (err) {
  1185. debug(`Invalid xpath: ${xpath}`);
  1186. }
  1187. return null;
  1188. }
  1189.  
  1190. function getAllElementsByXpath(xpath, contextNode, doc) {
  1191. if (doc && doc.ownerDocument) doc = doc.ownerDocument;
  1192. doc = (doc && doc.evaluate) ? doc : document;
  1193. contextNode = contextNode || doc;
  1194. var result = [];
  1195. try {
  1196. var query = doc.evaluate(xpath, contextNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  1197. for (var i = 0; i < query.snapshotLength; i++) {
  1198. var node = query.snapshotItem(i);
  1199. if (node.nodeType === 1) {
  1200. result.push(node);
  1201. }
  1202. }
  1203. } catch (err) {
  1204. debug(`Invalid xpath: ${xpath}`);
  1205. }
  1206. return result;
  1207. }
  1208.  
  1209. function isXPath(xpath) {
  1210. if (!xpath) {
  1211. return false;
  1212. }
  1213. return /^\(*(descendant::|\.\/|\/|id\()/.test(xpath);
  1214. }
  1215.  
  1216. function getAllElements(sel, doc, contextNode) {
  1217. try {
  1218. if (!isXPath(sel)) {
  1219. return doc.querySelectorAll(sel);
  1220. }
  1221. } catch(e) {
  1222. debug(e, 'Error selector');
  1223. }
  1224. return getAllElementsByXpath(sel, contextNode, doc);
  1225. }
  1226.  
  1227. function getElement(sel, doc, contextNode, bySort) {
  1228. try {
  1229. if (!isXPath(sel)) {
  1230. if (!bySort) {
  1231. return doc.querySelector(sel);
  1232. } else {
  1233. let selArr = sel.split(",");
  1234. try {
  1235. for (let i = 0; i < selArr.length; i++) {
  1236. let ele = doc.querySelector(selArr[i].trim());
  1237. if (ele) {
  1238. return ele;
  1239. }
  1240. }
  1241. } catch(e) {
  1242. return doc.querySelector(sel);
  1243. }
  1244. return null;
  1245. }
  1246. }
  1247. } catch(e) {
  1248. debug(e, 'Error selector');
  1249. }
  1250. return getElementByXpath(sel, doc, contextNode);
  1251. }
  1252.  
  1253. function compareNodeName(node, names) {
  1254. if (!node || !node.nodeName || !node.nodeName.toLowerCase) {
  1255. return false;
  1256. }
  1257. let nodeName = node.nodeName.toLowerCase();
  1258. for (let i = 0; i < names.length; i++) {
  1259. if (names[i] === nodeName) {
  1260. return true;
  1261. }
  1262. }
  1263. return false;
  1264. }
  1265.  
  1266. function geneSelector(ele, addID, exact) {
  1267. let selector = ele.nodeName.toLowerCase();
  1268. //Google id class都是隨機。百度更過分,style script順序都是隨機的
  1269. if (selector !== "html" && selector !== "body") {
  1270. let hasId = false;
  1271. if (addID && ele.id && /^[a-z_][\w\-_]*$/i.test(ele.id)) {
  1272. if (ele.ownerDocument && ele.ownerDocument.querySelectorAll("#" + ele.id).length === 1) {
  1273. hasId = true;
  1274. selector = '#' + ele.id;
  1275. }
  1276. }
  1277. if (!hasId) {
  1278. let className = "";
  1279. if (ele.className) {
  1280. let classList = ele.classList;
  1281. for (let i = 0; i < classList.length; i++) {
  1282. let c = classList[i];
  1283. if (c !== 'scrolling' && /^[a-z_][\w\-_]*$/.test(c) && !/\d{4,}/.test(c)) {
  1284. className += '.' + c;
  1285. }
  1286. }
  1287. selector += className;
  1288. }
  1289. let parent = ele.parentElement;
  1290. if (parent) {
  1291. if (exact) {
  1292. let i, nth = 0, all = 0;
  1293. for (i = 0; i < parent.children.length; i++) {
  1294. if (parent.children[i].nodeName === ele.nodeName) {
  1295. all++;
  1296. if (parent.children[i] === ele) {
  1297. nth = all;
  1298. }
  1299. if (nth > 0 && all > 1) {
  1300. break;
  1301. }
  1302. }
  1303. }
  1304. selector += (all === 1 ? "" : `:nth-of-type(${nth})`);
  1305. } else if (!className && !hasId && parent.children.length > 1 && !compareNodeName(parent, ["html"])) {
  1306. let prevE = ele.previousElementSibling;
  1307. if (prevE && prevE.className) {
  1308. let classList = prevE.classList;
  1309. for (let i = 0; i < classList.length; i++) {
  1310. let c = classList[i];
  1311. if (c !== 'scrolling' && /^[a-z_][\w\-_]*$/.test(c) && !/\d{4,}/.test(c)) {
  1312. className += '.' + c;
  1313. }
  1314. }
  1315. if (className) {
  1316. selector = prevE.nodeName.toLowerCase() + className + "+" + selector;
  1317. }
  1318. }
  1319. if (!className) {
  1320. let i, nth = 0, all = 0;
  1321. for (i = 0; i < parent.children.length; i++) {
  1322. if (parent.children[i].nodeName === ele.nodeName) {
  1323. all++;
  1324. if (parent.children[i] === ele) {
  1325. nth = all;
  1326. }
  1327. if (nth > 0 && all > 1) {
  1328. break;
  1329. }
  1330. }
  1331. }
  1332. selector += (all === 1 ? "" : `:nth-of-type(${nth})`);
  1333. }
  1334. }
  1335. selector = geneSelector(parent, addID, exact) + ' > ' + selector;
  1336. }
  1337. }
  1338. }
  1339. return selector;
  1340. }
  1341.  
  1342. function createXPathFromElement(elm) {
  1343. let allNodes = document.getElementsByTagName('*'), segs;
  1344. for (segs = []; elm && elm.nodeType === 1; elm = elm.parentNode) {
  1345. if (compareNodeName(elm, ["body", "html"])) {
  1346. segs.unshift(elm.localName.toLowerCase());
  1347. continue;
  1348. }
  1349. if (elm.hasAttribute && elm.hasAttribute('id')) {
  1350. var uniqueIdCount = 0;
  1351. for (var n = 0; n < allNodes.length; n++) {
  1352. if (allNodes[n].hasAttribute('id') && allNodes[n].id === elm.id) {
  1353. uniqueIdCount++;
  1354. }
  1355. if (uniqueIdCount > 1) {
  1356. break;
  1357. }
  1358. }
  1359. if ( uniqueIdCount === 1) {
  1360. segs.unshift('id("' + elm.getAttribute('id') + '")');
  1361. return segs.join('/');
  1362. } else {
  1363. segs.unshift(elm.localName.toLowerCase() + '[@id="' + elm.getAttribute('id') + '"]');
  1364. }
  1365. } else if (elm.hasAttribute && elm.hasAttribute('class')) {
  1366. segs.unshift(elm.localName.toLowerCase() + '[@class="' + elm.getAttribute('class') + '"]');
  1367. } else {
  1368. let i, sib;
  1369. for (i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling) {
  1370. if (sib.localName === elm.localName) {
  1371. i++;
  1372. }
  1373. }
  1374. segs.unshift(elm.localName.toLowerCase() + '[' + i + ']');
  1375. }
  1376. }
  1377. return segs.length ? '/' + segs.join('/') : null;
  1378. }
  1379.  
  1380. const escapeHTMLPolicy = (_unsafeWindow.trustedTypes && _unsafeWindow.trustedTypes.createPolicy) ? _unsafeWindow.trustedTypes.createPolicy('pagetual_default', {
  1381. createHTML: (string, sink) => string
  1382. }) : null;
  1383.  
  1384. function createHTML(html) {
  1385. return escapeHTMLPolicy ? escapeHTMLPolicy.createHTML(html) : html;
  1386. }
  1387.  
  1388. const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
  1389.  
  1390. async function sleep(time) {
  1391. await new Promise((resolve) => {
  1392. setTimeout(() => {
  1393. resolve();
  1394. }, time);
  1395. });
  1396. }
  1397.  
  1398. class RuleParser {
  1399. constructor() {
  1400. this.hpRules = [];
  1401. this.smartRules = [];
  1402. this.customRules = [];
  1403. this.rules = [];
  1404. this.pageDoc = document;
  1405. this.nextLinkHref = null;
  1406. this.nextTitle = "";
  1407. this.oldUrl = "";
  1408. this.curUrl = location.href;
  1409. this.curSiteRule = {};
  1410. }
  1411.  
  1412. async initSavedRules(callback) {
  1413. var self = this;
  1414. let smartRules = await getData("smartRules");
  1415. if (smartRules) self.smartRules = smartRules;
  1416. let hpRules = await getData("hpRules");
  1417. if (hpRules) self.hpRules = hpRules;
  1418. let customRules = await getData("customRules");
  1419. if (customRules) self.customRules = customRules;
  1420. if (_unsafeWindow.pagetualRules && _unsafeWindow.pagetualRules.length) {
  1421. _unsafeWindow.pagetualRules.forEach(rule => {
  1422. rule.isScript = true;
  1423. });
  1424. self.customRules = _unsafeWindow.pagetualRules.concat(self.customRules);
  1425. }
  1426. let rules = await getData("rules");
  1427. if (rules) self.rules = rules;
  1428. callback();
  1429. }
  1430.  
  1431. saveCurSiteRule() {
  1432. /*if(!this.curSiteRule || !this.curSiteRule.url || this.curSiteRule.smart || this.curSiteRule.url.length<13)return;
  1433. this.hpRules=this.hpRules.filter(item=>{return item&&item.url!=this.curSiteRule.url});
  1434. this.hpRules.unshift(this.curSiteRule);
  1435. if(this.hpRules.length>30){
  1436. this.hpRules.pop();
  1437. }
  1438. storage.setItem("hpRules", this.hpRules);*/
  1439. }
  1440.  
  1441. requestJSON(url, callback) {
  1442. _GM_xmlhttpRequest({
  1443. url: url,
  1444. method: 'GET',
  1445. timeout: 1000000,
  1446. headers: {
  1447. 'accept': 'application/json,text/html',
  1448. 'Referer': url,
  1449. },
  1450. onload: function(res) {
  1451. let json = null;
  1452. try {
  1453. json = JSON.parse(res.response || res.responseText);
  1454. } catch(e) {
  1455. debug(e, 'Error json');
  1456. }
  1457. callback(json);
  1458. },
  1459. onerror: function(e) {
  1460. callback(null, e);
  1461. },
  1462. ontimeout: function(e) {
  1463. callback(null, e);
  1464. }
  1465. });
  1466. }
  1467.  
  1468. formatRule(item, from) {
  1469. if (item.data && item.data.url) {
  1470. let result = {
  1471. name: item.name,
  1472. from: from,
  1473. action: item.data.forceIframe === "true" ? 1 : undefined,
  1474. url: item.data.url,
  1475. pageElement: item.data.pageElement,
  1476. nextLink: item.data.nextLink,
  1477. insert: item.data.insertBefore||undefined,
  1478. updatedAt: item.updated_at
  1479. };
  1480. let _css = (item.data.Stylus || '') + (item.data.CSS || '');
  1481. if (_css) result.css = _css;
  1482. if (item.data.bookmarklet) result.pageAction = item.data.bookmarklet;
  1483. return result;
  1484. } else {
  1485. item.from = from;
  1486. return item;
  1487. }
  1488. return null;
  1489. }
  1490.  
  1491. addRuleByUrl(url, from, callback) {
  1492. if (url.indexOf("?") === -1) {
  1493. url = url + "?" + Date.now();
  1494. } else {
  1495. url = url + "&" + Date.now();
  1496. }
  1497. this.requestJSON(url, (json,err) => {
  1498. if (!json) {
  1499. debug(err, "Failed to update " + url + " rules!");
  1500. }
  1501. this.addRules(json, from);
  1502. callback(json, err);
  1503. });
  1504. }
  1505.  
  1506. addRules(rules, from) {
  1507. if (rules && rules.length > 0) {
  1508. let first = -1;
  1509. this.rules = this.rules.filter((item, i) => {
  1510. if (item.from === from) {
  1511. if (first === -1) first = i;
  1512. return false;
  1513. } else return true;
  1514. });
  1515. if (first === -1) first = 0;
  1516. rules.forEach(item => {
  1517. let rule = this.formatRule(item, from);
  1518. if (rule) {
  1519. this.rules.splice(first, 0, rule)
  1520. }
  1521. });
  1522. }
  1523. }
  1524.  
  1525. ruleMatchPre(r) {
  1526. if (r.include) {
  1527. let include;
  1528. if (Array && Array.isArray && Array.isArray(r.include)) {
  1529. include = r.include.every((sel, i) => {
  1530. let ele = getElement(sel, document);
  1531. return !!ele;
  1532. });
  1533. } else include = getElement(r.include, document);
  1534. if (!include) return false;
  1535. }
  1536. if (r.exclude) {
  1537. let exclude;
  1538. if (Array && Array.isArray && Array.isArray(r.exclude)) {
  1539. exclude = !r.exclude.every((sel, i) => {
  1540. let ele = getElement(sel, document);
  1541. return !ele;
  1542. });
  1543. } else exclude = getElement(r.exclude, document);
  1544. if (exclude) return false;
  1545. }
  1546. return true;
  1547. }
  1548.  
  1549. ruleMatchReady(r) {
  1550. let findIndex = 0;
  1551. if (r.nextLink && r.nextLink !== 0) {
  1552. let nextLinkSel = r.nextLink, nextLink;
  1553. if (Array && Array.isArray && Array.isArray(nextLinkSel)) {
  1554. nextLink = !nextLinkSel.every((sel, i) => {
  1555. let ele = getElement(sel, document);
  1556. if (ele) findIndex = i;
  1557. return !ele;
  1558. });
  1559. } else nextLink = getElement(nextLinkSel, document);
  1560. if (!nextLink) return false;
  1561. }
  1562. if (r.pageElement) {
  1563. let pageElementSel = r.pageElement, pageElement;
  1564. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  1565. pageElementSel = pageElementSel[findIndex];
  1566. }
  1567. pageElement = getElement(pageElementSel, document);
  1568. if (!pageElement) return false;
  1569. }
  1570. if (r.insert) {
  1571. let insertSel = r.insert, insert;
  1572. if (Array && Array.isArray && Array.isArray(insertSel)) {
  1573. insertSel = insertSel[findIndex];
  1574. }
  1575. insert = getElement(insertSel, document);
  1576. if (!insert) return false;
  1577. }
  1578. //if (findIndex !== 0) nextIndex = findIndex;
  1579. return true;
  1580. }
  1581.  
  1582. ruleMatch(r) {
  1583. return this.ruleMatchPre(r) && this.ruleMatchReady(r);
  1584. }
  1585.  
  1586. scrollToShow(sel, doc) {
  1587. let exclude = getElement(sel, doc);
  1588. if (exclude) {
  1589. var actualTop = exclude.offsetTop;
  1590. var current = exclude.offsetParent;
  1591. while (current !== null) {
  1592. actualTop += current.offsetTop;
  1593. current = current.offsetParent;
  1594. }
  1595. getBody(doc).scrollTop = 0;
  1596. doc.documentElement.scrollTop = 0;
  1597. let maxHeight = Math.max(getBody(doc).scrollHeight, doc.documentElement.scrollHeight);
  1598. getBody(doc).scrollTop = actualTop - 10;
  1599. doc.documentElement.scrollTop = actualTop - 10;
  1600. setTimeout(() => {
  1601. while (actualTop < maxHeight) {
  1602. actualTop += 200;
  1603. getBody(doc).scrollTop = actualTop;
  1604. doc.documentElement.scrollTop = actualTop;
  1605. }
  1606. }, 0);
  1607. return false;
  1608. }
  1609. return true;
  1610. }
  1611.  
  1612. waitElement(doc, selArr) {
  1613. if (!selArr) selArr = this.curSiteRule.waitElement;
  1614. if (!Array.isArray(selArr)) {
  1615. selArr = [selArr];
  1616. }
  1617. let includeSel = selArr[0].trim(), excludeSel;
  1618. if (selArr.length === 2) {
  1619. excludeSel = selArr[1].trim().replace(/^!/, '');
  1620. } else if (includeSel.indexOf('!') === 0) {
  1621. excludeSel = includeSel.replace(/^!/, '');
  1622. includeSel = '';
  1623. }
  1624. if (includeSel) {
  1625. let include = getElement(includeSel, doc);
  1626. if (!include) {
  1627. if (doc !== document) {
  1628. getBody(doc).scrollTop = 9999999;
  1629. doc.documentElement.scrollTop = 9999999;
  1630. }
  1631. return false;
  1632. }
  1633. }
  1634. if (doc === document) return true;
  1635. if (excludeSel) {
  1636. if (!this.scrollToShow(excludeSel, doc)) {
  1637. if (!loadingDiv.offsetParent && this.insert.parentNode) {
  1638. this.insertElement(loadingDiv);
  1639. }
  1640. return false;
  1641. }
  1642. }
  1643. return true;
  1644. }
  1645.  
  1646. runPageBar(pageBar) {
  1647. if (this.curSiteRule.pageBar && this.curSiteRule.pageBar !== 0) {
  1648. try {
  1649. ((typeof this.curSiteRule.pageBar === 'function') ? this.curSiteRule.pageBar : Function("pageBar",'"use strict";' + this.curSiteRule.pageBar))(pageBar);
  1650. } catch(e) {
  1651. debug(e);
  1652. }
  1653. }
  1654. }
  1655.  
  1656. runWait(cb) {
  1657. let checkEval = null, waitTime = 0;
  1658. if (this.curSiteRule.waitElement) {
  1659. checkEval = async doc => {
  1660. return await this.waitElement(doc);
  1661. };
  1662. } else if(this.curSiteRule.wait) {
  1663. if (isNaN(this.curSiteRule.wait)) {
  1664. try {
  1665. checkEval = (typeof this.curSiteRule.wait === 'function') ? this.curSiteRule.wait : new AsyncFunction("doc", '"use strict";' + this.curSiteRule.wait);
  1666. } catch(e) {
  1667. debug(e);
  1668. }
  1669. } else {
  1670. waitTime = this.curSiteRule.wait;
  1671. }
  1672. }
  1673. cb(checkEval, waitTime);
  1674. }
  1675.  
  1676. findNoNext() {
  1677. if (!this.curSiteRule || !this.curSiteRule.smart || this.curSiteRule.nextLink === 0 || this.possibleRule) return;
  1678. let self = this;
  1679. self.curSiteRule.nextLink = 0;
  1680. self.smartRules = self.smartRules.filter(item => {return item && item.url !== self.curSiteRule.url;});
  1681. self.smartRules.unshift(self.curSiteRule);
  1682. storage.setItem("smartRules", self.smartRules);
  1683. }
  1684.  
  1685. async getRule(callback) {
  1686. var href = location.href.slice(0, 500);
  1687. if(noRuleTest) {
  1688. this.curSiteRule = {};
  1689. this.curSiteRule.url = href;
  1690. this.curSiteRule.smart = true;
  1691. callback();
  1692. return;
  1693. }
  1694. if (_unsafeWindow.pagetualRule) {
  1695. this.curSiteRule = _unsafeWindow.pagetualRule;
  1696. if (!this.curSiteRule.url) this.curSiteRule.url = ".";
  1697. this.curSiteRule.isScript = true;
  1698. }
  1699. if (this.curSiteRule && this.curSiteRule.url && !this.curSiteRule.smart) {
  1700. let urlReg = new RegExp(this.curSiteRule.url, "i");
  1701. if (urlReg.test(href) && this.ruleMatch(this.curSiteRule)) {
  1702. return callback();
  1703. }
  1704. }
  1705. if (this.possibleRule) {
  1706. let urlReg = new RegExp(this.possibleRule.url, "i");
  1707. if (urlReg.test(href) && this.ruleMatch(this.possibleRule)) {
  1708. this.curSiteRule = this.possibleRule;
  1709. debug(this.curSiteRule, 'Match');
  1710. return callback();
  1711. }
  1712. }
  1713. this.curSiteRule = {};
  1714. var self = this;
  1715.  
  1716. function setRule(r) {
  1717. if (self.preSiteRule) {
  1718. href = location.href.slice(0, 500);
  1719. let urlReg = new RegExp(self.preSiteRule.url, "i");
  1720. if (urlReg.test(href) && self.ruleMatch(self.preSiteRule)) {
  1721. self.curSiteRule = self.preSiteRule;
  1722. return callback();
  1723. }
  1724. }
  1725. if (r.from === 2) {
  1726. delete r.autoLoadNum;
  1727. delete r.history;
  1728. delete r.sideController;
  1729. if (r.pageBar === 0) delete r.pageBar;
  1730. }
  1731. if (!r.smart) {
  1732. self.insert = null;
  1733. self.curSiteRule = r;
  1734. self.preSiteRule = r;
  1735. if (r.enable !== 0) debug(r, 'Match');
  1736. } else if (!self.curSiteRule || !self.curSiteRule.smart) self.curSiteRule = r;
  1737. callback();
  1738. }
  1739.  
  1740. function checkRule(r) {
  1741. if (r.from === 1 && r.url.length <= 13) return false;
  1742. let urlReg = new RegExp(r.url, "i");
  1743. if (urlReg.test(href)) {
  1744. if (!self.ruleMatchPre(r)) return false;
  1745. if (r.url.length > 15 && r.from !== 1) {
  1746. self.possibleRule = r;
  1747. }
  1748. if (r.waitElement) {
  1749. let waitTime = 500;
  1750. let checkReady = () => {
  1751. setTimeout(() => {
  1752. if (!self.waitElement(document, r.waitElement) || !self.ruleMatchReady(r)) {
  1753. checkReady();
  1754. } else {
  1755. setRule(r);
  1756. }
  1757. }, parseInt(waitTime));
  1758. };
  1759. checkReady();
  1760. debug(r, 'Wait for');
  1761. return true;
  1762. } else if (r.wait) {
  1763. let waitTime = 500, checkEval, maxCheckTimes = 50;
  1764. if (isNaN(r.wait)) {
  1765. try {
  1766. checkEval = (typeof r.wait === 'function') ? r.wait : AsyncFunction("doc",'"use strict";' + r.wait);
  1767. } catch(e) {
  1768. debug(e, 'Error when checkeval');
  1769. }
  1770. } else {
  1771. waitTime = r.wait;
  1772. }
  1773. let checkReady = () => {
  1774. if (maxCheckTimes-- <= 0) {
  1775. debug("Wait for rule ready but failed");
  1776. setRule(r);
  1777. return;
  1778. }
  1779. setTimeout(async() => {
  1780. if (!self.ruleMatchReady(r) || (checkEval && !await checkEval(document))) {
  1781. checkReady();
  1782. } else {
  1783. setRule(r);
  1784. }
  1785. }, parseInt(waitTime));
  1786. };
  1787. checkReady();
  1788. debug(r, 'Wait for');
  1789. return true;
  1790. }
  1791. if (r.pinUrl) {
  1792. setRule(r);
  1793. return true;
  1794. }
  1795. if (!self.ruleMatchReady(r)) {
  1796. return false;
  1797. }
  1798. setRule(r);
  1799. return true;
  1800. }
  1801. return false;
  1802. }
  1803.  
  1804. function checkHpRules() {
  1805. for (let i in self.hpRules) {
  1806. let rule = self.hpRules[i];
  1807. if (!rule || !rule.url || rule.smart) continue;
  1808. if (checkRule(rule)) return true;
  1809. }
  1810. return false;
  1811. }
  1812.  
  1813. function checkCustomRules() {
  1814. for (let i in self.customRules) {
  1815. let rule = self.customRules[i];
  1816. if (!rule || !rule.url) continue;
  1817. if (checkRule(rule)) return true;
  1818. }
  1819. return false;
  1820. }
  1821.  
  1822. if (rulesData.customFirst) {
  1823. if (checkCustomRules()) return;
  1824. await sleep(1);
  1825. if (checkHpRules()) return;
  1826. } else {
  1827. if (checkHpRules()) return;
  1828. await sleep(1);
  1829. if (checkCustomRules()) return;
  1830. }
  1831. await sleep(1);
  1832.  
  1833. for (let i in this.smartRules) {
  1834. let rule = this.smartRules[i];
  1835. if (!rule || !rule.url || !rule.smart) continue;
  1836. if (href == rule.url) {
  1837. setRule(rule);
  1838. return;
  1839. }
  1840. }
  1841. let r = 0;
  1842. async function searchByTime() {
  1843. while (document.hidden) {
  1844. await sleep(1000);
  1845. }
  1846. setTimeout(() => {
  1847. let end = r + 20;
  1848. end = end > self.rules.length ? self.rules.length : end;
  1849. for (; r < end; r++) {
  1850. let rule = self.rules[r];
  1851. if (checkRule(rule)) return;
  1852. }
  1853. if (end >= self.rules.length) {
  1854. setRule({url: href, smart: true});
  1855. return;
  1856. } else {
  1857. searchByTime();
  1858. }
  1859. }, 1);
  1860. }
  1861. searchByTime();
  1862. }
  1863.  
  1864. addToHpRules(instead) {
  1865. try {
  1866. if (this.curSiteRule.isScript) return;
  1867. if (!this.hpRules) this.hpRules = [];
  1868. let url = this.curSiteRule && this.curSiteRule.url, self = this;
  1869. let href = location.href.slice(0, 500);
  1870. let matchedRules = this.hpRules.filter(rule => rule != self.curSiteRule && new RegExp(rule.url, "i").test(href) && self.ruleMatch(rule));
  1871. if (url) matchedRules.unshift(this.curSiteRule);
  1872. matchedRules.sort((a, b) => {
  1873. if ((a.include || a.exclude) && (!b.include && !b.exclude)) {
  1874. return -1;
  1875. } else if ((b.include || b.exclude) && (!a.include && !a.exclude)) {
  1876. return 1;
  1877. } else {
  1878. if ((a.nextLink || a.pageElement) && (!b.nextLink && !b.pageElement)) {
  1879. return -1;
  1880. } else if ((b.nextLink || b.pageElement) && (!a.nextLink && !a.pageElement)) {
  1881. return 1;
  1882. } else {
  1883. if (a.url.length > b.url.length) {
  1884. return -1;
  1885. } else if (a.url.length < b.url.length) {
  1886. return 1;
  1887. } else {
  1888. return 0;
  1889. }
  1890. }
  1891. }
  1892. });
  1893. this.hpRules = this.hpRules.filter(item => {
  1894. return item && !matchedRules.find(rule => item.url == rule.url && JSON.stringify(item) == JSON.stringify(rule));
  1895. });
  1896. if (instead) {
  1897. if (url) {
  1898. this.hpRules.unshift(this.curSiteRule);
  1899. matchedRules = [];
  1900. }
  1901. } else {
  1902. this.hpRules = matchedRules.concat(this.hpRules);
  1903. }
  1904. if (matchedRules && matchedRules.length) this.curSiteRule = matchedRules[0];
  1905. if (this.hpRules.length > 30) {
  1906. this.hpRules.pop();
  1907. }
  1908. if (!rulesData.sort) rulesData.sort = [1];
  1909. this.hpRules.sort((a, b) => {
  1910. let aSort = -1, bSort = -1;
  1911. for (let s = 0; s < rulesData.sort.length; s++) {
  1912. if (a.from == rulesData.sort[s]) aSort = s;
  1913. if (b.from == rulesData.sort[s]) bSort = s;
  1914. if (aSort > -1 && bSort > -1) break;
  1915. }
  1916. return aSort - bSort;
  1917. });
  1918. storage.setItem("hpRules", this.hpRules);
  1919. } catch (e) {
  1920. debug(e);
  1921. }
  1922. }
  1923.  
  1924. replaceElement(doc) {
  1925. if (!doc || doc === document) return;
  1926. let replaceElementSel = this.curSiteRule.replaceElement;
  1927. if (replaceElementSel) {
  1928. if (!Array.isArray(replaceElementSel)) {
  1929. replaceElementSel = [replaceElementSel];
  1930. }
  1931. replaceElementSel.forEach(sel => {
  1932. let pageEles = getAllElements(sel, document);
  1933. let replaceEles = getAllElements(sel, doc);
  1934. for (let i = 0; i < pageEles.length; i++) {
  1935. let replaceEle = replaceEles[i];
  1936. let pageEle = pageEles[i];
  1937. if (replaceEle) {
  1938. pageEle.parentNode.replaceChild(replaceEle.cloneNode(true), pageEle);
  1939. } else break;
  1940. }
  1941. });
  1942. }
  1943. }
  1944.  
  1945. refreshByClick() {
  1946. let refreshByClickSel = this.curSiteRule.refreshByClick;
  1947. if (refreshByClickSel) {
  1948. let self = this;
  1949. if (!this.refreshByClickHandler) {
  1950. this.refreshByClickHandler = e => {
  1951. if (!self.refreshing) {
  1952. self.refreshing = true;
  1953. setTimeout(() => {
  1954. self.refreshing = false;
  1955. let checkEles = getAllElements(refreshByClickSel, document);
  1956. for (let i = 0; i < checkEles.length; i++) {
  1957. let curEle = checkEles[i];
  1958. if (curEle === e.target || curEle.contains(e.target)) {
  1959. ruleParser.urlChanged();
  1960. isPause = true;
  1961. if (!ruleParser.nextLinkHref) isLoading = false;
  1962. break;
  1963. }
  1964. }
  1965. }, 300);
  1966. }
  1967. }
  1968. }
  1969. document.removeEventListener("click", this.refreshByClickHandler);
  1970. document.addEventListener("click", this.refreshByClickHandler);
  1971. }
  1972. }
  1973.  
  1974. getValidSize(ele, win) {
  1975. if (!win) return {h: 0, w: 0};
  1976. let eleStyle = win.getComputedStyle(ele);
  1977. if (!ele.offsetParent && (eleStyle.position !== "fixed" || eleStyle.opacity === 0)) {
  1978. return {h: 0, w: 0};
  1979. }
  1980. if (ele.children && ele.children.length === 1 && (ele.offsetWidth === 0 || ele.offsetHeight === 0)) {
  1981. ele = ele.children[0];
  1982. }
  1983. let h = ele.scrollHeight, w;
  1984. if (eleStyle.overflow === "hidden") {
  1985. h = ele.offsetHeight;
  1986. w = ele.offsetWidth;
  1987. } else w = parseInt(ele.offsetWidth || ele.scrollWidth);
  1988. if (h === 0 && ele.parentNode && ele.parentNode.children.length === 1) {
  1989. h = ele.parentNode.scrollHeight;
  1990. }
  1991. while (h === 0 && ele.children && ele.children.length === 1) {
  1992. ele = ele.children[0];
  1993. h = ele.scrollHeight;
  1994. }
  1995. if (h === 0 && ele.children && ele.children.length) {
  1996. let maxChildSize = {h: 0}, self = this;
  1997. [].forEach.call(ele.children, el => {
  1998. let childSize = self.getValidSize(el, win);
  1999. if (childSize.h > maxChildSize.h) maxChildSize = childSize;
  2000. });
  2001. if (maxChildSize.h !== 0) return maxChildSize;
  2002. }
  2003. const maxNum = 2147483647;
  2004. let moreChild = ele.children[0], minOffsetTop = maxNum;
  2005. while (moreChild) {
  2006. if ((moreChild.offsetParent === ele || moreChild.offsetParent === ele.offsetParent)) {
  2007. let curOffsetTop = moreChild.offsetParent === ele.offsetParent ? moreChild.offsetTop - ele.offsetTop : moreChild.offsetTop;
  2008. if (curOffsetTop < minOffsetTop) {
  2009. minOffsetTop = curOffsetTop;
  2010. }
  2011. }
  2012. moreChild = moreChild.nextElementSibling;
  2013. }
  2014. if (h && minOffsetTop !== maxNum && minOffsetTop > 0) {
  2015. h -= minOffsetTop;
  2016. }
  2017. return {h: h, w: w};
  2018. }
  2019.  
  2020. checkTargetChildren(ele, curWin, articleNum, curHeight) {
  2021. let pf = false;
  2022. if (ele.parentNode) {
  2023. let paStyle = curWin.getComputedStyle(ele.parentNode);
  2024. let paDisplay = paStyle.display;
  2025. let paOverflow = paStyle.overflow;
  2026. pf = (paDisplay.indexOf('flex') !== -1 && paStyle.flexDirection.indexOf("row") === 0 && paStyle.flexWrap !== "wrap") || compareNodeName(ele.parentNode, ["ul"]) || paDisplay.indexOf('grid') !== -1 || paOverflow === "hidden";
  2027. }
  2028. let curStyle = curWin.getComputedStyle(ele);
  2029. if (ele.children.length > 1) {
  2030. if (articleNum > 1) {
  2031. return ">article";
  2032. } else {
  2033. let hasText = false;
  2034. for (let i in ele.childNodes) {
  2035. let child = ele.childNodes[i];
  2036. if (child.nodeType === 3 && child.nodeValue.trim() !== '') {
  2037. hasText = true;
  2038. break;
  2039. }
  2040. }
  2041. let gridArea = curStyle.gridArea;
  2042. if (gridArea && gridArea !== "auto" && gridArea !== "auto / auto / auto / auto") {
  2043. return ">*";
  2044. } else {
  2045. let middleChild = ele.children[parseInt(ele.children.length / 2)];
  2046. if ((curStyle.display === 'flex' && curStyle.flexDirection.indexOf("row") === 0 && curStyle.flexWrap !== "wrap") || (curStyle.float === "none" && curStyle.display !== "table-cell" && (rulesData.opacity !== 0 || hasText) && !pf)) {
  2047. return "";
  2048. } else if ((middleChild.style && middleChild.style.position === "absolute" && middleChild.style.left && middleChild.style.top) || compareNodeName(ele, ["ul"]) || curHeight === 0) {
  2049. return "";
  2050. } else {
  2051. return ">*";
  2052. }
  2053. }
  2054. }
  2055. } else if (pf || curStyle.position === "absolute") {
  2056. return ">*";
  2057. }
  2058. return "";
  2059. }
  2060.  
  2061. getPageElement(doc, curWin, dontFind) {
  2062. if (doc === document && this.docElementValid()) {
  2063. return this.docPageElement;
  2064. }
  2065. let pageElement = null;
  2066. let self = this;
  2067. let body = getBody(doc);
  2068. if (this.curSiteRule.pageElement) {
  2069. let pageElementSel = this.curSiteRule.pageElement;
  2070. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  2071. pageElementSel = pageElementSel[nextIndex < pageElementSel.length ? nextIndex : 0];
  2072. }
  2073. pageElement = getAllElements(pageElementSel, doc);
  2074. if (this.curSiteRule.smart && (!pageElement || pageElement.length === 0)) {
  2075. const childSelMatch = />\s*\*$/;
  2076. const targetChild = childSelMatch.test(pageElementSel);
  2077. if (targetChild) pageElementSel = pageElementSel.replace(childSelMatch, "");
  2078. let pageElementSelSplit = pageElementSel.split(">");
  2079. while(pageElementSelSplit && pageElementSelSplit.length > 5) {
  2080. pageElementSelSplit.shift();
  2081. let tempSel = pageElementSelSplit.join(">");
  2082. pageElement = getAllElements(tempSel, doc);
  2083. if (pageElement && pageElement.length === 1) {
  2084. if (targetChild) {
  2085. pageElement = pageElement.children;
  2086. }
  2087. this.curSiteRule.pageElement = tempSel + (targetChild ? ">*" : "");
  2088. break;
  2089. }
  2090. }
  2091. if (!pageElement || pageElement.length === 0) {
  2092. pageElementSel = pageElementSel.replace(/:nth-of-type\(\d+\)/g, "");
  2093. pageElement = getAllElements(pageElementSel, doc);
  2094. if (pageElement && pageElement.length === 1) {
  2095. if (targetChild) {
  2096. pageElement = pageElement.children;
  2097. }
  2098. this.curSiteRule.pageElement = pageElementSel + (targetChild ? ">*" : "");
  2099. }
  2100. }
  2101. }
  2102. if (this.curSiteRule.smart && pageElement && pageElement.length && curWin && curWin !== _unsafeWindow) {
  2103. if (pageElement.length === 1 && !pageElement[0].src && pageElement[0].innerHTML.trim() === "") {
  2104. pageElement = null;
  2105. } else {
  2106. let parent = pageElement[0].parentNode;
  2107. let loading = parent.querySelector('[class*=loading]');
  2108. if (loading && loading.offsetParent && loading.offsetHeight > parent.offsetHeight>>2) {
  2109. pageElement = null;
  2110. }
  2111. }
  2112. }
  2113. }
  2114. if (pageElement && pageElement.length === 1 && pageElement[0].style.display === 'none') {
  2115. pageElement = [body];
  2116. }
  2117. if (this.curSiteRule.smart && pageElement && pageElement.length > 0 && compareNodeName(pageElement[0], ["tr"])) {
  2118. let mainTr = this.insert.parentNode.querySelectorAll('tr'), mainTdNum = 0, newTdNum = 0;
  2119. mainTr = mainTr[mainTr.length - 1];
  2120. [].forEach.call(mainTr.children, el => {
  2121. if (compareNodeName(el, ["td", "th"])) {
  2122. mainTdNum += el.colSpan || 1;
  2123. }
  2124. });
  2125. [].forEach.call(pageElement[0].children, el => {
  2126. if (compareNodeName(el, ["td", "th"])) {
  2127. newTdNum += el.colSpan || 1;
  2128. }
  2129. });
  2130. if (mainTdNum !== newTdNum) {
  2131. this.curSiteRule.pageElement = this.curSiteRule.pageElement.replace(/> *table.*/, ">table");
  2132. this.getInsert(true);
  2133. return this.getPageElement(doc, curWin, dontFind);
  2134. }
  2135. }
  2136. if ((this.curSiteRule.smart || !this.curSiteRule.pageElement) && (!pageElement || pageElement.length == 0) && curWin && !dontFind) {
  2137. if (!body) return null;
  2138. let bodyHeight = parseInt(body.offsetHeight || body.scrollHeight);
  2139. let curHeight = bodyHeight, curWidth = 0;
  2140. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  2141. let windowWidth = window.innerWidth || document.documentElement.clientWidth;
  2142. let needCheckNext = (doc == document && this.initNext), nextLeftPos = 0;
  2143. if (needCheckNext && this.initNext.getBoundingClientRect) {
  2144. nextLeftPos = this.initNext.getBoundingClientRect().left;
  2145. }
  2146. function checkElement(ele) {
  2147. if (compareNodeName(ele, ["pre", "code"])) {
  2148. self.curSiteRule.pageElement = geneSelector(ele.parentNode);
  2149. debug(self.curSiteRule.pageElement, 'Page element');
  2150. return [ele.parentNode];
  2151. }
  2152. if (ele.children && ele.children.length === 1) {
  2153. let hasText = false;
  2154. for (let i in ele.childNodes) {
  2155. let child = ele.childNodes[i];
  2156. if (child.nodeType === 3 && child.nodeValue.trim() !== '') {
  2157. hasText = true;
  2158. break;
  2159. }
  2160. }
  2161. if (!hasText) {
  2162. ele = ele.children[0];
  2163. let validSize = self.getValidSize(ele, curWin);
  2164. curHeight = validSize.h;
  2165. curWidth = validSize.w;
  2166. }
  2167. }
  2168. if (compareNodeName(ele, ["picture"]) || !ele.innerText || ele.innerText.trim() === '') {
  2169. self.curSiteRule.pageElement = geneSelector(ele.parentNode) + ">" + ele.nodeName.toLowerCase();
  2170. debug(self.curSiteRule.pageElement, 'Page element');
  2171. let eles = [];
  2172. for (let i = 0; i < ele.parentNode.children.length; i++) {
  2173. let curNode = ele.parentNode.children[i];
  2174. if (curNode.nodeName === ele.nodeName && curNode.id === ele.id && curNode.className === ele.className) {
  2175. eles.push(curNode);
  2176. }
  2177. }
  2178. return eles;
  2179. }
  2180. if (compareNodeName(ele, ["form"]) && ele.parentNode !== getBody(document)) {
  2181. self.curSiteRule.pageElement = geneSelector(ele) + ">*";
  2182. debug(self.curSiteRule.pageElement, 'Page element');
  2183. return ele.children;
  2184. }
  2185. if (ele.children.length === 0 && !self.curSiteRule.pageElement) {
  2186. if (compareNodeName(ele.parentNode, ["p"])) ele = ele.parentNode;
  2187. self.curSiteRule.pageElement = geneSelector(ele.parentNode) + ">" + ele.nodeName.toLowerCase();
  2188. debug(self.curSiteRule.pageElement, 'Page element');
  2189. return getAllElements(self.curSiteRule.pageElement, doc);
  2190. }
  2191. let i, minHeight = curHeight * 0.52, curMaxEle = null, curMaxArea = 0, minWidth = Math.min(curWidth * 0.38, 500);
  2192. let isHori, preOffsetTop = -1;
  2193. let articleNum = 0;
  2194. for (i = 0; i < ele.children.length; i++) {
  2195. let curNode = ele.children[i];
  2196. if (ele !== body && /^H\d$/i.test(curNode.nodeName) && curNode.offsetParent) {
  2197. curMaxEle = null;
  2198. break;
  2199. }
  2200. if (compareNodeName(curNode, ["canvas", "nav"])) continue;
  2201. let curStyle = curWin.getComputedStyle(curNode);
  2202. if (!curNode.offsetParent && (curStyle.position !== "fixed" || curStyle.opacity === 0)) {
  2203. continue;
  2204. }
  2205. if (!compareNodeName(curNode, ["img"]) && curNode.querySelector('img') === null && /^\s*$/.test(curNode.innerText)) continue;
  2206. if (needCheckNext && !curNode.contains(self.initNext) && getElementTop(curNode) > windowHeight) {
  2207. continue;
  2208. }
  2209. if (compareNodeName(curNode, ["article"])) articleNum++;
  2210. let validSize = self.getValidSize(curNode, curWin);
  2211. let h = validSize.h;
  2212. let w = validSize.w;
  2213. if (isNaN(h) || isNaN(w) || !h || !w) continue;
  2214. isHori = Math.abs(preOffsetTop - curNode.offsetTop) <= 20 ? true : (preOffsetTop === -1 && curNode.nextElementSibling && curNode.nextElementSibling.offsetTop === curNode.offsetTop);
  2215. if (isHori && h <= 50) continue;
  2216. /*if (isHori && nextLeftPos && curMaxEle && curWidth > 500 && curHeight > 500) {
  2217. let curRect = curNode.getBoundingClientRect();
  2218. if (curRect.left > windowWidth>>2 && curRect.left <= nextLeftPos && curRect.right > nextLeftPos) {
  2219. continue;
  2220. }
  2221. }*/
  2222. let a = h * w, moreChild = curNode.children[0];
  2223. while (moreChild) {
  2224. let validSize = self.getValidSize(moreChild, curWin);
  2225. let ch = validSize.h;
  2226. let cw = validSize.w;
  2227. if (h < ch) {
  2228. h = ch;
  2229. }
  2230. if (moreChild.innerText !== "" && ch && cw) {
  2231. a += ch * cw;
  2232. }
  2233. moreChild = moreChild.nextElementSibling;
  2234. }
  2235. let isMax = false;
  2236. if (isHori) {
  2237. if (curMaxEle) {
  2238. if (w > curWidth && (windowWidth>>1) > curWidth) {
  2239. isMax = true;
  2240. } else if (w + 300 > curWidth && a > curMaxArea) {
  2241. isMax = true;
  2242. }
  2243. }
  2244. } else {
  2245. if (curMaxEle && curMaxEle.offsetParent === curNode.offsetParent && curMaxEle.offsetTop === curNode.offsetTop) {
  2246. if (curMaxArea * 2 > a) continue;
  2247. }
  2248. isMax = curMaxArea < a;
  2249. }
  2250. if (curMaxEle === null || isMax) {
  2251. if (isHori) {
  2252. if (w < minWidth) {
  2253. continue;
  2254. }
  2255. }
  2256. if (h < minHeight) {
  2257. if (!needCheckNext || h < (windowHeight>>1)) {
  2258. continue;
  2259. }
  2260. if (!ele.contains(self.initNext)) {
  2261. continue;
  2262. } else if (!curNode.contains(self.initNext) && h < curHeight >> 1) {
  2263. continue;
  2264. }
  2265. }
  2266. curHeight = h;
  2267. curMaxArea = a;
  2268. curWidth = w;
  2269. curMaxEle = curNode;
  2270. preOffsetTop = curNode.offsetTop;
  2271. }
  2272. }
  2273. let curHeightPercent = curHeight / bodyHeight;
  2274. if (curMaxEle && curHeightPercent <= 0.18) {
  2275. let article;
  2276. for (let i = 0; i < mainSel.length; i++) {
  2277. article = doc.querySelectorAll(mainSel[i]);
  2278. if (article && article.length === 1) break;
  2279. }
  2280. if (article && article.length === 1) {
  2281. article = article[0];
  2282. let childrenEnd = self.checkTargetChildren(article, curWin, articleNum, curHeight);
  2283. self.curSiteRule.pageElement = article.nodeName.toLowerCase() + (article.id ? "#" + article.id : "") + (article.className ? "." + article.className.replace(/ /g, ".") : "") + childrenEnd;
  2284. debug(self.curSiteRule.pageElement, 'Page element');
  2285. return childrenEnd ? article.children : [article];
  2286. }
  2287. curMaxEle = null;
  2288. }
  2289. if (curMaxEle && (!compareNodeName(curMaxEle, ["ul"]) || curHeightPercent > 0.8)) {
  2290. let sameClassNum = 0, hasDifferent = false;
  2291. if (curMaxEle.className) {
  2292. for(i = 0; i < ele.children.length; i++) {
  2293. let curNode = ele.children[i];
  2294. if (curMaxEle !== curNode && curNode.style.display !== 'none' && curMaxEle.className === curNode.className && curMaxEle.nodeName === curNode.nodeName){
  2295. sameClassNum++;
  2296. } else if (curMaxEle.className !== curNode.className) {
  2297. hasDifferent = true;
  2298. }
  2299. }
  2300. }
  2301. if (sameClassNum < 2 || (sameClassNum < 5 && hasDifferent)) {
  2302. return checkElement(curMaxEle);
  2303. }
  2304. }
  2305. if (ele.nodeName === "APP-ROOT") {
  2306. isPause = true;
  2307. debug(ele, "Angular root");
  2308. return null;
  2309. }
  2310. while (compareNodeName(ele, ["p", "br", "td"])) {
  2311. ele = ele.parentNode;
  2312. }
  2313. if (compareNodeName(ele, ["tbody"])) {
  2314. self.curSiteRule.pageElement = geneSelector(ele) + ">*";
  2315. if (ele.children.length > 0 && ele.children[0].querySelector("th")) {
  2316. self.curSiteRule.pageElement += ":not(:first-child)";
  2317. }
  2318. debug(self.curSiteRule.pageElement, 'Page element');
  2319. return ele.children;
  2320. }
  2321. let imgs = ele.querySelectorAll('img');
  2322. if (imgs.length === 1) {
  2323. let img = imgs[0];
  2324. if (img.offsetWidth > ele.offsetWidth / 3 * 2 && img.offsetHeight > ele.offsetHeight / 2) {
  2325. ele = img;
  2326. }
  2327. }
  2328. let childrenEnd = self.checkTargetChildren(ele, curWin, articleNum, curHeight);
  2329. if (childrenEnd) {
  2330. self.curSiteRule.pageElement = geneSelector(ele) + childrenEnd;
  2331. ele = ele.children;
  2332. } else {
  2333. if (ele.scrollHeight === 0 && ele.parentNode.children.length === 1) {
  2334. ele = ele.parentNode;
  2335. }
  2336. self.curSiteRule.pageElement = geneSelector(ele);
  2337. ele = [ele];
  2338. }
  2339. debug(self.curSiteRule.pageElement, 'Page element');
  2340. return ele;
  2341. }
  2342. pageElement = checkElement(body);
  2343. if (doc === document && pageElement && pageElement.length > 0 && self.initNext) {
  2344. let posEle = pageElement[pageElement.length - 1];
  2345. while (posEle && !posEle.offsetParent) {
  2346. posEle = posEle.previousElementSibling || posEle.parentNode;
  2347. }
  2348. if (posEle && posEle.scrollHeight === 0 && posEle.lastElementChild) posEle = posEle.lastElementChild;
  2349. let lastBottom = forceState !== 2 && forceState !== 3 && posEle && getElementBottom(posEle);
  2350. if (lastBottom && getElementTop(self.initNext) - lastBottom > 1000) {
  2351. debug("Stop as too long between next & page element, try to enable Force-Join mode.");
  2352. isPause = true;
  2353. pageElement = [];
  2354. sideController.remove();
  2355. } else {
  2356. if (pageElement.length === 1 && compareNodeName(pageElement[0], ["img"])) {
  2357. self.curSiteRule.pageBar = 0;
  2358. }
  2359. }
  2360. }
  2361. //if(pageElement)this.saveCurSiteRule();
  2362. }
  2363.  
  2364. if (doc !== document) {
  2365. this.setPageElementCss(pageElement);
  2366. this.lazyImgAction(pageElement, doc);
  2367. this.filterEles(doc, pageElement);
  2368. } else if (!this.docPageElement) {
  2369. this.setPageElementCss(pageElement, true);
  2370. this.docPageElement = pageElement;
  2371. this.filterEles(doc, pageElement);
  2372. if (this.nextLinkHref) {
  2373. this.openInNewTab(pageElement);
  2374. }
  2375. }
  2376. return pageElement;
  2377. }
  2378.  
  2379. showAddedElements() {
  2380. if (!this.addedElementsIsHide) return;
  2381. if (this.addedElePool && this.addedElePool.length) {
  2382. this.addedElePool.forEach(ele => {
  2383. ele.classList && ele.classList.remove("pagetual-hide");
  2384. });
  2385. }
  2386. this.addedElementsIsHide = false;
  2387. }
  2388.  
  2389. hideAddedElements() {
  2390. if (this.addedElePool && this.addedElePool.length) {
  2391. this.addedElePool.forEach(ele => {
  2392. ele.classList && ele.classList.add("pagetual-hide");
  2393. });
  2394. }
  2395. this.addedElementsIsHide = true;
  2396. }
  2397.  
  2398. toggleAddedElements() {
  2399. if (this.addedElementsIsHide) {
  2400. this.showAddedElements();
  2401. } else {
  2402. this.hideAddedElements();
  2403. }
  2404. }
  2405.  
  2406. changeVisibility() {
  2407. let contentVisibility = this.curSiteRule.contentVisibility || rulesData.contentVisibility;
  2408. if (!contentVisibility) return;
  2409. if (!this.changingVisibility) {
  2410. clearTimeout(this.changeVisibilityTimer);
  2411. this.changeVisibilityTimer = setTimeout(() => {
  2412. this.changingVisibility = true;
  2413. this.changeVisibility();
  2414. }, 300);
  2415. return;
  2416. }
  2417. this.changingVisibility = false;
  2418. if (!this.visibilityItems || !this.visibilityItems.length || this.visibleIndex < 0) return;
  2419. let tempIndex = this.visibleIndex, findVisible = false, lastVisible = 0;
  2420. let viewPortHeight = window.innerHeight || document.documentElement.clientHeight || getBody(document).clientHeight;
  2421. let checkItem = this.visibilityItems[tempIndex];
  2422. while(checkItem) {
  2423. if (checkItem.offsetParent) {
  2424. if (!checkItem.style.containIntrinsicSize) return;
  2425. let clientRect = checkItem.getBoundingClientRect();
  2426. let top = clientRect && clientRect.top;
  2427. let bottom = clientRect && clientRect.bottom;
  2428. if (bottom > 0 && top < viewPortHeight) {
  2429. if (!findVisible) {
  2430. findVisible = true;
  2431. lastVisible = tempIndex;
  2432. }
  2433. checkItem.style.contentVisibility = "visible";
  2434. } else {
  2435. if (top < viewPortHeight && checkItem.style.contentVisibility === "auto") {
  2436. break;
  2437. } else checkItem.style.contentVisibility = "auto";
  2438. }
  2439. }
  2440. if (tempIndex === 0) break;
  2441. tempIndex--;
  2442. checkItem = this.visibilityItems[tempIndex];
  2443. }
  2444. tempIndex = this.visibleIndex + 1;
  2445. if (findVisible) {
  2446. this.visibleIndex = lastVisible;
  2447. }
  2448. checkItem = this.visibilityItems[tempIndex];
  2449. while(checkItem) {
  2450. if (checkItem.offsetParent) {
  2451. if (!checkItem.style.containIntrinsicSize) return;
  2452. let clientRect = checkItem.getBoundingClientRect();
  2453. let top = clientRect && clientRect.top;
  2454. let bottom = clientRect && clientRect.bottom;
  2455. if (bottom > 0 && top < viewPortHeight) {
  2456. findVisible = true;
  2457. lastVisible = tempIndex;
  2458. checkItem.style.contentVisibility = "visible";
  2459. } else {
  2460. if (findVisible && checkItem.style.contentVisibility === "auto") {
  2461. break;
  2462. } else checkItem.style.contentVisibility = "auto";
  2463. }
  2464. }
  2465. if (tempIndex === this.visibilityItems.length - 1) break;
  2466. tempIndex++;
  2467. checkItem = this.visibilityItems[tempIndex];
  2468. }
  2469. if (findVisible) {
  2470. this.visibleIndex = lastVisible;
  2471. }
  2472. }
  2473.  
  2474. setPageElementCss(pageElement, init) {
  2475. let self = this;
  2476. if (pageElement && pageElement.length > 0) {
  2477. let pageElementCss = this.curSiteRule.pageElementCss || rulesData.pageElementCss;
  2478. if (!pageElementCss && init && !this.nextLinkHref) return;
  2479. let contentVisibility = this.curSiteRule.contentVisibility || rulesData.contentVisibility;
  2480. if (!contentVisibility && !pageElementCss) return;
  2481. [].forEach.call(pageElement, (ele, i) => {
  2482. if (!compareNodeName(ele, ["link", "meta", "style", "script"])) {
  2483. if (pageElementCss) {
  2484. if (pageElementCss !== '0' && !ele.dataset.pagetualPageElement) {
  2485. ele.style.cssText = (ele.style.cssText || '') + pageElementCss;
  2486. ele.dataset.pagetualPageElement = 1;
  2487. }
  2488. }
  2489. if (contentVisibility) {
  2490. ele.style.containIntrinsicSize = `auto ${ele.offsetHeight || self.preVisibleHeight || 100}px`;
  2491. if (ele.style.containIntrinsicSize) {
  2492. if (ele.offsetHeight) self.preVisibleHeight = ele.offsetHeight;
  2493. if (init) {
  2494. ele.style.contentVisibility = "visible";
  2495. self.visibilityItems.push(ele);
  2496. self.visibleIndex++;
  2497. } else {
  2498. ele.style.contentVisibility = emuIframe ? "visible" : "auto";
  2499. }
  2500. }
  2501. }
  2502. }
  2503. });
  2504. }
  2505. }
  2506.  
  2507. clearAddedElements() {
  2508. if (this.addedElePool && this.addedElePool.length) {
  2509. this.addedElePool.forEach(ele => {
  2510. if (ele.parentNode) ele.parentNode.removeChild(ele);
  2511. });
  2512. }
  2513. this.addedElePool = [];
  2514. sideController.remove();
  2515. }
  2516.  
  2517. linkHasHref(link) {
  2518. return link.href && link.href.replace && !this.hrefIsJs(link.href);
  2519. }
  2520.  
  2521. hrefIsJs(href) {
  2522. return /^(javascript|#|$)/.test(href.trim().replace("#p{", "").replace(location.href, ""));
  2523. }
  2524.  
  2525. async querySelectorList(source, list, defaultView) {
  2526. for (let i = 0; i < list.length; i++) {
  2527. await sleep(1);
  2528. let sel = list[i];
  2529. let result = getAllElements(sel, source);
  2530. if (result.length > 0) {
  2531. if (defaultView) {
  2532. for (let i = result.length - 1; i >= 0; i--) {
  2533. let ele = result[i];
  2534. if (isVisible(ele, defaultView)) return ele;
  2535. }
  2536. }
  2537. return result[result.length - 1];
  2538. }
  2539. }
  2540. return null;
  2541. }
  2542.  
  2543. verifyElement(ele) {
  2544. let verifyHandler = e => {
  2545. if (e.nodeType == 9) return true;
  2546. if (e.style.display === "none" || e.getAttribute("aria-disabled") === "true") {
  2547. return false;
  2548. }
  2549. if (e.className) {
  2550. if (/slick|slide|gallery|disabled\s*$/i.test(e.className)) {
  2551. return false;
  2552. } else if (e.classList) {
  2553. if (e.classList.contains('disabled') || e.classList.contains('active')) {
  2554. return false;
  2555. }
  2556. }
  2557. }
  2558. let ariaLabel = e.getAttribute("aria-label");
  2559. if (ariaLabel && /slick|slide|gallery/i.test(ariaLabel)) return false;
  2560. return true;
  2561. };
  2562. if (!ele) return false;
  2563. let i = 0;
  2564. while (ele && i++ < 6) {
  2565. if (!verifyHandler(ele)) return false;
  2566. ele = ele.parentNode;
  2567. }
  2568. return true;
  2569. }
  2570.  
  2571. async getPage(doc, exist) {
  2572. if (document.documentElement.className.indexOf && document.documentElement.className.indexOf('discourse') !== -1) return {};
  2573. let body = getBody(doc);
  2574. let canSave = false;//發現頁碼選擇器在其他頁對不上,還是別保存了
  2575. let url = this.curUrl.slice(0, 250).replace("index.php?", "?");
  2576. let _url = url.replace(/\.s?html?$/i, "").toLowerCase();
  2577. let pageNum = 1, preStr = "", afterStr = "";
  2578. let pageTwoReg = /^[\/\?&]?[_-]?(p|page)?=?\/?2(\/[^\/]*$|\?|&|$)/i;
  2579. let pageMatch1 = url.match(/(.*[\?&]p(?:age)?=)(\d+)($|[#&].*)/i);
  2580. let doubtTextReg = /^\s*(»|>>)\s*$/;
  2581. if (pageMatch1) {
  2582. preStr = pageMatch1[1];
  2583. pageNum = parseInt(pageMatch1[2]);
  2584. afterStr = pageMatch1[3];
  2585. } else {
  2586. let pageMatch2 = url.match(/(.*[a-z\/\-_](?:p|page)?\/?)(\d+)(\.s?html?$|\/?$)/i);
  2587. if (pageMatch2) {
  2588. preStr = pageMatch2[1];
  2589. pageNum = parseInt(pageMatch2[2]);
  2590. afterStr = pageMatch2[3];
  2591. if (/^\/?$/.test(afterStr) && !/(p(age)?|_|\-|\/)$/.test(preStr)) {
  2592. preStr = "";
  2593. afterStr = "";
  2594. }
  2595. }
  2596. }
  2597. if (pageNum > 999) {
  2598. pageNum = 1;
  2599. preStr = "";
  2600. afterStr = "";
  2601. }
  2602. let curPage = doc, i, cur, jsNext;
  2603. let next1, next2, next3, next4, nextJs1, nextJs2;
  2604. let selectorList = [
  2605. ".page-next>a",
  2606. "a.next_page",
  2607. "#next_page",
  2608. ".curPage+a",
  2609. ".nextPage",
  2610. ".pagination-next>a",
  2611. "a[data-pagination=next]",
  2612. ".pageButtonsCurrent+a",
  2613. "a[class*=nextpage]",
  2614. "li.page-current+li>a",
  2615. "[class^=pag] a[rel=next]",
  2616. "[class^=Pag] [aria-label=next]",
  2617. "[aria-label='Next Page']",
  2618. "[aria-label='Next page']",
  2619. "[aria-label='next page']",
  2620. ".pagination-nav__item--next>a",
  2621. "a.pageright",
  2622. ".page-numbers.current+a",
  2623. "a.page-numbers.next",
  2624. "body [class*=pagination] li.active+span+li>a",
  2625. "body [class*=pagination] li.active+li>a",
  2626. "body [class^=pag] .current+a",
  2627. ".page_current+a",
  2628. "input[value='next']",
  2629. "input[value='Next page']",
  2630. "input[value='下一页']",
  2631. "input[value='下一頁']",
  2632. "a#pb_next",
  2633. "a#rightFix",
  2634. "a#btnPreGn",
  2635. "a.page-next",
  2636. "a.pages-next",
  2637. "a.page.right",
  2638. ".paging>.active+.item",
  2639. "a#next",
  2640. ".next>a",
  2641. ".next>button",
  2642. "a[alt=next]",
  2643. ".pg_area>em+a",
  2644. "button.next:not([disabled])",
  2645. ".btn_next:not([disabled])",
  2646. ".btn-next:not([disabled])",
  2647. "a#linkNext",
  2648. "body a[class*=page__next]",
  2649. "body [class*=pager]>a.next",
  2650. "body [class*=pagination-next]>a",
  2651. "body [class*=pagination-next]>button",
  2652. "body [class*=page--current]+li>a",
  2653. "body [class*=Pages]>.curr+a",
  2654. "body [class*=pagination] .next-btn",
  2655. ".page>em+a",
  2656. '//button[contains(@class, "Page")][text()="Next"]',
  2657. '//button[contains(@class, "page")][text()="next"]'
  2658. ];
  2659. let next = await this.querySelectorList(body, selectorList, doc.defaultView);
  2660. if (!next) {
  2661. await sleep(1);
  2662. let nexts = body.querySelectorAll("a.next");
  2663. const prevReg = /^\s*([上前首尾]|previous)/i;
  2664. for (i = 0; i < nexts.length; i++) {
  2665. let n = nexts[i];
  2666. if (this.verifyElement(n) && this.linkHasHref(n) && !prevReg.test(n.innerText.trim())) {
  2667. next = n;
  2668. break;
  2669. }
  2670. }
  2671. }
  2672. if (next) {
  2673. let innerText = next.innerText;
  2674. let isJs = !this.linkHasHref(next);
  2675. if (innerText && nextTextReg2.test(innerText.trim())) {
  2676. if (isJs) {
  2677. if (this.verifyElement(next)) {
  2678. nextJs2 = next;
  2679. }
  2680. } else {
  2681. next2 = next;
  2682. }
  2683. next = null;
  2684. } else {
  2685. if (isJs) {
  2686. if (this.verifyElement(next)) {
  2687. jsNext = next;
  2688. }
  2689. next = null;
  2690. }
  2691. }
  2692. }
  2693. if (!next) {
  2694. await sleep(1);
  2695. next = body.querySelector("a.curr+a") ||
  2696. body.querySelector("div.wp-pagenavi>span.current+a,div.page-nav>span.current+a,div.article-paging>span+a") ||
  2697. body.querySelector(".number>ul>li.active+li>a");
  2698. }
  2699. if (!next) {
  2700. await sleep(1);
  2701. let pageDiv = body.querySelector(".pages>ul,.page_no>ul");
  2702. if (pageDiv) {
  2703. cur = pageDiv.querySelector("li>b,li>strong");
  2704. if (cur) next = cur.parentNode.nextElementSibling;
  2705. if (next) next = next.querySelector("a");
  2706. }
  2707. }
  2708. if (!next) {
  2709. await sleep(1);
  2710. next = body.querySelector(".pages>a[href='javascript:;']+a");
  2711. if (next && (next.href === "javascript:;" || next.getAttribute("href") === "#")) next = null;
  2712. }
  2713. if (!next) {
  2714. await sleep(1);
  2715. let pageDiv = body.querySelector(".pagination");
  2716. if (pageDiv) {
  2717. cur = pageDiv.querySelector("[class*=current],.page-selected");
  2718. if (cur) next = cur.parentNode.nextElementSibling;
  2719. if (next) next = next.querySelector("a");
  2720. }
  2721. }
  2722. if (!next) {
  2723. await sleep(1);
  2724. let pageDivs = body.querySelectorAll("[class*=pagination],[class*=Pagination]");
  2725. if (pageDivs && pageDivs.length) {
  2726. for (let i = pageDivs.length - 1; i >= 0; i--) {
  2727. let p = pageDivs[i];
  2728. if (/(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)/i.test(p.title || p.value || '')) {
  2729. next = p.querySelector("a,button,[type='button']") || p;
  2730. break;
  2731. } else if (/^(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)$/i.test((p.innerText || '').trim())) {
  2732. next = p.querySelector("a,button,[type='button']") || p;
  2733. break;
  2734. }
  2735. }
  2736. if (next && !this.linkHasHref(next)) {
  2737. if (!jsNext) jsNext = next;
  2738. next = null;
  2739. }
  2740. }
  2741. }
  2742. if (!next) {
  2743. let isApp = !!body.querySelector("main#app");
  2744. let aTags = body.querySelectorAll("a,button,[type='button'],.btn-action");
  2745. for (i = aTags.length - 1; i >= 0; i--) {
  2746. if (next1) break;
  2747. if (i % 100 === 0) {
  2748. await sleep(1);
  2749. }
  2750. let aTag = aTags[i];
  2751. let title = aTag.title || "";
  2752. let value = aTag.value || "";
  2753. let innerText = aTag.innerText || "";
  2754. if (innerText === "" || (title !== "" && title.length < innerText.length)) {
  2755. innerText = title;
  2756. }
  2757. if (innerText === "" || (value !== "" && value.length < innerText.length)) {
  2758. innerText = value;
  2759. }
  2760. if (innerText !== "") {
  2761. if (innerText === "§") continue;
  2762. innerText = innerText.trim();
  2763. if (innerText.length > 80) continue;
  2764. }
  2765. if (!this.verifyElement(aTag)) continue;
  2766. if (aTag.dataset && aTag.dataset.preview) continue;
  2767. let availableHref = aTag.href && aTag.href.length < 250 && !/^(javascript:|#)/.test(aTag.href);
  2768. if (availableHref && /next\-?(page)?$|\/video\/|\/vod\/play\//i.test(aTag.href)) continue;
  2769. if (compareNodeName(aTag.parentNode, ["blockquote"])) continue;
  2770. if (aTag.previousElementSibling && /\b(play|volume)\b/.test(aTag.previousElementSibling.className)) continue;
  2771. if (aTag.nextElementSibling && /\b(play|volume)\b/.test(aTag.nextElementSibling.className)) continue;
  2772. let isJs = !this.linkHasHref(aTag);
  2773. if (exist && isJs && !aTag.offsetParent) continue;
  2774. if (innerText) {
  2775. innerText = innerText.split(/\n/)[0].replace(/ /g, '');
  2776. if (isJs && /^(»|>>|>|›|→|❯)$/.test(innerText)) continue;
  2777. if (innerText && innerText.length <= 25) {
  2778. if (!next1) {
  2779. if (nextTextReg1.test(innerText)) {
  2780. if (isJs) {
  2781. if (!nextJs1) nextJs1 = aTag;
  2782. } else {
  2783. next1 = aTag;
  2784. }
  2785. }
  2786. }
  2787. if (!next4) {
  2788. if (!next2) {
  2789. if (nextTextReg2.test(innerText) || /nextpage|pager\-older/i.test(aTag.className) || /^(»|>>)$/.test(innerText)) {
  2790. if (isJs) {
  2791. if (!nextJs2) nextJs2 = aTag;
  2792. } else {
  2793. next2 = aTag;
  2794. }
  2795. }
  2796. }
  2797. if (!isApp && !next3 && !isJs) {
  2798. if (/^(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)$/i.test(aTag.textContent) && aTag.parentNode.hasAttribute && !aTag.parentNode.hasAttribute("jsaction")) {
  2799. next3 = aTag;
  2800. }
  2801. }
  2802. }
  2803. }
  2804. }
  2805. if (isJs) continue;
  2806. if (!next4) {
  2807. let prevEle = aTag.previousElementSibling;
  2808. if (prevEle && compareNodeName(prevEle, ["b", "span", "strong"])) {
  2809. if (/^\d+$/.test(aTag.innerText.trim()) && /^\d+$/.test(prevEle.innerText.trim()) && parseInt(aTag.innerText) === parseInt(prevEle.innerText) + 1) {
  2810. next4 = aTag;
  2811. }
  2812. }
  2813. }
  2814. if (urlWillChange) continue;
  2815. if (!next4 && availableHref) {
  2816. let aHref = aTag.href.indexOf("http") === 0 ? aTag.href : this.canonicalUri(aTag.href);
  2817. if (aHref.indexOf(location.hostname) === -1) continue;
  2818. let _aHref = aHref.replace("?&", "?").replace("index.php?", "?");
  2819. if (preStr || afterStr) {
  2820. let _aHrefTrim = _aHref;
  2821. if (preStr) _aHrefTrim = _aHrefTrim.replace(preStr, "");
  2822. if (afterStr) _aHrefTrim = _aHrefTrim.replace(afterStr, "");
  2823. if (_aHrefTrim == pageNum + 1) {
  2824. next4 = aTag;
  2825. }
  2826. } else if (this.curUrl !== aHref) {
  2827. _aHref = _aHref.replace(/\.s?html?$/i, "").toLowerCase();
  2828. if (_aHref.indexOf(_url) !== -1) {
  2829. let pageTwoMatch = _aHref.replace(_url, "").match(pageTwoReg);
  2830. if (pageTwoMatch) {
  2831. afterStr = pageTwoMatch[2];
  2832. next4 = aTag;
  2833. }
  2834. }
  2835. }
  2836. if (next4 && !/page/.test(next4.href)) {
  2837. let curHref = next4.getAttribute("href");
  2838. let curPageReg = new RegExp("(.*)" + (pageNum + 1) + afterStr.replace(/([\.\?])/g, '\\$1'));
  2839. let otherPageHref = curHref.replace(curPageReg, `$1${pageNum}${afterStr}`);
  2840. let otherPageEle = body.querySelector(`a[href='${otherPageHref}']`);
  2841. if (!otherPageEle) {
  2842. otherPageHref = curHref.replace(curPageReg, `$1${pageNum + 2}${afterStr}`);
  2843. otherPageEle = body.querySelector(`a[href='${otherPageHref}']`);
  2844. }
  2845. if (otherPageEle) {
  2846. let parent = otherPageEle.parentNode;
  2847. if (parent && parent.parentNode) {
  2848. parent = parent.parentNode;
  2849. if (parent.parentNode) {
  2850. parent = parent.parentNode;
  2851. }
  2852. }
  2853. if (parent && parent.contains(next4) && !/^\d+$/.test(next4.innerText.trim())) {
  2854. next4 = null;
  2855. }
  2856. }
  2857. }
  2858. }
  2859. }
  2860. if (next2 && doubtTextReg.test(next2.innerText)) {
  2861. next2 = this.verifyNext(next2, doc, false);
  2862. }
  2863. if (nextJs2 && doubtTextReg.test(nextJs2.innerText)) {
  2864. nextJs2 = this.verifyNext(nextJs2, doc, true);
  2865. }
  2866. if (next3) {
  2867. next3 = this.verifyNext(next3, doc, false);
  2868. }
  2869. }
  2870. if (!next) next = next1 || next4 || next3 || next2;
  2871. if (!next && location.pathname + location.search !== "/") {
  2872. next = jsNext || nextJs1 || nextJs2;
  2873. if (next && next.parentNode.className && next.parentNode.className.indexOf && next.parentNode.className.indexOf('tab') !== -1) next = null;
  2874. }
  2875. if (next && next.classList && (next.classList.contains("results-more") || next.classList.contains("no"))) next = null;
  2876. if (next && next.hasAttribute && next.hasAttribute("disabled")) next = null;
  2877. if (next && next.parentNode.href && compareNodeName(next.parentNode, ["a"])) next = next.parentNode;
  2878. return {next:next, canSave:canSave};
  2879. }
  2880.  
  2881. verifyNext(next, doc, isJs) {
  2882. if (!next) return null;
  2883. if (!isJs) {
  2884. let href = next.getAttribute("href");
  2885. if (href && !/\d/.test(next.getAttribute("href"))) {
  2886. return null;
  2887. }
  2888. }
  2889. if (next.previousElementSibling && compareNodeName(next.previousElementSibling, ["br"])) return null;
  2890. let eles = [];
  2891. if (next.innerText && next.innerText.indexOf("\n") === -1) {
  2892. eles = getAllElements(`//${next.nodeName}[text()='${next.innerText}']`, doc);
  2893. }
  2894. if (eles.length >= 2 && eles[0].href !== eles[1].href) {
  2895. next = null;
  2896. } else if (doc === document) {
  2897. let left = getElementLeft(next);
  2898. if (left < 20 || (document.documentElement.scrollWidth > 500 && left < 250)) {
  2899. next = null;
  2900. } else {
  2901. let top = getElementTop(next);
  2902. if (top < 20 || (left < window.innerWidth / 3 && top < window.innerHeight / 3)) {
  2903. next = null;
  2904. } else {
  2905. let bottom = top + next.offsetHeight || 0;
  2906. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  2907. if (scrollH - bottom < 10) next = null;
  2908. }
  2909. }
  2910. }
  2911. return next;
  2912. }
  2913.  
  2914. canonicalUri(src) {
  2915. if (!src) {
  2916. return "";
  2917. }
  2918. if (src.charAt(0) === "#") return this.curUrl + src;
  2919. if (src.charAt(0) === "?") return this.curUrl.replace(/^([^\?#]+).*/, "$1" + src);
  2920. let origin = location.protocol + '//' + location.host;
  2921. let url = this.basePath || origin;
  2922. url = url.replace(/(\?|#).*/, "");
  2923. if (/https?:\/\/[^\/]+$/.test(url)) url = url + '/';
  2924. if (url.indexOf("http") !== 0) url = origin + url;
  2925. var root_page = /^[^\?#]*\//.exec(url)[0],
  2926. root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  2927. absolute_regex = /^\w+\:\/\//;
  2928. this.updateUrl = false;
  2929. while (src.indexOf("../") === 0) {
  2930. src = src.substr(3);
  2931. root_page = root_page.replace(/\/[^\/]+\/$/, "/");
  2932. this.updateUrl = true;
  2933. }
  2934. src = src.replace(/\.\//, "");
  2935. if (/^\/\/\/?/.test(src)) {
  2936. src = location.protocol + src;
  2937. }
  2938. return (absolute_regex.test(src) ? src : ((src.charAt(0) === "/" ? root_domain : root_page) + src));
  2939. }
  2940.  
  2941. getLinkByPage(url, pageNum) {
  2942. if (!url) return null;
  2943. if (this.curSiteRule.pageNum) {
  2944. let result = this.curSiteRule.pageNum;
  2945. let strMatch = result.match(/\{.*?}/);
  2946. if (!strMatch) return null;
  2947. let urlReg = new RegExp("(" + result.replace(strMatch[0], ")\\d+(") + ")", "i");
  2948. let code = strMatch[0].replace(/^{/, "").replace(/}$/, "").replace(/\$p/g, pageNum);
  2949. if (code === pageNum) {
  2950. result = url.replace(urlReg, "$1" + code + "$2");
  2951. } else {
  2952. try {
  2953. code = Function('"use strict";return ' + code)();
  2954. if (code && code % 1 == 0) {
  2955. result = url.replace(urlReg, "$1" + code + "$2");
  2956. } else return null;
  2957. } catch(e) {
  2958. debug(e);
  2959. }
  2960. }
  2961. if (result != url) {
  2962. return result;
  2963. }
  2964. }
  2965. return url.replace(/([&\/\?](p=|page[=\/_-]?))\d+/i, "$1" + pageNum).replace(/([_-])\d+\./i, "$1" + pageNum + ".");
  2966. }
  2967.  
  2968. getPageNumFromUrl(url, defaultPage) {
  2969. if (!url) return defaultPage;
  2970. if (this.curSiteRule.pageNum) {
  2971. let result = this.curSiteRule.pageNum;
  2972. let strMatch = result.match(/\{.*?}/);
  2973. if (!strMatch) return defaultPage;
  2974. let urlReg = new RegExp(".*" + result.replace(strMatch[0], "(\\d+)") + ".*", "i");
  2975. let curShowNum = url.replace(urlReg, "$1");
  2976. if (curShowNum !== url) {
  2977. let code = strMatch[0].replace(/^{/, "").replace(/}$/, "");
  2978. if (code === "$p") {
  2979. return curShowNum;
  2980. } else {
  2981. try {
  2982. let page1 = parseInt(Function('"use strict";return ' + code.replace("$p", "0"))());
  2983. let page2 = parseInt(Function('"use strict";return ' + code.replace("$p", "1"))());
  2984. let numGap = page2 - page1;
  2985. let _page = (parseInt(curShowNum) - page1) / numGap;
  2986. if (_page && _page % 1 === 0) return _page;
  2987. else {
  2988. this.curSiteRule.pageNum = null;
  2989. return defaultPage;
  2990. }
  2991. } catch(e) {
  2992. debug(e);
  2993. }
  2994. }
  2995. } else {
  2996. return defaultPage;
  2997. }
  2998. }
  2999. let pageNum = url.replace(/.*[&\/\?](p=|page[=\/_-]?)(\d+).*/i, "$2");
  3000. return pageNum === url ? defaultPage : (pageNum.length > 4 ? defaultPage : pageNum);
  3001. }
  3002.  
  3003. async getNextLink(doc, exist) {
  3004. let nextLink = null, page, href;
  3005. let getNextLinkByForm = (form, submitBtn, n) => {
  3006. let params = [];
  3007. let formData = new FormData(form);
  3008. if (submitBtn && submitBtn.getAttribute) {
  3009. let btnValue, btnName;
  3010. btnName = submitBtn.getAttribute("name");
  3011. btnValue = submitBtn.getAttribute("value");
  3012. if (btnName && btnValue) params = [btnName + "=" + encodeURIComponent(btnValue)];
  3013. }
  3014. for (let [key, value] of formData) {
  3015. if (n && /^(p|page)$/i.test(key)) {
  3016. params.push(key + '=' + n);
  3017. } else {
  3018. params.push(key + '=' + encodeURIComponent(value));
  3019. }
  3020. }
  3021. params = params.join('&');
  3022. return form.action + (form.action.indexOf('?') === -1 ? '?' : '&') + params + (form.method === 'post' ? '#p{' + params + '}' : '');
  3023. };
  3024. if (this.curSiteRule.pageElementByJs) {
  3025. this.nextLinkHref = "#";
  3026. return true;
  3027. } else if (this.curSiteRule.nextLinkByJs) {
  3028. try {
  3029. let over = _url => {};
  3030. let targetUrl = await ((typeof this.curSiteRule.nextLinkByJs === 'function') ? this.curSiteRule.nextLinkByJs : new AsyncFunction("doc", '"use strict";' + this.curSiteRule.nextLinkByJs))(doc);
  3031. if (targetUrl) nextLink = {href: targetUrl};
  3032. } catch(e) {
  3033. debug(e);
  3034. }
  3035. } else if (this.curSiteRule.nextLinkByUrl) {
  3036. let targetUrl = this.curUrl.replace(new RegExp(this.curSiteRule.nextLinkByUrl[0], "i"), this.curSiteRule.nextLinkByUrl[1]);
  3037. if (targetUrl !== this.curUrl) {
  3038. let includeSel = this.curSiteRule.nextLinkByUrl[2];
  3039. let excludeSel = this.curSiteRule.nextLinkByUrl[3];
  3040. if (includeSel) {
  3041. includeSel = includeSel.trim();
  3042. if (!getElement(includeSel, doc)) {
  3043. this.nextLinkHref=false;
  3044. return null;
  3045. }
  3046. }
  3047. if (excludeSel) {
  3048. excludeSel = excludeSel.trim();
  3049. if (getElement(excludeSel, doc)) {
  3050. this.nextLinkHref=false;
  3051. return null;
  3052. }
  3053. }
  3054. let reps = targetUrl.match(/{.*?}/g);
  3055. if (reps) {
  3056. reps.forEach(rep => {
  3057. let code = rep.replace("{", "").replace("}", "").replace(/\(\)/g, "0");
  3058. let result = code.match(/^(\d*)\+1$/);
  3059. if (result) {
  3060. result = parseInt(result[1] || 1) + 1;
  3061. } else {
  3062. try {
  3063. result = Function('"use strict";return ' + code)();
  3064. } catch(e) {
  3065. debug(e);
  3066. }
  3067. }
  3068. targetUrl = targetUrl.replace(rep, result);
  3069. });
  3070. }
  3071. }
  3072. nextLink = {href: targetUrl};
  3073. } else if (typeof this.curSiteRule.nextLink !== 'undefined') {
  3074. let nextLinkSel = this.curSiteRule.nextLink;
  3075. if (nextLinkSel != 0) {
  3076. if (Array && Array.isArray && Array.isArray(nextLinkSel)) {
  3077. nextLink = getElement(nextLinkSel[nextIndex], doc, null, true);
  3078. if (!nextLink && curPage === 1 && nextIndex !== 0) {
  3079. nextIndex = 0;
  3080. nextLink = getElement(nextLinkSel[nextIndex], doc, null, true);
  3081. }
  3082. } else nextLink = getElement(nextLinkSel, doc, null, true);
  3083. }
  3084. if (nextLink && (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2)) {
  3085. let form = doc.querySelector('#search-form');
  3086. if (!nextLink.href && nextLink.hasAttribute && nextLink.hasAttribute("onclick") && form) {
  3087. if (/^\d+$/.test(nextLink.innerText)) {
  3088. nextLink.href = getNextLinkByForm(form, nextLink, nextLink.innerText);
  3089. }
  3090. } else if (compareNodeName(nextLink, ["input"]) || nextLink.type === "submit") {
  3091. form = nextLink.parentNode;
  3092. while (form) {
  3093. if (compareNodeName(form, ["form"])) break;
  3094. else form = form.parentNode;
  3095. }
  3096. if (form) {
  3097. nextLink.href = getNextLinkByForm(form, nextLink);
  3098. }
  3099. }
  3100. if (nextLink.href && this.curSiteRule.action != 0) {
  3101. nextLink.href = nextLink.href.replace(/#p{.*/, "");
  3102. }
  3103. }
  3104. } else {
  3105. page = await this.getPage(doc, exist);
  3106. nextLink = page.next;
  3107. if (nextLink) {
  3108. if (compareNodeName(nextLink, ["input"]) || nextLink.type === "submit") {
  3109. if (!/next/i.test(nextLink.getAttribute("onclick"))) {
  3110. let form = nextLink.parentNode;
  3111. while (form) {
  3112. if (compareNodeName(form, ["form"])) break;
  3113. else form = form.parentNode;
  3114. }
  3115. if (form) {
  3116. nextLink.href = getNextLinkByForm(form, nextLink);
  3117. }
  3118. }
  3119. }
  3120. let parent = nextLink;
  3121. while (parent && !compareNodeName(parent, ["body"])) {
  3122. if (parent.hasAttribute && parent.hasAttribute("disabled")) {
  3123. this.nextLinkHref = false;
  3124. return null;
  3125. }
  3126. if (parent.className && parent.classList) {
  3127. if (parent.classList.contains("noClick") || parent.classList.contains("no-pages") || parent.classList.contains("disabled")) {
  3128. this.nextLinkHref = false;
  3129. return null;
  3130. }
  3131. }
  3132. if (parent.style && parent.style.display === "none") {
  3133. this.nextLinkHref = false;
  3134. return null;
  3135. }
  3136. parent = parent.parentNode;
  3137. }
  3138. if (doc === document) {
  3139. if (!this.linkHasHref(nextLink)) {
  3140. if ((clickedSth && this.curSiteRule.smart) || !isVisible(nextLink, _unsafeWindow)) {
  3141. this.nextLinkHref = false;
  3142. return null;
  3143. }
  3144. let video = document.querySelector("video,iframe[id*=play],[id*=play]>iframe,iframe[src*=player],iframe[src*=m3u8]");
  3145. if (video) {
  3146. if (video.offsetParent && video.name !== 'pagetual-iframe') {
  3147. let scrollWidth = video.scrollWidth || video.offsetWidth;
  3148. let scrollHeight = video.scrollHeight || video.offsetHeight;
  3149. if (compareNodeName(video, ["iframe"])) {
  3150. } else if (scrollWidth > 100 && scrollHeight > 100) {
  3151. let winWidth = window.innerWidth || document.documentElement.clientWidth;
  3152. let winHeight = window.innerHeight || document.documentElement.clientHeight;
  3153. if (scrollWidth > winWidth>>1 && scrollHeight > winHeight>>1) {
  3154. debug("Disable when large media found");
  3155. } else {
  3156. video = null;
  3157. }
  3158. } else {
  3159. video = null;
  3160. }
  3161. } else {
  3162. video = null;
  3163. }
  3164. }
  3165. if (video) {
  3166. isPause = true;
  3167. this.clearAddedElements();
  3168. this.nextLinkHref = false;
  3169. return null;
  3170. }
  3171. }
  3172.  
  3173. let nextLinkCs = _unsafeWindow.getComputedStyle(nextLink);
  3174. if (nextLinkCs.cursor === "not-allowed") {
  3175. this.nextLinkHref = false;
  3176. return null;
  3177. }
  3178. this.initNext = nextLink;
  3179. }
  3180. let form = doc.querySelector('#search-form');
  3181. if (!nextLink.href && nextLink.hasAttribute("onclick") && form) {
  3182. if (form && /^\d+$/.test(nextLink.innerText)) {
  3183. href = getNextLinkByForm(form, nextLink, nextLink.innerText);
  3184. }
  3185. }
  3186. }
  3187. }
  3188. if (nextLink) {
  3189. if (!this.checkStopSign(nextLink, doc)) {
  3190. if (curPage > 1) {
  3191. if (rulesData.lastPageTips) {
  3192. showTips(i18n("lastPage"), "", 800);
  3193. }
  3194. _unsafeWindow.postMessage({
  3195. action: "lastPage",
  3196. command: 'pagetual'
  3197. }, '*');
  3198. }
  3199. return null;
  3200. }
  3201. if (this.curSiteRule.action == 3) {
  3202. if (doc == document) debug(nextLink, 'Next link');
  3203. this.nextLinkHref = '#';
  3204. } else {
  3205. let needUrl = (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2);
  3206. if (!href) href = nextLink.href;
  3207. if (href && nextLink.getAttribute) {
  3208. let _href = nextLink.getAttribute("href");
  3209. if (_href) {
  3210. if (_href.charAt(0) === "#" || _href === "?"){
  3211. href = "#";
  3212. } else {
  3213. href = _href;
  3214. }
  3215. } else if (_href === "") {
  3216. href = _href;
  3217. }
  3218. }
  3219.  
  3220. if (needUrl && (href === "" || href === null)) {
  3221. this.nextLinkHref = false;
  3222. } else if (needUrl && /^(javascript:|#)/.test(href)) {
  3223. this.nextLinkHref = false;
  3224. } else {
  3225. this.nextLinkHref = (href && !/^(javascript:|#)/.test(href)) ? this.canonicalUri(href) : "#";
  3226. let tempUrl = this.nextLinkHref;
  3227. 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 + "#"))) {
  3228. this.nextLinkHref = false;
  3229. } else if (doc === document) {
  3230. debug(nextLink, 'Next link');
  3231. }
  3232. }
  3233. }
  3234. } else {
  3235. this.nextLinkHref = false;
  3236. }
  3237. this.nextLinkEle = nextLink;
  3238. this.preload();
  3239. return nextLink;
  3240. }
  3241.  
  3242. compareUrl(url1, url2) {
  3243. if (url1 === url2) return true;
  3244. if (!url1 || !url2) return false;
  3245. let url1Arr = url1.split("?");
  3246. let url2Arr = url2.split("?");
  3247. if (url1Arr[0] != url2Arr[0]) return false;
  3248. if (!url1Arr[1] || !url2Arr[1]) return false;
  3249. url1Arr = url1Arr[1].split("&").sort().join("&");
  3250. url2Arr = url2Arr[1].split("&").sort().join("&");
  3251. return url1Arr === url2Arr;
  3252. }
  3253.  
  3254. filterEles(doc, eles) {
  3255. let filter = this.curSiteRule.filter;
  3256. if (!filter || !eles || eles.length === 0) return;
  3257. if (eles.length === 1) {
  3258. eles = eles[0].children;
  3259. if (eles.length === 1) {
  3260. eles = eles[0].children;
  3261. }
  3262. }
  3263. if (typeof filter === "string") {
  3264. if (/^\d+$/.test(filter)) {
  3265. filter = {count: parseInt(filter)};
  3266. } else filter = {words: filter};
  3267. }
  3268. [].forEach.call(eles, ele => {
  3269. if (!ele.parentNode) return;
  3270. let canKeep = (() => {
  3271. let innerText = (ele.innerText && ele.innerText.trim()) || "";
  3272. if (filter.count) {
  3273. if (innerText.length < filter.count) return false;
  3274. }
  3275. if (filter.words) {
  3276. let wordsRegExp = new RegExp(filter.words, "i");
  3277. if (innerText && wordsRegExp.test(innerText)) return false;
  3278. }
  3279. if (filter.link) {
  3280. let linkRegExp = new RegExp(filter.link, "i");
  3281. if (compareNodeName(ele, ["a"]) && linkRegExp.test(ele.href)) return false;
  3282. let aChildren = ele.querySelectorAll("a");
  3283. for (let i = 0; i < aChildren.length; i++) {
  3284. let child = aChildren[i];
  3285. if (linkRegExp.test(child.href)) return false;
  3286. }
  3287. }
  3288. if (filter.selector) {
  3289. if (getElement(filter.selector, doc, ele)) return false;
  3290. }
  3291. return true;
  3292. })();
  3293. if (!canKeep) {
  3294. ele.parentNode.removeChild(ele);
  3295. }
  3296. });
  3297. }
  3298.  
  3299. checkStopSign(nextLink, doc) {
  3300. if (this.curSiteRule.stopSign) {
  3301. let typeArray = Array && Array.isArray && Array.isArray(this.curSiteRule.stopSign);
  3302. let typeObject = !typeArray && (this.curSiteRule.stopSign.include || this.curSiteRule.stopSign.exclude || this.curSiteRule.stopSign.pageNum);
  3303. if (typeArray || typeObject) {
  3304. let includeSel, excludeSel, curSign, maxSign;
  3305. if (typeArray) {
  3306. includeSel = this.curSiteRule.stopSign[0];
  3307. excludeSel = this.curSiteRule.stopSign[1];
  3308. curSign = this.curSiteRule.stopSign[2];
  3309. maxSign = this.curSiteRule.stopSign[3];
  3310. if (Array && Array.isArray && Array.isArray(includeSel) && !curSign) {
  3311. curSign = includeSel;
  3312. includeSel = false;
  3313. }
  3314. if (excludeSel && Array && Array.isArray && Array.isArray(excludeSel) && !maxSign) {
  3315. maxSign = excludeSel;
  3316. excludeSel = false;
  3317. }
  3318. } else {
  3319. includeSel = this.curSiteRule.stopSign.include;
  3320. excludeSel = this.curSiteRule.stopSign.exclude;
  3321. curSign = this.curSiteRule.stopSign.pageNum;
  3322. }
  3323. if (includeSel) {
  3324. includeSel = includeSel.trim();
  3325. if (!getElement(includeSel, doc)) {
  3326. isPause = true;
  3327. this.nextLinkHref = false;
  3328. return false;
  3329. }
  3330. }
  3331. if (excludeSel) {
  3332. excludeSel = excludeSel.trim();
  3333. if (getElement(excludeSel, doc)) {
  3334. isPause = true;
  3335. this.nextLinkHref = false;
  3336. return false;
  3337. }
  3338. }
  3339. if (curSign) {
  3340. if (!maxSign) maxSign = curSign.slice(2);
  3341. let currentEle = getElement(curSign[0], doc);
  3342. let maxEle = getElement(maxSign[0], doc);
  3343. if (currentEle && maxEle) {
  3344. let currentSignNum, maxSignNum;
  3345. if (/\(.*\)/.test(curSign[1])) {
  3346. currentSignNum = currentEle.innerText.match(new RegExp(curSign[1]));
  3347. if (currentSignNum) currentSignNum = currentSignNum[1];
  3348. } else if (currentEle.getAttribute) {
  3349. currentSignNum = currentEle.getAttribute(curSign[1]);
  3350. }
  3351. if (/\(.*\)/.test(maxSign[1])) {
  3352. maxSignNum = maxEle.innerText.match(new RegExp(maxSign[1]));
  3353. if (maxSignNum) maxSignNum = maxSignNum[1];
  3354. } else if (maxEle.getAttribute) {
  3355. maxSignNum = maxEle.getAttribute(maxSign[1]);
  3356. }
  3357. if (currentSignNum && maxSignNum && currentSignNum == maxSignNum) {
  3358. isPause = true;
  3359. this.nextLinkHref = false;
  3360. return false;
  3361. }
  3362. }
  3363. }
  3364. } else {
  3365. try {
  3366. let stopSign = ((typeof this.curSiteRule.stopSign === 'function') ? this.curSiteRule.stopSign : Function("doc", "nextLink", '"use strict";' + this.curSiteRule.stopSign))(doc, nextLink);
  3367. if (stopSign) {
  3368. isPause = true;
  3369. this.nextLinkHref = false;
  3370. return false;
  3371. }
  3372. } catch(e) {
  3373. debug(e);
  3374. }
  3375. }
  3376. }
  3377. return true;
  3378. }
  3379.  
  3380. preloadImageHandler() {
  3381. if (this.preloadingImage || !this.unCheckedImgs.length) return;
  3382. this.preloadingImage = true;
  3383. setTimeout(() => {
  3384. this.preloadingImage = false;
  3385. this.preloadImageHandler();
  3386. }, 10);
  3387. let iSrc = this.unCheckedImgs.shift();
  3388. let img = document.createElement('img');
  3389. img.src = iSrc;
  3390. this.preloadDiv.appendChild(img);
  3391. }
  3392.  
  3393. preload() {
  3394. if (!rulesData.preload) return;
  3395. if (this.curSiteRule.preload === 0) return;
  3396. if (!this.nextLinkHref || this.nextLinkHref == "#") return;
  3397. if (this.readyStateUnComplete) return;
  3398. if (document.readyState !== 'complete') {
  3399. this.readyStateUnComplete = true;
  3400. let self = this;
  3401. window.addEventListener("load", e => {
  3402. self.readyStateUnComplete = false;
  3403. self.preload();
  3404. });
  3405. return;
  3406. }
  3407. let self = this, url = this.nextLinkHref;
  3408. let postParams = url.match(/#p{(.*)}$/);
  3409. if (postParams) {
  3410. postParams = postParams[1];
  3411. url = url.replace(/#p{.*/, "");
  3412. }
  3413. _GM_xmlhttpRequest({
  3414. url: url,
  3415. method: postParams ? 'POST' : 'GET',
  3416. data: postParams,
  3417. overrideMimeType: 'text/html;charset=' + charset,
  3418. headers: {
  3419. 'Referer': location.href,
  3420. 'User-Agent': navigator.userAgent,
  3421. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + charset,
  3422. },
  3423. timeout: 10000,
  3424. onload: function(res) {
  3425. var doc = null;
  3426. try {
  3427. doc = document.implementation.createHTMLDocument('');
  3428. doc.documentElement.innerHTML = createHTML(res.response);
  3429. var body = getBody(doc);
  3430. if (!self.preloadDiv) {
  3431. self.preloadDiv = document.createElement('div');
  3432. self.preloadDiv.id = "pagetual-preload";
  3433. self.preloadDiv.style.cssText = 'display:none!important;';
  3434. getBody(document).appendChild(self.preloadDiv);
  3435. self.checkedImgs = {};
  3436. self.unCheckedImgs = [];
  3437. }
  3438. let code = self.curSiteRule.preloadImages;
  3439. if (code) {
  3440. let imgSrcArr = new Function("doc", '"use strict";' + code)(doc);
  3441. if (imgSrcArr && imgSrcArr.length) {
  3442. imgSrcArr.forEach(imgSrc => {
  3443. if (imgSrc && !self.checkedImgs[imgSrc]) {
  3444. self.checkedImgs[imgSrc] = true;
  3445. self.unCheckedImgs.push(imgSrc);
  3446. }
  3447. });
  3448. }
  3449. self.preloadImageHandler();
  3450. } else if (code !== 0 && code !== false) {
  3451. if (body && body.firstChild) {
  3452. self.lazyImgAction(body.children, doc);
  3453. }
  3454. [].forEach.call(doc.images, i => {
  3455. let iSrc = i.src;
  3456. if (iSrc && !self.checkedImgs[iSrc]) {
  3457. self.checkedImgs[iSrc] = true;
  3458. self.unCheckedImgs.push(iSrc);
  3459. }
  3460. });
  3461. self.preloadImageHandler();
  3462. }
  3463. }
  3464. catch(e) {
  3465. debug(e);
  3466. return;
  3467. }
  3468. }
  3469. });
  3470. }
  3471.  
  3472. getInsert(refresh) {
  3473. if (refresh) {
  3474. this.insert = null;
  3475. }
  3476. if (this.insert && this.insert.parentNode && document.documentElement.contains(this.insert)) {
  3477. return this.insert;
  3478. }
  3479. if (this.curSiteRule.insert) {
  3480. let insertSel = this.curSiteRule.insert;
  3481. if (Array && Array.isArray && Array.isArray(insertSel)) {
  3482. insertSel = insertSel[nextIndex < insertSel.length ? nextIndex : 0];
  3483. }
  3484. this.insert = getElement(insertSel, document, null, true);
  3485. } else {
  3486. this.docPageElement = null;
  3487. let pageElement = this.getPageElement(document, _unsafeWindow);
  3488. if (this.curSiteRule.smart && this.nextLinkHref == "#" && this.curSiteRule.pageElement === 'body') {
  3489. debug("Stop as jsNext & whole body");
  3490. isPause = true;
  3491. return null;
  3492. }
  3493. if (pageElement && pageElement.length > 0) {
  3494. let pEIndex = pageElement.length - 1;
  3495. let pELast = pageElement[pEIndex];
  3496. while(pELast && compareNodeName(pELast, ["link", "meta", "style", "script"])) {
  3497. pEIndex--;
  3498. pELast = pageElement[pEIndex];
  3499. }
  3500. this.insert = pELast.nextSibling ? pELast.nextSibling : pELast.parentNode.appendChild(document.createTextNode(' '));
  3501. }
  3502. }
  3503. return this.insert;
  3504. }
  3505.  
  3506. pageInit(doc, eles) {
  3507. let code = this.curSiteRule.pageInit;
  3508. if (code) {
  3509. let initFunc = ((typeof code == 'function') ? code : Function("doc", "eles", '"use strict";' + code));
  3510. let checkInit = (resolve) => {
  3511. try {
  3512. if (initFunc(doc, eles) === false) {
  3513. setTimeout(() => {
  3514. checkInit(resolve);
  3515. }, 100);
  3516. } else {
  3517. resolve(true);
  3518. }
  3519. } catch(e) {
  3520. resolve(false);
  3521. debug(e);
  3522. }
  3523. };
  3524. return new Promise((resolve) => {
  3525. checkInit(function(e) {
  3526. resolve(e)
  3527. });
  3528. })
  3529. }
  3530. }
  3531.  
  3532. pageAction(doc, eles) {
  3533. let code = this.curSiteRule.pageAction;
  3534. if (code) {
  3535. try {
  3536. ((typeof code == 'function') ? code : Function("doc", "eles", '"use strict";' + code))(doc, eles);
  3537. } catch(e) {
  3538. debug(e);
  3539. }
  3540. }
  3541. this.openInNewTab(eles);
  3542. this.replaceElement(doc);
  3543. }
  3544.  
  3545. openInNewTab(eles) {
  3546. if (openInNewTab) {
  3547. [].forEach.call(eles, ele => {
  3548. if (compareNodeName(ele, ["a"]) && ele.href && !/^(mailto:|javascript:)|#/.test(ele.href)) {
  3549. ele.setAttribute('target', openInNewTab == 1 ? '_blank' : '_self');
  3550. } else {
  3551. [].forEach.call(ele.querySelectorAll('a[href]:not([href^="mailto:"]):not([href^="javascript:"]):not([href^="#"])'), a => {
  3552. if (openInNewTab == 1) {
  3553. a.setAttribute('target', '_blank');
  3554. if (a.getAttribute('onclick') == 'atarget(this)') {
  3555. a.removeAttribute('onclick');
  3556. }
  3557. } else a.setAttribute('target', '_self');
  3558. });
  3559. }
  3560. });
  3561. }
  3562. }
  3563.  
  3564. lazyImgAction(eles, doc) {
  3565. if (!eles || eles.length == 0) return;
  3566. let lazyImgSrc = this.curSiteRule.lazyImgSrc;
  3567. if (lazyImgSrc === 0 || lazyImgSrc === '0') return;
  3568. let imgLazyAttrs = [];
  3569. 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"];
  3570. let removeProps = [];
  3571. let setLazyImg = img => {
  3572. let realSrc;
  3573. imgLazyAttrs.forEach(attr => {
  3574. realSrc = img.getAttribute(lazyImgSrc[0]);
  3575. if (realSrc) {
  3576. removeProps.forEach(prop => {
  3577. img.removeAttribute(prop.trim());
  3578. });
  3579. img.src = realSrc;
  3580. return;
  3581. }
  3582. })
  3583. if (!realSrc) {
  3584. let lazyAttr = "";
  3585. if (img.getAttribute("_src") && !img.src) {
  3586. lazyAttr = "_src";
  3587. realSrc = img.getAttribute(lazyAttr);
  3588. } else {
  3589. for (let i in lazyImgAttr) {
  3590. lazyAttr = lazyImgAttr[i];
  3591. let attrValue = img.getAttribute(lazyAttr);
  3592. if (attrValue) {
  3593. realSrc = attrValue;
  3594. break;
  3595. }
  3596. }
  3597. }
  3598. if (!realSrc && img._lazyrias && img._lazyrias.srcset) {
  3599. realSrc = img._lazyrias.srcset[img._lazyrias.srcset.length - 1];
  3600. lazyAttr = "_lazyrias";
  3601. }
  3602. if (!realSrc && img.srcset) {
  3603. lazyAttr = "srcset";
  3604. var srcs = img.srcset.split(/[xw],/i), largeSize = 0;
  3605. srcs.forEach(srci => {
  3606. let srcInfo = srci.trim().split(" "), curSize = parseInt(srcInfo[1]);
  3607. if (srcInfo[1] && curSize > largeSize) {
  3608. largeSize = curSize;
  3609. realSrc = srcInfo[0];
  3610. }
  3611. });
  3612. }
  3613. if (realSrc) {
  3614. img.src = realSrc;
  3615. img.removeAttribute("srcset");
  3616. img.removeAttribute(lazyAttr);
  3617. if (img.classList && img.classList.contains && img.classList.contains("lazy")) {
  3618. img.classList.remove("lazy");
  3619. }
  3620. if (img.style.display == "none") {
  3621. img.style.display = "";
  3622. }
  3623. if (img.style.visibility == "hidden") {
  3624. img.style.visibility = "";
  3625. }
  3626. if (img.style.opacity == 0) {
  3627. img.style.opacity = "";
  3628. }
  3629. }
  3630. }
  3631. };
  3632. if (lazyImgSrc) {
  3633. if (!Array.isArray(lazyImgSrc)) {
  3634. lazyAttrs = lazyImgSrc.split(",");
  3635. } else {
  3636. lazyAttrs = lazyImgSrc[0].split(",");
  3637. removeProps = lazyImgSrc[1].split(",");
  3638. }
  3639. }
  3640. lazyAttrs.forEach(attr => {
  3641. let attrArr = attr.split("|");
  3642. if (attrArr.length !== 2) {
  3643. imgLazyAttrs.push(attr.trim());
  3644. } else {
  3645. let selector = attrArr[0].trim();
  3646. let lazyAttr = attrArr[1].trim();
  3647. if (selector == "img") {
  3648. imgLazyAttrs.push(lazyAttr);
  3649. } else {
  3650. selector += "[" + lazyAttr + "]";
  3651. [].forEach.call(doc.querySelectorAll(selector), ele => {
  3652. ele.style.setProperty("background-image", "url(" + ele.getAttribute(lazyAttr) + ")", "important");
  3653. removeProps.forEach(prop => {
  3654. ele.removeAttribute(prop.trim());
  3655. });
  3656. });
  3657. }
  3658. }
  3659. });
  3660. [].forEach.call(doc.querySelectorAll("img,picture>source"), img => {
  3661. setLazyImg(img);
  3662. });
  3663. }
  3664.  
  3665. canListenUrlChange() {
  3666. if (this.curSiteRule && typeof this.curSiteRule.listenUrlChange === 'undefined' && this.docElementValid()) {
  3667. return false;
  3668. }
  3669. return true;
  3670. }
  3671.  
  3672. docElementValid() {
  3673. return (this.docPageElement && document.documentElement.contains(this.docPageElement[0]));
  3674. }
  3675.  
  3676. urlChanged() {
  3677. urlChanged = true;
  3678. this.clearAddedElements();
  3679. }
  3680.  
  3681. initPage(callback) {
  3682. let self = this;
  3683. if (self.initing) return;
  3684. self.initing = true;
  3685. setTimeout(() => {
  3686. self.initing = false;
  3687. }, 100);
  3688. curPage = 1;
  3689. urlChanged = false;
  3690. tryTimes = 0;
  3691. this.clearAddedElements();
  3692. this.insert = null;
  3693. this.visibilityItems = [];
  3694. this.visibleIndex = -1;
  3695. this.pageDoc = document;
  3696. this.nextLinkHref = null;
  3697. this.curUrl = location.href;
  3698. this.oldUrl = "";
  3699. this.initUrl = location.href;
  3700. this.historyUrl = "";
  3701. this.possibleCheck = 0;
  3702. let base = document.querySelector("base");
  3703. this.basePath = base ? base.href : location.href;
  3704. this.getRule(async () => {
  3705. if (self.curSiteRule.sideController === true || (self.curSiteRule.sideController !== false && rulesData.sideController)) {
  3706. isPause = manualPause;
  3707. }
  3708. if (typeof(self.curSiteRule.rate) !== "undefined") {
  3709. rate = self.curSiteRule.rate;
  3710. }
  3711. if (self.curSiteRule.enable == 0) {
  3712. debug("Stop as rule disable");
  3713. isPause = true;
  3714. _GM_registerMenuCommand(i18n("enable"), () => {
  3715. showTips(i18n("enableSiteTips"));
  3716. if(!self.customRules) {
  3717. self.customRules = [];
  3718. }
  3719. for (let i in self.customRules) {
  3720. if (self.customRules[i].url == self.curSiteRule.url) {
  3721. self.customRules.splice(i, 1);
  3722. break;
  3723. }
  3724. }
  3725. self.curSiteRule.enable = 1;
  3726. self.customRules.unshift(self.curSiteRule);
  3727. storage.setItem("customRules", self.customRules);
  3728. location.reload();
  3729. });
  3730. return;
  3731. }
  3732. if (rulesData.sideControllerAlways) {
  3733. sideController.setup();
  3734. }
  3735. //若是再亂匹配就不緩存wedata,或者只在找完本地規則之後再考慮wedata的緩存
  3736. if (self.curSiteRule.smart) {
  3737. delete self.curSiteRule.pageElement;
  3738. if (!self.possibleRule) {
  3739. self.smartRules = self.smartRules.filter(item => {return item && item.url != self.curSiteRule.url});
  3740. self.smartRules.unshift(self.curSiteRule);
  3741. if (self.smartRules.length > 100) {
  3742. self.smartRules.pop();
  3743. }
  3744. storage.setItem("smartRules", self.smartRules);
  3745. }
  3746. } else if (self.curSiteRule && self.curSiteRule.url.length > 13) {
  3747. self.addToHpRules();
  3748. }
  3749. let css = self.curSiteRule.css || rulesData.customCss;
  3750. if (css) {
  3751. let cssArr = css.split("inIframe:");
  3752. if (cssArr && cssArr.length) {
  3753. _GM_addStyle(cssArr[0]);
  3754. }
  3755. }
  3756. if (/sidesearch=(1|true)$/.test(self.curUrl)) {
  3757. openInNewTab = 0;
  3758. } else if (typeof self.curSiteRule.openInNewTab !== 'undefined') {
  3759. openInNewTab = self.curSiteRule.openInNewTab ? 1 : 2;
  3760. }
  3761. let autoClick = self.curSiteRule.autoClick;
  3762. if (autoClick) {
  3763. let autoClickBtn;
  3764. autoClickBtn = getElement(autoClick, document, null, true);
  3765. if (autoClickBtn) {
  3766. emuClick(autoClickBtn);
  3767. }
  3768. }
  3769. let code = self.curSiteRule.init;
  3770. if (code) {
  3771. try {
  3772. 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)});
  3773. } catch(e) {
  3774. debug(e);
  3775. }
  3776. }
  3777. await self.getNextLink(document, true);
  3778. if (self.curSiteRule.pageNum && self.nextLinkHref && self.nextLinkHref != "#") {
  3779. let num1st = self.getPageNumFromUrl(location.href, 1);
  3780. let num2nd = self.getPageNumFromUrl(self.nextLinkHref, 1);
  3781. if (num2nd != num1st + 1) {
  3782. self.curSiteRule.pageNum = null;
  3783. }
  3784. }
  3785. if (self.curSiteRule.smart && self.nextLinkHref == false && self.possibleRule) {
  3786. let urlReg = new RegExp(self.possibleRule.url, "i");
  3787. function checkPossible () {
  3788. if (self.possibleCheck++ < 3) {
  3789. setTimeout(() => {
  3790. if (self.curSiteRule.smart) {
  3791. var href = location.href.slice(0, 500);
  3792. if (urlReg.test(href) && self.ruleMatch(self.possibleRule)) {
  3793. self.initPage(() => {});
  3794. } else checkPossible();
  3795. }
  3796. }, 3000);
  3797. }
  3798. }
  3799. checkPossible();
  3800. }
  3801. self.refreshByClick();
  3802. if (emuIframe && emuIframe.parentNode) {
  3803. emuIframe.parentNode.removeChild(emuIframe);
  3804. emuIframe = null;
  3805. }
  3806.  
  3807. let pageElementCss = self.curSiteRule.pageElementCss || rulesData.pageElementCss;
  3808. if (pageElementCss && pageElementCss !== '0') {
  3809. self.getPageElement(document, _unsafeWindow);
  3810. }
  3811. callback();
  3812. let initRun = typeof self.curSiteRule.initRun == 'undefined' ? rulesData.initRun : self.curSiteRule.initRun;
  3813. if (self.nextLinkHref) {
  3814. sideController.setup();
  3815. if (initRun && initRun != false) {
  3816. setTimeout(() => {
  3817. nextPage();
  3818. }, 300);
  3819. }
  3820. }
  3821. });
  3822. }
  3823.  
  3824. async hookUrlSetEle(ele, doc) {
  3825. let self = this;
  3826. return new Promise((resolve) => {
  3827. let catchUrl = e => {
  3828. ele.dataset.url = self.catchedUrl;
  3829. ele.setAttribute('onclick', 'window.open(this.dataset.url)');
  3830. window.removeEventListener('pagetual_openUrl', catchUrl);
  3831. resolve();
  3832. };
  3833. window.addEventListener('pagetual_openUrl', catchUrl);
  3834. emuClick(ele, doc);
  3835. });
  3836. }
  3837.  
  3838. async hookUrl(doc) {
  3839. let sel = this.curSiteRule.hookUrl;
  3840. if (!sel) return;
  3841. let self = this;
  3842. if (!this.initHook) {
  3843. this.initHook = true;
  3844. Object.defineProperty(doc.defaultView, 'open', {
  3845. get: function () {
  3846. return (s) => {
  3847. self.catchedUrl = s;
  3848. var e = new CustomEvent('pagetual_openUrl');
  3849. window.dispatchEvent(e);
  3850. }
  3851. }
  3852. });
  3853. }
  3854. let eles = getAllElements(sel, doc);
  3855. for (let i = 0; i < eles.length; i++) {
  3856. await sleep(1);
  3857. let ele = eles[i];
  3858. if (!ele.dataset.url) {
  3859. await this.hookUrlSetEle(ele, doc);
  3860. }
  3861. }
  3862. }
  3863.  
  3864. beginLoading() {
  3865. isLoading = true;
  3866. if (targetY >= 0) {
  3867. window.scrollTo({ top: targetY, behavior: 'instant'});
  3868. targetY = -1;
  3869. }
  3870. let lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3871. ruleParser.insertElement(loadingDiv);
  3872. if (forceState == 2) {
  3873. getBody(document).appendChild(loadingDiv);
  3874. } else {
  3875. let parent = loadingDiv.parentNode;
  3876. if (compareNodeName(parent, ["tbody"])) {
  3877. parent = parent.parentNode;
  3878. }
  3879. if (compareNodeName(parent, ["table"])) {
  3880. parent.parentNode.appendChild(loadingDiv);
  3881. }
  3882. }
  3883. getBody(document).scrollTop = lastScrollTop;
  3884. document.documentElement.scrollTop = lastScrollTop;
  3885. }
  3886.  
  3887. insertElement(ele) {
  3888. if (!this.insert || !this.insert.parentNode) {
  3889. this.getInsert();
  3890. }
  3891. if (this.insert && this.insert.parentNode) {
  3892. let self = this;
  3893. if (ele.nodeName == "#document-fragment") {
  3894. [].forEach.call(ele.children, el => {
  3895. self.addedElePool.push(el);
  3896. });
  3897. } else {
  3898. this.addedElePool.push(ele);
  3899. }
  3900. if (this.curSiteRule.insertPos == 2 || this.curSiteRule.insertPos == "in") {
  3901. this.insert.appendChild(ele);
  3902. } else {
  3903. this.insert.parentNode.insertBefore(ele, this.insert);
  3904. }
  3905. }
  3906. }
  3907.  
  3908. noValidContent(url) {
  3909. if (!this.curSiteRule.nextLinkByUrl) showTips(i18n("noValidContent"), url);
  3910. }
  3911.  
  3912. async insertPage(doc, eles, url, callback, tried) {
  3913. this.oldUrl = this.curUrl;
  3914. let oldTitle = document.title;
  3915. try {
  3916. let oldTitle = this.pageDoc.title;
  3917. } catch (e) {}
  3918. this.pageDoc = doc;
  3919. this.curUrl = url;
  3920. isLoading = true;
  3921. let nextLink = await this.getNextLink(doc);
  3922. this.nextTitle = "";
  3923. if (this.curSiteRule.pageBarText) {
  3924. if (this.curSiteRule.pageBarText == 1 || this.curSiteRule.pageBarText == true) {
  3925. this.nextTitle = doc.title;
  3926. } else {
  3927. try {
  3928. this.nextTitle = ((typeof this.curSiteRule.pageBarText == 'function') ? this.curSiteRule.pageBarText : Function("doc",'"use strict";' + this.curSiteRule.pageBarText))(doc);
  3929. } catch(e) {
  3930. debug(e);
  3931. }
  3932. }
  3933. }
  3934. if (curPage == 1 && !tried && !nextLink && this.curSiteRule.smart && this.curSiteRule.pageElement && this.curSiteRule.action != 0) {
  3935. this.curSiteRule.action = 1;
  3936. this.curUrl = location.href;
  3937. isLoading = false;
  3938. return false;
  3939. }
  3940.  
  3941. if (targetY >= 0) {
  3942. window.scrollTo({ top: targetY, behavior: 'instant'});
  3943. targetY = -1;
  3944. }
  3945. let lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3946. this.getInsert();
  3947. await this.pageInit(doc, eles);
  3948. var self = this, newEles = [];
  3949. if (!eles || eles.length == 0 || !self.insert || !self.insert.parentNode) {
  3950. if (callback) callback(eles);
  3951. loadPageOver();
  3952. } else {
  3953. if (callback) callback(eles);
  3954. loadPageOver();
  3955. const collection = document.createDocumentFragment();
  3956. [].forEach.call(eles, ele => {
  3957. let newEle = ele.cloneNode(true);
  3958. let oldCanvass = ele.querySelectorAll("canvas");
  3959. let newCanvass = newEle.querySelectorAll("canvas");
  3960. if (self.updateUrl) {
  3961. [].forEach.call(newEle.querySelectorAll("img"), img => {
  3962. if (img.getAttribute("src")) img.src = self.canonicalUri(img.getAttribute("src"));
  3963. });
  3964. [].forEach.call(newEle.querySelectorAll("a"), a => {
  3965. if (a.getAttribute("href")) a.href = self.canonicalUri(a.getAttribute("href"));
  3966. });
  3967. }
  3968. for (let i = 0; i < oldCanvass.length; i++) {
  3969. let oldCanvas = oldCanvass[i];
  3970. let newCanvas = newCanvass[i];
  3971. newCanvas.getContext('2d').drawImage(oldCanvas, 0, 0);
  3972. }
  3973. if (!compareNodeName(newEle, ["style", "script"])) self.visibilityItems.push(newEle);
  3974. collection.appendChild(newEle)
  3975. newEles.push(newEle);
  3976. });
  3977. self.insertElement(collection);
  3978. }
  3979. getBody(document).scrollTop = lastScrollTop;
  3980. document.documentElement.scrollTop = lastScrollTop;
  3981. this.pageAction(doc, newEles);
  3982. let enableHistory = this.curSiteRule.history;
  3983. let enableHistoryAfterInsert = false;
  3984. if (enableHistory == 1) {
  3985. enableHistory = true;
  3986. } else if (enableHistory == 2) {
  3987. enableHistory = true;
  3988. enableHistoryAfterInsert = true;
  3989. } else if (enableHistory == 0) {
  3990. enableHistory = false;
  3991. } else {
  3992. enableHistory = rulesData.enableHistory;
  3993. enableHistoryAfterInsert = rulesData.enableHistoryAfterInsert;
  3994. }
  3995. if (enableHistory) {
  3996. this.historyUrl = enableHistoryAfterInsert ? this.curUrl : this.oldUrl;
  3997. if(this.historyUrl != location.href) {
  3998. let isJs = this.hrefIsJs(this.historyUrl);
  3999. if (!isJs) {
  4000. let historyTitle = enableHistoryAfterInsert ? doc.title : oldTitle;
  4001. _unsafeWindow.history.replaceState(undefined, historyTitle, this.historyUrl);
  4002. document.title = historyTitle;
  4003. }
  4004. }
  4005. }
  4006. isLoading = false;
  4007. _unsafeWindow.postMessage({
  4008. action: "insert",
  4009. command: 'pagetual'
  4010. }, '*');
  4011. return true;
  4012. }
  4013. }
  4014. var ruleParser = new RuleParser();
  4015.  
  4016. class SideController {
  4017. //static controller;
  4018. constructor() {
  4019. this.inited = false;
  4020. }
  4021.  
  4022. /*static getInstance() {
  4023. if (!SideController.controller) {
  4024. SideController.controller = new SideController();
  4025. }
  4026. return SideController.controller;
  4027. }*/
  4028.  
  4029. setup() {
  4030. if (ruleParser.curSiteRule.sideController === false) return;
  4031. if (!rulesData.sideController && !ruleParser.curSiteRule.sideController) return;
  4032. this.addToStage();
  4033. }
  4034.  
  4035. init() {
  4036. if (this.inited) return;
  4037. this.inited = true;
  4038. let self = this;
  4039. this.cssText = `
  4040. #pagetual-sideController {
  4041. position: fixed;
  4042. top: calc(50% - 83px);
  4043. left: calc(99% - 40px);
  4044. width: 40px;
  4045. border-radius: 20px;
  4046. box-shadow: rgb(0 0 0) 0px 0px 10px;
  4047. text-align: center;
  4048. background: #ffffffd0!important;
  4049. user-select: none;
  4050. z-index: 2147483646!important;
  4051. padding: 0!important;
  4052. opacity: 0.35;
  4053. transition: opacity .5s ease, background .5s, box-shadow .5s;
  4054. }
  4055. #pagetual-sideController * {
  4056. font-weight: bold;
  4057. font-family: arial;
  4058. font-style: normal;
  4059. font-size: 20px!important;
  4060. color: black!important;
  4061. line-height: normal;
  4062. float: none;
  4063. text-align: center;
  4064. }
  4065. #pagetual-sideController.stop {
  4066. -webkit-filter: invert(100%);
  4067. filter: invert(100%);
  4068. }
  4069. .pagetual-sideController-btn {
  4070. padding: 5px 0;
  4071. cursor: pointer;
  4072. transition: transform .15s ease-in-out, opacity .3s ease;
  4073. }
  4074. #pagetual-sideController .pagetual-sideController-btn:hover {
  4075. transform: scale(1.5);
  4076. color: red!important;
  4077. }
  4078. #pagetual-sideController #pagetual-sideController-move > svg {
  4079. transition: transform .3s ease;
  4080. }
  4081. #pagetual-sideController #pagetual-sideController-move > svg:hover {
  4082. transform: scale(1.2);
  4083. }
  4084. #pagetual-sideController.minSize #pagetual-sideController-move > svg {
  4085. background: white;
  4086. opacity: 0;
  4087. }
  4088. #pagetual-sideController #pagetual-sideController-move > img,
  4089. #pagetual-sideController #pagetual-sideController-move > span {
  4090. width: 35px;
  4091. height: 35px;
  4092. cursor: pointer;
  4093. }
  4094. #pagetual-sideController.minSize #pagetual-sideController-move > img,
  4095. #pagetual-sideController.minSize #pagetual-sideController-move > span {
  4096. border-radius: 50px;
  4097. text-shadow: rgb(255 255 255) 0px 0px 10px;
  4098. }
  4099. #pagetual-sideController #pagetual-sideController-pagenum {
  4100. font-size: 15px!important;
  4101. line-height: 30px;
  4102. text-align: center;
  4103. position: absolute;
  4104. right: calc(50% - 15px);
  4105. top: calc(50% - 15px);
  4106. border: 1px solid #00000099;
  4107. display: inline-block;
  4108. width: 30px;
  4109. height: 30px;
  4110. box-sizing: border-box;
  4111. border-radius: 50%;
  4112. background: white;
  4113. opacity: 0;
  4114. transition: opacity .5s ease;
  4115. pointer-events: none;
  4116. }
  4117. #pagetual-sideController.minSize #pagetual-sideController-pagenum {
  4118. opacity: 0.8;
  4119. }
  4120. #pagetual-sideController:hover {
  4121. opacity: 1;
  4122. }
  4123. #pagetual-sideController>.extra {
  4124. bottom: 170px;
  4125. left: 0px;
  4126. width: 40px;
  4127. position: absolute;
  4128. }
  4129. #pagetual-sideController>.extra>svg {
  4130. width: 40px;
  4131. height: 30px;
  4132. opacity: 0.1;
  4133. cursor: pointer;
  4134. margin: 0 0 5px 0;
  4135. transition: opacity .3s ease;
  4136. }
  4137. #pagetual-sideController.minSize>.extra>svg {
  4138. opacity: 0;
  4139. }
  4140. #pagetual-sideController>.extra>svg:hover {
  4141. opacity: 1;
  4142. }
  4143. #pagetual-sideController.minSize {
  4144. box-shadow: rgb(0 0 0 / 0%) 0px 0px 0px;
  4145. background: #00000000!important;
  4146. pointer-events: none;
  4147. }
  4148. #pagetual-sideController.minSize #pagetual-sideController-move {
  4149. pointer-events: all;
  4150. }
  4151. #pagetual-sideController.minSize .pagetual-sideController-btn {
  4152. opacity: 0;
  4153. }
  4154. `;
  4155. let frame = document.createElement("div");
  4156. frame.id = "pagetual-sideController";
  4157. frame.innerHTML = createHTML(`
  4158. <div class="extra">
  4159. <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>
  4160. <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>
  4161. </div>
  4162. <div id="pagetual-sideController-top" class="pagetual-sideController-btn">⊼</div>
  4163. <div>
  4164. <div id="pagetual-sideController-pre" class="pagetual-sideController-btn">∧</div>
  4165. <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>
  4166. <div id="pagetual-sideController-next" class="pagetual-sideController-btn">∨</div>
  4167. </div>
  4168. <div id="pagetual-sideController-bottom" class="pagetual-sideController-btn">⊻</div>
  4169. `);
  4170. frame.classList.add("stop");
  4171. let top = frame.querySelector("#pagetual-sideController-top");
  4172. let pre = frame.querySelector("#pagetual-sideController-pre");
  4173. let move = frame.querySelector("#pagetual-sideController-move");
  4174. let next = frame.querySelector("#pagetual-sideController-next");
  4175. let bottom = frame.querySelector("#pagetual-sideController-bottom");
  4176. let pagenum = frame.querySelector("#pagetual-sideController-pagenum");
  4177. let scroll = frame.querySelector("#scroll");
  4178. let loadNow = frame.querySelector("#loadNow");
  4179. if (rulesData.sideControllerScroll === false) {
  4180. scroll.style.display = "none";
  4181. }
  4182. if (rulesData.sideControllerLoadNow === false) {
  4183. loadNow.style.display = "none";
  4184. }
  4185. if (sideControllerIcon) move.innerHTML = sideControllerIcon;
  4186.  
  4187. frame.addEventListener("dblclick", e => {
  4188. e.preventDefault();
  4189. e.stopPropagation();
  4190. });
  4191.  
  4192. frame.addEventListener("mouseenter", e => {
  4193. clearTimeout(self.hideTimer);
  4194. frame.classList.remove("minSize");
  4195. });
  4196.  
  4197. frame.addEventListener("mouseleave", e => {
  4198. clearTimeout(self.hideTimer);
  4199. self.hideTimer = setTimeout(() => {
  4200. frame.classList.add("minSize");
  4201. }, 800);
  4202. });
  4203.  
  4204. document.body.addEventListener('touchstart', e => {
  4205. if (e.target === frame || frame.contains(e.target)) {
  4206. frame.classList.remove("minSize");
  4207. } else {
  4208. frame.classList.add("minSize");
  4209. }
  4210. });
  4211.  
  4212. scroll.addEventListener("click", e => {
  4213. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  4214. autoScroll = parseInt(autoScroll) || 0;
  4215. if (autoScroll < 0) autoScroll = 0;
  4216. if (autoScroll && autoScroll != autoScrollRate) {
  4217. autoScrollRate = autoScroll;
  4218. storage.setItem("autoScrollRate", autoScrollRate);
  4219. }
  4220. setListData("autoScroll", location.host + location.pathname, autoScroll);
  4221. startAutoScroll();
  4222. }, true);
  4223.  
  4224. loadNow.addEventListener("click", e => {
  4225. if (autoLoadNum != -1) {
  4226. autoLoadNum = -1;
  4227. return;
  4228. }
  4229. let loadNum = window.prompt(i18n("loadConfirm"), loadNowNum);
  4230. if (loadNum === "" || loadNum === null) return;
  4231. loadNum = Math.abs(parseInt(loadNum)) || 0;
  4232. if (loadNowNum != loadNum) {
  4233. loadNowNum = loadNum;
  4234. storage.setItem("loadNowNum", loadNowNum);
  4235. }
  4236. autoLoadNum = loadNum;
  4237. nextPage();
  4238. }, true);
  4239.  
  4240. pre.addEventListener("click", e => {
  4241. let prePageBar = getPageBar().preBar;
  4242. if (prePageBar) {
  4243. scrollToPageBar(prePageBar);
  4244. } else {
  4245. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  4246. targetY = scrollTop - (window.innerHeight || document.documentElement.clientHeight);
  4247. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4248. }
  4249. }, true);
  4250.  
  4251. next.addEventListener("click", e => {
  4252. let pageBarObj = getPageBar();
  4253. let nextPageBar = pageBarObj.nextBar;
  4254. if (nextPageBar) {
  4255. scrollToPageBar(nextPageBar);
  4256. } else {
  4257. if (pageBarObj.preBar) {
  4258. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  4259. targetY = scrollH || 9999999;
  4260. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4261. } else {
  4262. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  4263. targetY = scrollTop + (window.innerHeight || document.documentElement.clientHeight);
  4264. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4265. }
  4266. }
  4267. }, true);
  4268.  
  4269. top.addEventListener("click", e => {
  4270. getBody(document).scrollTop=0;
  4271. document.documentElement.scrollTop=0;
  4272. e.preventDefault();
  4273. e.stopPropagation();
  4274. }, true);
  4275.  
  4276. bottom.addEventListener("click", e => {
  4277. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  4278. changeStop(true, true);
  4279. }
  4280. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  4281. getBody(document).scrollTop = scrollH || 9999999;
  4282. document.documentElement.scrollTop = scrollH || 9999999;
  4283. e.preventDefault();
  4284. e.stopPropagation();
  4285. }, true);
  4286.  
  4287. let initX, initY, moving = false;
  4288. let removeTimer;
  4289. move.addEventListener("click", e => {
  4290. if (!moving) {
  4291. changeStop(!isPause, true);
  4292. }
  4293. }, true);
  4294. move.addEventListener("dblclick", e => {
  4295. clearTimeout(removeTimer);
  4296. document.removeEventListener("mousemove", mouseMoveHandler, true);
  4297. document.removeEventListener("mouseup", mouseUpHandler, true);
  4298. changeStop(!isPause, true);
  4299. if (isPause) {
  4300. ruleParser.hideAddedElements();
  4301. } else {
  4302. ruleParser.showAddedElements();
  4303. }
  4304. }, true);
  4305.  
  4306. move.oncontextmenu = e => {
  4307. e.preventDefault();
  4308. picker.start();
  4309. };
  4310.  
  4311. let clientX = e => {
  4312. if (e.type.indexOf('mouse') === 0) {
  4313. return e.clientX;
  4314. } else {
  4315. return e.changedTouches[0].clientX;
  4316. }
  4317. };
  4318.  
  4319. let clientY = e => {
  4320. if (e.type.indexOf('mouse') === 0) {
  4321. return e.clientY;
  4322. } else {
  4323. return e.changedTouches[0].clientY;
  4324. }
  4325. };
  4326.  
  4327. let mouseMoveHandler = e => {
  4328. if (moving) {
  4329. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  4330. let windowWidth = window.innerWidth || document.documentElement.clientWidth;
  4331. initX = (clientX(e) - 10 + 40) / windowWidth * 100;
  4332. initY = (clientY(e) - 83 + 83) / windowHeight * 100;
  4333. this.frame.style.top = `calc(${initY}% - 83px)`;
  4334. this.frame.style.left = `calc(${initX}% - 40px)`;
  4335. } else if (Math.abs(clientX(e) - initX) + Math.abs(clientY(e) - initY) > 20) {
  4336. moving = true;
  4337. clearTimeout(removeTimer);
  4338. }
  4339. };
  4340. let mouseUpHandler = e => {
  4341. clearTimeout(removeTimer);
  4342. document.removeEventListener("mousemove", mouseMoveHandler, true);
  4343. document.removeEventListener("mouseup", mouseUpHandler, true);
  4344. document.removeEventListener("touchmove", mouseMoveHandler, true);
  4345. document.removeEventListener("touchend", mouseUpHandler, true);
  4346. if (moving) {
  4347. rulesData.sideControllerPos = {x: parseInt(initX), y: parseInt(initY)};
  4348. storage.setItem("rulesData", rulesData);
  4349. }
  4350. };
  4351. let mouseDownHandler = e => {
  4352. initX = clientX(e);
  4353. initY = clientY(e);
  4354. moving = false;
  4355. clearTimeout(removeTimer);
  4356. removeTimer = setTimeout(() => {
  4357. if (e.type === "touchstart") {
  4358. picker.start();
  4359. } else {
  4360. self.remove();
  4361. }
  4362. }, 1500);
  4363. document.addEventListener("mousemove", mouseMoveHandler, true);
  4364. document.addEventListener("mouseup", mouseUpHandler, true);
  4365. document.addEventListener("touchmove", mouseMoveHandler, true);
  4366. document.addEventListener("touchend", mouseUpHandler, true);
  4367. e.stopPropagation();
  4368. e.preventDefault();
  4369. };
  4370.  
  4371. move.addEventListener("mousedown", mouseDownHandler, true);
  4372. move.addEventListener("touchstart", mouseDownHandler, { passive: false, capture: true });
  4373.  
  4374. this.frame = frame;
  4375. this.pagenum = pagenum;
  4376. if (rulesData.sideControllerPos) {
  4377. this.frame.style.top = `calc(${rulesData.sideControllerPos.y}% - 83px)`;
  4378. this.frame.style.left = `calc(${rulesData.sideControllerPos.x}% - 40px)`;
  4379. }
  4380. }
  4381.  
  4382. addToStage() {
  4383. this.init();
  4384. if (!this.styleEle || !this.styleEle.parentNode) {
  4385. this.styleEle = _GM_addStyle(this.cssText);
  4386. }
  4387. if (!isPause) {
  4388. this.frame.classList.remove("stop");
  4389. }
  4390. this.pagenum.innerHTML = createHTML(curPage);
  4391. this.frame.title = i18n("page") + curPage;
  4392. if (this.frame.parentNode) return;
  4393. getBody(document).appendChild(this.frame);
  4394. clearTimeout(this.hideTimer);
  4395. this.frame.classList.add("minSize");
  4396. }
  4397.  
  4398. remove() {
  4399. if (this.frame && this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  4400. }
  4401. }
  4402. const sideController = new SideController();
  4403.  
  4404. class NextSwitch {
  4405. //static nextSwitch;
  4406. constructor() {
  4407. this.inited = false;
  4408. }
  4409.  
  4410. /*static getInstance() {
  4411. if (!NextSwitch.nextSwitch) {
  4412. NextSwitch.nextSwitch = new NextSwitch();
  4413. }
  4414. return NextSwitch.nextSwitch;
  4415. }*/
  4416.  
  4417. init() {
  4418. if (this.inited) return;
  4419. this.inited = true;
  4420. let self = this;
  4421. this.cssText = `
  4422. #pagetual-nextSwitch {
  4423. position: fixed;
  4424. top: 10px;
  4425. left: calc(50% - 160px);
  4426. background: aliceblue;
  4427. padding: 10px;
  4428. border-radius: 5px;
  4429. text-align: center;
  4430. opacity: 0.95;
  4431. color: #161616;
  4432. z-index: 2147483647;
  4433. font-size: 16px;
  4434. box-shadow: rgb(0 0 0) 0px 0px 10px;
  4435. }
  4436. #pagetual-nextSwitch>.title {
  4437. margin: -5px 45px 10px 45px;
  4438. font-size: 20px;
  4439. font-weight: bold;
  4440. border-bottom: 1px solid black;
  4441. user-select: none;
  4442. color: orangered;
  4443. }
  4444. #pagetual-nextSwitch>.group {
  4445. display: flex;
  4446. flex-direction: column;
  4447. }
  4448. #pagetual-nextSwitch>.group>span {
  4449. color: #161616;
  4450. cursor: pointer;
  4451. margin: 3px;
  4452. font-size: larger;
  4453. }
  4454. #pagetual-nextSwitch>.group>span:hover {
  4455. color: red;
  4456. }
  4457. #pagetual-nextSwitch>.group>span.current {
  4458. border: 2px dotted red;
  4459. border-radius: 10px;
  4460. }
  4461. #pagetual-nextSwitch>.closeSwitch {
  4462. position: absolute;
  4463. top: 3px;
  4464. right: 10px;
  4465. background: none;
  4466. border: none;
  4467. vertical-align: top;
  4468. transition: transform .15s ease-in-out;
  4469. float: right;
  4470. cursor: pointer;
  4471. }
  4472. #pagetual-nextSwitch svg {
  4473. width: 30px;
  4474. height: 30px;
  4475. vertical-align: middle;
  4476. fill: #161616;
  4477. overflow: hidden;
  4478. }
  4479. #pagetual-nextSwitch button:hover {
  4480. transform: scale(1.2);
  4481. }
  4482. `;
  4483. let frame = document.createElement("div");
  4484. frame.id = "pagetual-nextSwitch";
  4485. frame.innerHTML = createHTML(`
  4486. <div class="title">${i18n("nextSwitch")}</div>
  4487. <button type="button" class="closeSwitch">
  4488. <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2754">
  4489. <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">
  4490. </path>
  4491. </svg>
  4492. </button>
  4493. <div class="group"></div>
  4494. `);
  4495. let group = frame.querySelector(".group");
  4496. let closeBtn = frame.querySelector(".closeSwitch");
  4497. closeBtn.addEventListener("click", e => {
  4498. self.close();
  4499. }, true);
  4500. this.frame = frame;
  4501. let currentSpan;
  4502. ruleParser.curSiteRule.nextLink.forEach((link, i) => {
  4503. let span = document.createElement("span");
  4504. let target = getElement(link, document);
  4505. let index = "<b>" + (i + 1) + "</b>: ";
  4506. if (target) {
  4507. let targetInner = target.innerText.trim();
  4508. span.innerHTML = index + (targetInner || link);
  4509. } else {
  4510. span.innerHTML = index + "Not Found";
  4511. }
  4512. span.title = link;
  4513. span.addEventListener("click", e => {
  4514. if (currentSpan) currentSpan.classList.remove("current");
  4515. span.classList.add("current");
  4516. currentSpan = span;
  4517. nextIndex = i;
  4518. setListData("nextSwitch", location.host, nextIndex === 0 ? "" : nextIndex);
  4519. ruleParser.curUrl += "#pagetual";
  4520. ruleParser.oldUrl = ruleParser.curUrl;
  4521. autoLoadNum = -1;
  4522. if (!ruleParser.nextLinkHref) {
  4523. isLoading = false;
  4524. }
  4525. ruleParser.getNextLink(ruleParser.pageDoc || document);
  4526. self.close();
  4527. }, true);
  4528. if (i == nextIndex) {
  4529. span.classList.add("current");
  4530. currentSpan = span;
  4531. }
  4532. group.appendChild(span);
  4533. });
  4534. }
  4535.  
  4536. start() {
  4537. this.init();
  4538. if (!this.styleEle || !this.styleEle.parentNode) {
  4539. this.styleEle = _GM_addStyle(this.cssText);
  4540. }
  4541. document.documentElement.appendChild(this.frame);
  4542. }
  4543.  
  4544. close() {
  4545. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  4546. }
  4547. }
  4548. const nextSwitch = new NextSwitch();
  4549.  
  4550. class Picker {
  4551. //static picker;
  4552. constructor() {
  4553. this.inited = false;
  4554. }
  4555.  
  4556. /*static getInstance() {
  4557. if (!Picker.picker) {
  4558. Picker.picker = new Picker();
  4559. }
  4560. return Picker.picker;
  4561. }*/
  4562.  
  4563. init() {
  4564. if (this.inited) return;
  4565. this.inited = true;
  4566. let self = this;
  4567. this.signList = [];
  4568. this.cssText = `
  4569. body.pagetual-picker,
  4570. body.pagetual-picker *:hover,
  4571. body.pagetual-picker a:hover {
  4572. cursor: crosshair !important;
  4573. }
  4574. #pagetual-picker {
  4575. position: fixed;
  4576. top: 10px;
  4577. left: calc(50% - 178px);
  4578. background: aliceblue;
  4579. padding: 10px;
  4580. border-radius: 5px;
  4581. text-align: center;
  4582. opacity: 0.95;
  4583. color: #161616;
  4584. z-index: 2147483646;
  4585. font-size: 16px;
  4586. overflow: hidden;
  4587. box-shadow: rgb(0 0 0) 0px 0px 10px;
  4588. }
  4589. #pagetual-picker * {
  4590. margin: 0;
  4591. padding: 0;
  4592. font-family: Times New Roman;
  4593. overflow: initial;
  4594. user-select: none;
  4595. line-height: unset;
  4596. min-width: unset;
  4597. min-height: unset;
  4598. }
  4599. #pagetual-picker>.title {
  4600. margin: -5px 45px 10px 45px;
  4601. font-size: 20px;
  4602. font-weight: bold;
  4603. cursor: pointer;
  4604. border-bottom: 1px solid black;
  4605. user-select: none;
  4606. color: orangered;
  4607. height: initial;
  4608. width: initial;
  4609. position: initial;
  4610. transition: transform .3s ease;
  4611. }
  4612. #pagetual-picker>.title:hover {
  4613. transform: scale(1.1);
  4614. }
  4615. #pagetual-picker button {
  4616. background: none;
  4617. border: none;
  4618. vertical-align: top;
  4619. transition: transform .15s ease-in-out;
  4620. float: right;
  4621. cursor: pointer;
  4622. overflow: hidden;
  4623. background-color: unset!important;
  4624. }
  4625. #pagetual-picker button:hover {
  4626. transform: scale(1.2);
  4627. }
  4628. #pagetual-picker>.closePicker {
  4629. position: absolute;
  4630. top: 3px;
  4631. right: 10px;
  4632. }
  4633. #pagetual-picker>.logoIcon {
  4634. position: absolute;
  4635. top: 3px;
  4636. left: 10px;
  4637. }
  4638. #pagetual-picker>.logoIcon.showSign>svg>path {
  4639. fill: gray!important;
  4640. }
  4641. #pagetual-picker textarea{
  4642. display: inline-block;
  4643. width: calc(100% - 65px);
  4644. height: 20px;
  4645. min-width: 250px;
  4646. max-width: calc(65vw - 50px);
  4647. min-height: unset;
  4648. max-height: unset;
  4649. padding: 6px 12px;
  4650. font-size: 16px;
  4651. font-weight: 400;
  4652. line-height: 1.5;
  4653. color: #495057;
  4654. background-color: #fff;
  4655. background-clip: padding-box;
  4656. border: 1px solid #ced4da;
  4657. border-radius: 4px;
  4658. transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
  4659. box-sizing: content-box;
  4660. margin-right: 5px;
  4661. resize: both;
  4662. box-shadow: 0 1px 5px 1px #ddd;
  4663. overflow-wrap: anywhere;
  4664. }
  4665. #pagetual-picker textarea:focus {
  4666. color: black;
  4667. background-color: #fff;
  4668. border-color: #80bdff;
  4669. outline: 0;
  4670. box-shadow: 0 0 0 3.2px rgb(0 123 255 / 25%);
  4671. }
  4672. #pagetual-picker [type=checkbox],
  4673. #pagetual-picker [type=radio] {
  4674. line-height: 20px;
  4675. height: 25px;
  4676. width: 25px;
  4677. margin-left: 5px;
  4678. vertical-align: middle;
  4679. appearance: auto;
  4680. display: inline-block;
  4681. position: initial;
  4682. }
  4683. #pagetual-picker [type=checkbox]:after,
  4684. #pagetual-picker [type=radio]:after,
  4685. #pagetual-picker [type=checkbox]:before,
  4686. #pagetual-picker [type=radio]:before {
  4687. border: none;
  4688. background: none;
  4689. }
  4690. #pagetual-picker label {
  4691. font-size: 18px;
  4692. line-height: 25px;
  4693. vertical-align: middle;
  4694. display: inline-block;
  4695. color: black;
  4696. position: initial;
  4697. cursor: pointer;
  4698. }
  4699. #pagetual-picker .bottom {
  4700. text-align: left;
  4701. margin: 10px 0;
  4702. width: 100%;
  4703. }
  4704. #pagetual-picker .bottom>button {
  4705. float: right;
  4706. }
  4707. #pagetual-picker svg {
  4708. width: 30px;
  4709. height: 30px;
  4710. vertical-align: middle;
  4711. fill: #161616;
  4712. overflow: hidden;
  4713. }
  4714. #pagetual-picker svg * {
  4715. pointer-events: none;
  4716. }
  4717. #pagetual-picker .allpath {
  4718. font-size: 18px;
  4719. margin: 10px auto;
  4720. max-width: 330px;
  4721. word-break: break-all;
  4722. cursor: context-menu;
  4723. overflow: hidden;
  4724. max-height: 42px;
  4725. -moz-transition:max-height 1s ease-in;
  4726. -webkit-transition:max-height 1s ease-in;
  4727. transition:max-height 1s ease-in;
  4728. color: black;
  4729. }
  4730. #pagetual-picker .allpath:hover {
  4731. max-height: calc(100vh - 130px);
  4732. overflow: auto;
  4733. }
  4734. #pagetual-picker .allpath>span.path {
  4735. cursor: pointer;
  4736. }
  4737. #pagetual-picker .allpath>span.path:hover {
  4738. opacity: 0.6;
  4739. }
  4740. #pagetual-picker .allpath>span.path:hover,
  4741. #pagetual-picker .allpath>span.path.checked {
  4742. color: orangered;
  4743. }
  4744. #pagetual-picker .moreConfig {
  4745. display: flex;
  4746. justify-content: space-between;
  4747. border-top: 1px solid;
  4748. padding-top: 10px;
  4749. width: 100%;
  4750. }
  4751. #pagetual-picker .command {
  4752. width: 100%;
  4753. color: black!important;
  4754. text-align: center;
  4755. font-size: large;
  4756. margin-top: 10px;
  4757. box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.12);
  4758. border-radius: 5px;
  4759. }
  4760. #pagetual-picker .command:hover {
  4761. color: orangered;
  4762. }
  4763. #pagetual-picker #showDetail {
  4764. float: initial;
  4765. margin-top: 10px;
  4766. }
  4767. #pagetual-picker.showDetail #showDetail {
  4768. float: right;
  4769. }
  4770. #pagetual-picker #showDetail>svg {
  4771. -moz-transition:transform 0.3s ease;
  4772. -webkit-transition:transform 0.3s ease;
  4773. transition:transform 0.3 ease;
  4774. }
  4775. #pagetual-picker.showDetail #showDetail>svg {
  4776. transform: rotate(180deg);
  4777. }
  4778. #pagetual-picker .tempRule {
  4779. display: none;
  4780. margin-top: 10px;
  4781. height: 300px;
  4782. min-height: 150px;
  4783. }
  4784. #pagetual-picker.showDetail .tempRule {
  4785. display: inline-block;
  4786. word-break: break-all;
  4787. }
  4788. #pagetual-picker #saveDetail {
  4789. display: none;
  4790. position: absolute;
  4791. bottom: 10px;
  4792. right: 8px;
  4793. }
  4794. #pagetual-picker.showDetail #saveDetail {
  4795. display: inline-block;
  4796. }
  4797. #pagetual-picker #saveDetail svg {
  4798. width: 35px;
  4799. height: 35px;
  4800. }
  4801. #pagetual-picker .addProp {
  4802. display: none;
  4803. flex-direction: column;
  4804. position: absolute;
  4805. bottom: 45px;
  4806. right: 12px;
  4807. }
  4808. #pagetual-picker.showDetail .addProp {
  4809. display: flex;
  4810. }
  4811. #pagetual-picker .addProp>button {
  4812. font-size: 30px;
  4813. font-family: Arial,sans-serif;
  4814. line-height: 35px;
  4815. color: #161616;
  4816. }
  4817. #pagetual-picker #edit{
  4818. -webkit-animation: jumpAnimation .6s 5;
  4819. animation: jumpAnimation .6s 5;
  4820. }
  4821. @keyframes jumpAnimation {
  4822. 0% {
  4823. transform: scale(1) translateY(0);
  4824. animation-timing-function: ease-out;
  4825. }
  4826. 50% {
  4827. transform: scale(1.2) translateY(-5px);
  4828. animation-timing-function: ease-in;
  4829. }
  4830. 100% {
  4831. transform: scale(1) translateY(0);
  4832. animation-timing-function: ease-out;
  4833. }
  4834. }
  4835. @-webkit-keyframes jumpAnimation {
  4836. 0% {
  4837. -webkit-transform: scale(1) translateY(0);
  4838. animation-timing-function: ease-out;
  4839. }
  4840. 50% {
  4841. -webkit-transform: scale(1.2) translateY(-5px);
  4842. animation-timing-function: ease-in;
  4843. }
  4844. 100% {
  4845. -webkit-transform: scale(1) translateY(0);
  4846. animation-timing-function: ease-out;
  4847. }
  4848. }
  4849. `;
  4850. this.mainSignDiv = this.createSignDiv();
  4851. this.allSignDiv = [];
  4852. let frame = document.createElement("div");
  4853. frame.id = "pagetual-picker";
  4854. frame.innerHTML = createHTML(`
  4855. <button title="Pagetual" type="button" class="logoIcon">
  4856. <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>
  4857. </button>
  4858. <div class="title" title="${i18n("configure")}">${i18n("picker")}</div>
  4859. <button title="${i18n("closePicker")}" type="button" class="closePicker">
  4860. <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>
  4861. </button>
  4862. <div class="allpath" title="${i18n("switchSelector")}"></div>
  4863. <div>
  4864. <textarea class="selector" spellcheck="false" name="selector" placeholder="${i18n("pickerPlaceholder")}"></textarea>
  4865. <button id="check" title="${i18n("pickerCheck")}" type="button">
  4866. <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>
  4867. </button>
  4868. </div>
  4869. <div class="bottom">
  4870. <input name="xpath" id="checkbox_id" type="checkbox" />
  4871. <label for="checkbox_id">XPath</label>
  4872. <button id="edit" title="${i18n("gotoEdit")}" type="button">
  4873. <svg viewBox="0 0 1024 1024" style="color: orangered;fill: orangered;" version="1.1" xmlns="http://www.w3.org/2000/svg">
  4874. <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">
  4875. </path>
  4876. </svg>
  4877. </button>
  4878. </div>
  4879. <div class="moreConfig">
  4880. <div title="${i18n('forceStateIframe')}">
  4881. <input name="forceState" id="forceStateIframe" type="radio" />
  4882. <label for="forceStateIframe">${i18n('iframe')}</label>
  4883. </div>
  4884. <div title="${i18n('forceStateDynamic')}">
  4885. <input name="forceState" id="forceStateDynamic" type="radio" />
  4886. <label for="forceStateDynamic">${i18n('dynamic')}</label>
  4887. </div>
  4888. <div title="${i18n('forceStateDisable')}">
  4889. <input name="forceState" id="forceStateDisable" type="radio" />
  4890. <label for="forceStateDisable">${i18n('disable')}</label>
  4891. </div>
  4892. </div>
  4893. <button id="nextSwitch" class="command" title="${i18n("nextSwitch")}" type="button">${i18n("nextSwitch")}</button>
  4894. <button id="loadNow" class="command" title="${i18n("loadNow")}" type="button">${i18n("loadNow")}</button>
  4895. <button id="autoScroll" class="command" title="${i18n("toggleAutoScroll")}" type="button"></button>
  4896. <button id="ruleRequest" class="command" title="${i18n("ruleRequest")}" type="button">${i18n("ruleRequest")}</button>
  4897. <div>
  4898. <textarea class="tempRule" spellcheck="false" placeholder="{Rule object}" title="Rule for current site"></textarea>
  4899. <button id="showDetail" title="" type="button">
  4900. <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>
  4901. </button>
  4902. <div class="addProp">
  4903. <button id="addOtherProp" title="${i18n("addOtherProp")}" type="button">+</button>
  4904. <button id="addNextSelector" title="${i18n("addNextSelector")}" type="button">></button>
  4905. <button id="addPageSelector" title="${i18n("addPageSelector")}" type="button">❏</button>
  4906. </div>
  4907. <button id="saveDetail" title="${i18n("save")}" type="button">
  4908. <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>
  4909. </button>
  4910. </div>
  4911. `);
  4912. let forceStateIframe = frame.querySelector("#forceStateIframe");//forceState 1 禁用 2 强嵌 3 动态
  4913. let forceStateDynamic = frame.querySelector("#forceStateDynamic");
  4914. let forceStateDisable = frame.querySelector("#forceStateDisable");
  4915. let clickRadio = e => {
  4916. let radio = e.currentTarget.querySelector('input');
  4917. if (radio.checked) {
  4918. forceState = "";
  4919. } else {
  4920. switch (radio.id) {
  4921. case "forceStateIframe":
  4922. forceState = 2;
  4923. break;
  4924. case "forceStateDynamic":
  4925. forceState = 3;
  4926. break;
  4927. case "forceStateDisable":
  4928. forceState = 1;
  4929. break;
  4930. default:
  4931. return;
  4932. }
  4933. }
  4934. setListData("forceState", location.host, forceState);
  4935. self.close();
  4936. setTimeout(() => {
  4937. location.reload();
  4938. }, 500);
  4939. };
  4940. forceStateIframe.parentNode.addEventListener("mousedown", clickRadio);
  4941. forceStateDynamic.parentNode.addEventListener("mousedown", clickRadio);
  4942. forceStateDisable.parentNode.addEventListener("mousedown", clickRadio);
  4943. if (forceState == 1) forceStateDisable.checked = true;
  4944. else if (forceState == 2) forceStateIframe.checked = true;
  4945. else if (forceState == 3) forceStateDynamic.checked = true;
  4946. let closeBtn = frame.querySelector(".closePicker");
  4947. let logoBtn = frame.querySelector(".logoIcon");
  4948. let title = frame.querySelector(".title");
  4949. let allpath = frame.querySelector(".allpath");
  4950. let selectorInput = frame.querySelector(".selector");
  4951. let xpath = frame.querySelector("#checkbox_id");
  4952. let checkBtn = frame.querySelector("#check");
  4953. let editBtn = frame.querySelector("#edit");
  4954. let nextSwitchBtn = frame.querySelector("#nextSwitch");
  4955. let autoScrollBtn = frame.querySelector("#autoScroll");
  4956. let loadNow = frame.querySelector("#loadNow");
  4957. let tempRule = frame.querySelector(".tempRule");
  4958. let showDetailBtn = frame.querySelector("#showDetail");
  4959. let saveDetailBtn = frame.querySelector("#saveDetail");
  4960. let addOtherProp = frame.querySelector("#addOtherProp");
  4961. let addNextSelector = frame.querySelector("#addNextSelector");
  4962. let addPageSelector = frame.querySelector("#addPageSelector");
  4963. let ruleRequestBtn = frame.querySelector("#ruleRequest");
  4964. ruleRequestBtn.addEventListener("click", e => {
  4965. _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});
  4966. }, true);
  4967. autoScrollBtn.addEventListener("click", e => {
  4968. self.close();
  4969. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  4970. autoScroll = parseInt(autoScroll) || 0;
  4971. if (autoScroll < 0) autoScroll = 0;
  4972. if (autoScroll && autoScroll != autoScrollRate) {
  4973. autoScrollRate = autoScroll;
  4974. storage.setItem("autoScrollRate", autoScrollRate);
  4975. }
  4976. setListData("autoScroll", location.host + location.pathname, autoScroll);
  4977. startAutoScroll();
  4978. }, true);
  4979. addOtherProp.addEventListener("click", e => {
  4980. let propName = prompt(i18n("propName"), "author");
  4981. if (!propName) return;
  4982. let propValue = prompt(i18n("propValue"));
  4983. if (!propValue) return;
  4984. if (propValue === "true") propValue = true;
  4985. else if (propValue === "false") propValue = false;
  4986. else if (/^\d+$/.test(propValue)) propValue = parseInt(propValue);
  4987. if (propName === "author" && propValue) {
  4988. author = propValue;
  4989. storage.setItem("author", propValue);
  4990. }
  4991. let editTemp = self.getTempRule();
  4992. if (!editTemp) return;
  4993. editTemp[propName] = propValue;
  4994. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  4995. }, true);
  4996. addNextSelector.addEventListener("click", e => {
  4997. let editTemp = self.getTempRule();
  4998. if (!editTemp) return;
  4999. let selector = self.selectorInput.value;
  5000. if (selector) {
  5001. editTemp.nextLink = selector;
  5002. }
  5003. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  5004. }, true);
  5005. addPageSelector.addEventListener("click", e => {
  5006. let editTemp = self.getTempRule();
  5007. if (!editTemp) return;
  5008. let selector = self.selectorInput.value;
  5009. if (selector) {
  5010. editTemp.pageElement = selector;
  5011. }
  5012. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  5013. }, true);
  5014. showDetailBtn.addEventListener("click", e => {
  5015. frame.classList.toggle("showDetail");
  5016. }, true);
  5017. saveDetailBtn.addEventListener("click", e => {
  5018. let editTemp = self.getTempRule(true);
  5019. if (tempRule.value && !editTemp) {
  5020. return;
  5021. }
  5022. if(!ruleParser.customRules) {
  5023. ruleParser.customRules = [];
  5024. }
  5025. ruleParser.customRules = ruleParser.customRules.filter(item => {return item.url != editTemp.url || item.name != editTemp.name});
  5026. if (tempRule.value) {
  5027. ruleParser.customRules.unshift(editTemp);
  5028. ruleParser.curSiteRule = editTemp;
  5029. } else {
  5030. ruleParser.curSiteRule = {};
  5031. isPause = true;
  5032. }
  5033. storage.setItem("customRules", ruleParser.customRules);
  5034. if (ruleParser.hpRules && ruleParser.curSiteRule && !ruleParser.curSiteRule.smart) {
  5035. ruleParser.addToHpRules(true);
  5036. }
  5037. if (window.confirm(i18n("reloadPage"))) {
  5038. setTimeout(() => {location.reload()}, 100);
  5039. }
  5040. }, true);
  5041. nextSwitchBtn.addEventListener("click", e => {
  5042. self.close();
  5043. nextSwitch.start();
  5044. }, true);
  5045. loadNow.addEventListener("click", e => {
  5046. self.close();
  5047. let loadNum = window.prompt(i18n("loadConfirm"), "1");
  5048. if (loadNum === "" || loadNum === null) return;
  5049. autoLoadNum = Math.abs(parseInt(loadNum));
  5050. nextPage();
  5051. }, true);
  5052. closeBtn.addEventListener("click", e => {
  5053. self.close();
  5054. }, true);
  5055. this.showSign = true;
  5056. logoBtn.addEventListener("click", e => {
  5057. logoBtn.classList.toggle("showSign");
  5058. self.showSign = !self.showSign;
  5059. getBody(document).classList.toggle("pagetual-picker");
  5060. }, true);
  5061. let moving = false;
  5062. let initX = 0, initY = 0, initPos = {x: 0, y: 0};
  5063. let moveHanlder = e => {
  5064. if (moving) {
  5065. frame.style.left = e.clientX - initX + "px";
  5066. frame.style.top = e.clientY - initY + "px";
  5067. e.stopPropagation();
  5068. e.preventDefault();
  5069. } else if(Math.abs(e.clientX - initPos.x) + Math.abs(e.clientY - initPos.y) > 20) {
  5070. moving = true;
  5071. }
  5072. };
  5073. let upHanlder = e => {
  5074. if (moving) {
  5075. moving = false;
  5076. } else {
  5077. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  5078. }
  5079. document.removeEventListener("mousemove", moveHanlder, true);
  5080. title.removeEventListener("mouseup", upHanlder, true);
  5081. e.stopPropagation();
  5082. e.preventDefault();
  5083. };
  5084. title.addEventListener("mousedown", e => {
  5085. initPos = {x: e.clientX, y: e.clientY};
  5086. initX = e.clientX - parseInt(getComputedStyle(frame).left);
  5087. initY = e.clientY - parseInt(getComputedStyle(frame).top);
  5088. document.addEventListener("mousemove", moveHanlder, true);
  5089. title.addEventListener("mouseup", upHanlder, true);
  5090. });
  5091. frame.addEventListener("mouseenter", e => {
  5092. if (!self.showSign || moving) return;
  5093. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  5094. self.checkInputSelector(false);
  5095. });
  5096. frame.addEventListener("mouseleave", e => {
  5097. if (!self.showSign) {
  5098. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  5099. self.clearSigns();
  5100. return;
  5101. }
  5102. if (moving) return;
  5103. document.documentElement.appendChild(self.mainSignDiv);
  5104. self.clearSigns();
  5105. });
  5106. checkBtn.addEventListener("click", e => {
  5107. self.checkInputSelector();
  5108. if (this.selectorInput.value && self.foundEle) {
  5109. debug(self.foundEle);
  5110. self.foundEle[0].scrollIntoView({ behavior: "smooth" });
  5111. _GM_setClipboard(this.selectorInput.value);
  5112. showTips(i18n("copied"));
  5113. } else showTips("Null");
  5114. });
  5115. xpath.addEventListener("click", e => {
  5116. if (!selectorInput.value) {
  5117. self.setSelectorDiv("");
  5118. return;
  5119. }
  5120. let element = getElement(selectorInput.value, document);
  5121. let selector = self.getSelectorFromEle(element);
  5122. selectorInput.value = selector;
  5123. self.setSelectorDiv(selector);
  5124. });
  5125. editBtn.addEventListener("click", e => {
  5126. rulesData.editTemp = self.getTempRule();
  5127. storage.setItem("rulesData", rulesData);
  5128. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  5129. });
  5130. editBtn.oncontextmenu = e => {
  5131. e.preventDefault();
  5132. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  5133. };
  5134. this.frame = frame;
  5135. this.xpath = xpath;
  5136. this.allpath = allpath;
  5137. this.selectorInput = selectorInput;
  5138. this.nextSwitchBtn = nextSwitchBtn;
  5139. this.autoScrollBtn = autoScrollBtn;
  5140. this.loadNow = loadNow;
  5141. this.tempRule = tempRule;
  5142. this.logoBtn = logoBtn;
  5143. let setTitleTimer;
  5144. this.moveHandler = e => {
  5145. if (!self.showSign || e.target === document) return;
  5146. let target = self.getTarget(e.target);
  5147. self.adjustSignDiv(self.mainSignDiv, target);
  5148. clearTimeout(setTitleTimer);
  5149. setTitleTimer = setTimeout(() => {
  5150. if (self.inPicker && target.hasAttributes()) {
  5151. let title = target.nodeName.toLowerCase() + "\n";
  5152. for (const attr of target.attributes) {
  5153. title += `【${attr.name}】${attr.value ? " ➡️ " + attr.value : ""}\n`;
  5154. }
  5155. getBody(document).title = title;
  5156. }
  5157. }, 100);
  5158. };
  5159. this.clickHandler = e => {
  5160. if (!self.showSign) return;
  5161. if (self.inPicker) {
  5162. e.stopPropagation();
  5163. e.preventDefault();
  5164. }
  5165. let target = self.getTarget(e.target);
  5166. let selector = self.getSelectorFromEle(target);
  5167. selectorInput.value = selector;
  5168. self.setSelectorDiv(selector);
  5169. };
  5170. }
  5171.  
  5172. getTempRule(detail) {
  5173. if (this.tempRule.value) {
  5174. try {
  5175. this.editTemp = JSON.parse(this.tempRule.value);
  5176. } catch (e) {
  5177. this.editTemp = null;
  5178. if (detail) {
  5179. let pos = e && e.message && e.message.match(/position (\d+)/);
  5180. if (pos) {
  5181. pos = parseInt(pos[1]);
  5182. this.tempRule.value = this.tempRule.value.slice(0, pos) + "➡️" + this.tempRule.value.slice(pos);
  5183. }
  5184. showTips(i18n("errorJson"));
  5185. return null;
  5186. }
  5187. }
  5188. }
  5189. if (!this.editTemp) {
  5190. if (ruleParser.curSiteRule.url && !ruleParser.curSiteRule.smart) {
  5191. this.editTemp = ruleParser.curSiteRule;
  5192. } else {
  5193. this.editTemp = {
  5194. name: document.title,
  5195. url: "^" + (location.origin + location.pathname).replace(/[^\/]*$/, "").replace(/^https?/, "https?").replace(/\./g, "\\."),
  5196. example: location.href
  5197. };
  5198. if (author) this.editTemp.author = author;
  5199. }
  5200. delete this.editTemp.from;
  5201. delete this.editTemp.type;
  5202. delete this.editTemp.updatedAt;
  5203. }
  5204. if (this.selectorInput.value && (!this.frame.classList.contains("showDetail") || !this.editTemp || !this.editTemp.pageElement)) {
  5205. if (this.foundEle && this.foundEle.length === 1) {
  5206. let foundEleRect = this.foundEle[0].getBoundingClientRect();
  5207. if (foundEleRect.height < 100) {
  5208. showTips("Next Link", "", 500);
  5209. this.editTemp.nextLink = this.selectorInput.value;
  5210. return this.editTemp;
  5211. }
  5212. }
  5213. showTips("Page Element", "", 500);
  5214. this.editTemp.pageElement = this.selectorInput.value;
  5215. }
  5216. return this.editTemp;
  5217. }
  5218.  
  5219. getTarget(ele) {
  5220. while (ele.parentNode && (ele.offsetWidth === 0 || ele.offsetHeight === 0)) {
  5221. ele = ele.parentNode;
  5222. }
  5223. return ele;
  5224. }
  5225.  
  5226. close() {
  5227. this.clearSigns();
  5228. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  5229. if (this.mainSignDiv.parentNode) this.mainSignDiv.parentNode.removeChild(this.mainSignDiv);
  5230. getBody(document).classList.remove("pagetual-picker");
  5231. getBody(document).removeEventListener("mousemove", this.moveHandler, true);
  5232. getBody(document).removeEventListener("click", this.clickHandler, true);
  5233. getBody(document).title = "";
  5234. this.inPicker = false;
  5235. }
  5236.  
  5237. setImportant(ele, prop, value) {
  5238. ele.style.setProperty(prop, value, "important");
  5239. }
  5240.  
  5241. createSignDiv() {
  5242. let signDiv = document.createElement("div");
  5243. this.setImportant(signDiv, "position", "absolute");
  5244. this.setImportant(signDiv, "pointer-events", "none");
  5245. this.setImportant(signDiv, "z-index", "2147483645");
  5246. this.setImportant(signDiv, "background", "rgba(120, 170, 210, 0.6)");
  5247. this.setImportant(signDiv, "transition", "all 0.15s ease-out");
  5248. this.setImportant(signDiv, "box-shadow", "rgb(0 0 0) 0px 0px 3px 0px");
  5249. return signDiv;
  5250. }
  5251.  
  5252. adjustSignDiv(div, target) {
  5253. let rect = target.getBoundingClientRect();
  5254. this.setImportant(div, "width", rect.width + "px");
  5255. this.setImportant(div, "height", rect.height + "px");
  5256. this.setImportant(div, "left", rect.left + window.scrollX + "px");
  5257. this.setImportant(div, "top", rect.top + window.scrollY + "px");
  5258. }
  5259.  
  5260. getSelectorFromEle(ele) {
  5261. return this.xpath.checked ? createXPathFromElement(ele) : geneSelector(ele, true);
  5262. }
  5263.  
  5264. fillTempRuleTextarea() {
  5265. if (!this.frame.classList.contains("showDetail") || !this.editTemp || !this.editTemp.pageElement) this.tempRule.value = JSON.stringify(this.getTempRule(), null, 4);
  5266. }
  5267.  
  5268. setSelectorDiv(selector) {
  5269. let self = this;
  5270. this.allpath.innerHTML = createHTML("");
  5271. if (selector) {
  5272. if (this.xpath.checked) {
  5273. let span = document.createElement("span");
  5274. span.innerText = selector;
  5275. span.addEventListener("click", e => {
  5276. self.selectorInput.value = selector;
  5277. self.checkInputSelector();
  5278. }, true);
  5279. this.allpath.appendChild(span);
  5280. } else {
  5281. selector.split(">").forEach((item, index) => self.geneSelectorItem(item, index));
  5282. }
  5283. }
  5284. this.checkInputSelector();
  5285. }
  5286.  
  5287. geneSelectorItem(item, index) {
  5288. let self = this;
  5289. item = item.trim();
  5290. if (!item) return;
  5291. if (index !== 0) {
  5292. let span = document.createElement("span");
  5293. span.innerText = " > ";
  5294. this.allpath.appendChild(span);
  5295. }
  5296. let span = document.createElement("span");
  5297. span.className = "path";
  5298. span.innerText = item;
  5299. span.addEventListener("click", e => {
  5300. let selector = "";
  5301. let target = e.target;
  5302. while (target) {
  5303. selector = target.innerText + selector;
  5304. target = target.previousElementSibling;
  5305. }
  5306. self.selectorInput.value = selector;
  5307. self.checkInputSelector();
  5308. if (self.checkedPath) {
  5309. self.checkedPath.classList.remove("checked");
  5310. }
  5311. span.classList.add("checked");
  5312. self.checkedPath = span;
  5313. }, true);
  5314. this.allpath.appendChild(span);
  5315. }
  5316.  
  5317. checkInputSelector(fill = true) {
  5318. let self = this;
  5319. this.clearSigns();
  5320. if (!this.selectorInput.value) return;
  5321. let eles = getAllElements(this.selectorInput.value, document);
  5322. this.foundEle = null;
  5323. if (eles && eles.length > 0) {
  5324. this.foundEle = eles;
  5325. eles.forEach(ele => {
  5326. let sign = self.createSignDiv();
  5327. document.documentElement.appendChild(sign);
  5328. self.adjustSignDiv(sign, ele);
  5329. self.signList.push(sign);
  5330. });
  5331. if (fill) this.fillTempRuleTextarea();
  5332. }
  5333. }
  5334.  
  5335. clearSigns() {
  5336. this.signList.forEach(sign => {
  5337. if (sign.parentNode) sign.parentNode.removeChild(sign);
  5338. });
  5339. this.signList = [];
  5340. }
  5341.  
  5342. start() {
  5343. this.init();
  5344. if (this.inPicker) return;
  5345. this.inPicker = true;
  5346. if (!this.styleEle || !this.styleEle.parentNode) {
  5347. this.styleEle = _GM_addStyle(this.cssText);
  5348. }
  5349. document.documentElement.appendChild(this.frame);
  5350. document.documentElement.appendChild(this.mainSignDiv);
  5351. getBody(document).classList.add("pagetual-picker");
  5352.  
  5353. this.logoBtn.classList.remove("showSign");
  5354. this.showSign = true;
  5355.  
  5356. getBody(document).addEventListener("mousemove", this.moveHandler, true);
  5357. getBody(document).addEventListener("click", this.clickHandler, true);
  5358. this.xpath.checked = isXPath(ruleParser.curSiteRule.pageElement);
  5359. this.tempRule.value = "";
  5360. this.editTemp = null;
  5361. this.frame.classList.remove("showDetail");
  5362.  
  5363. this.loadNow.style.display = ruleParser.nextLinkHref ? "block" : "none";
  5364. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  5365. this.nextSwitchBtn.style.display = "block";
  5366. } else {
  5367. this.nextSwitchBtn.style.display = "none";
  5368. }
  5369. this.autoScrollBtn.innerText = i18n(autoScroll ? "disableAutoScroll" : "enableAutoScroll");
  5370.  
  5371. let pageElementSel = ruleParser.curSiteRule.pageElement || "";
  5372. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  5373. pageElementSel = pageElementSel[nextIndex < pageElementSel.length ? nextIndex : 0];
  5374. }
  5375. this.setSelectorDiv(pageElementSel);
  5376. this.fillTempRuleTextarea();
  5377. }
  5378. }
  5379. const picker = new Picker();
  5380.  
  5381. var editor, editorChanged = false, customRulesInput;
  5382. function createEdit() {
  5383. var options = {
  5384. mode: 'code',
  5385. modes: ['code', 'tree'],
  5386. templates: [
  5387. {
  5388. text: 'New site',
  5389. title: 'Insert a new site',
  5390. className: 'jsoneditor-type-object',
  5391. field: 'SiteTemplate',
  5392. value: {
  5393. 'name': 'Site name',
  5394. 'url': 'Site url'
  5395. }
  5396. }
  5397. ],
  5398. schema: {
  5399. "title": "Sites data",
  5400. "description": "Object containing site config",
  5401. "type": "array",
  5402. "items": {
  5403. "type": 'object',
  5404. "properties": {
  5405. "name": {
  5406. "title": "Site Name",
  5407. "description": "The site's name.",
  5408. "examples": [
  5409. "Google"
  5410. ],
  5411. "type": "string"
  5412. },
  5413. "url": {
  5414. "title": "Site Url",
  5415. "description": "The Regexp of site's url.",
  5416. "examples": [
  5417. "^https:\/\/yande\\.re\/"
  5418. ],
  5419. "type": "string"
  5420. }
  5421. },
  5422. "required": ["name", "url"]
  5423. }
  5424. },
  5425. onChange: () => {
  5426. editorChanged = true;
  5427. }
  5428. };
  5429. setTimeout(() => {
  5430. var container = document.getElementById("jsoneditor");
  5431. container.style.height = '800px';
  5432. container.innerHTML = "";
  5433. try {
  5434. editor = new _unsafeWindow.JSONEditor(container, options);
  5435. editor.set(ruleParser.customRules);
  5436. } catch (e) {
  5437. editor = null;
  5438. container.style.display = 'none';
  5439. customRulesInput.style.display = "";
  5440. }
  5441. }, 500);
  5442. }
  5443.  
  5444. function checkGuidePage(href) {
  5445. if (guidePage.test(href)) {
  5446. if (typeof _unsafeWindow.JSONEditor !== 'undefined') {
  5447. createEdit();
  5448. } else {
  5449. let timeout = 30;
  5450. let checkEditorReady = setInterval(() => {
  5451. if (typeof _unsafeWindow.JSONEditor !== 'undefined') {
  5452. createEdit();
  5453. clearInterval(checkEditorReady);
  5454. } else if (timeout-- <= 0) {
  5455. editor = null;
  5456. customRulesInput.style.display = "";
  5457. clearInterval(checkEditorReady);
  5458. }
  5459. }, 100);
  5460. }
  5461. return true;
  5462. }
  5463. return false;
  5464. }
  5465.  
  5466. function startAutoScroll() {
  5467. clearInterval(autoScrollInterval);
  5468. if (autoScroll <= 0) return;
  5469. let scrollRange_o = 1;
  5470. if (autoScroll > 1000) {
  5471. scrollRange_o = parseInt(autoScroll / 1000);
  5472. }
  5473. let devicePixelRatio = window.devicePixelRatio;
  5474. let scrollRange = Math.ceil(scrollRange_o / devicePixelRatio);
  5475.  
  5476. let scrollTarget, body = getBody(document);
  5477. if (document.documentElement.scrollTop) {
  5478. scrollTarget = document.documentElement;
  5479. } else if (body.scrollTop) {
  5480. scrollTarget = body;
  5481. } else {
  5482. let tempEle;
  5483. let img = body.querySelector('img');
  5484. if (img) {
  5485. tempEle = img;
  5486. while (tempEle && (tempEle.scrollHeight === tempEle.clientHeight || getComputedStyle(tempEle).overflowY === "hidden")) {
  5487. tempEle = tempEle.parentNode;
  5488. }
  5489. }
  5490. if (!tempEle && document.activeElement) {
  5491. let tempEle = document.activeElement;
  5492. while (tempEle && (tempEle.scrollHeight === tempEle.clientHeight || getComputedStyle(tempEle).overflowY === "hidden")) {
  5493. tempEle = tempEle.parentNode;
  5494. }
  5495. }
  5496. if (tempEle) scrollTarget = tempEle;
  5497. }
  5498. scrollTarget = scrollTarget || document.documentElement;
  5499.  
  5500. autoScrollInterval = setInterval(() => {
  5501. if (isPause) return;
  5502. if (devicePixelRatio !== window.devicePixelRatio) {
  5503. devicePixelRatio = window.devicePixelRatio;
  5504. scrollRange = Math.ceil(scrollRange_o / devicePixelRatio);
  5505. }
  5506. scrollTarget.scrollTop += scrollRange;
  5507. }, parseInt(1000 / autoScroll));
  5508. }
  5509.  
  5510. var inUpdate = false;
  5511. var importHandler, configCon;
  5512. function initConfig(href) {
  5513. if (location.hostname === "github.com") {
  5514. 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) {
  5515. let issue_body = document.getElementById("issue_body");
  5516. if (!issue_body) return true;
  5517. issue_body.value = issue_body.value.replace("\n", "\n" + location.hash.slice(1) + "\n");
  5518. let starButton = document.createElement("a");
  5519. starButton.href = "https://github.com/hoothin/UserScripts#star";
  5520. starButton.className = "js-toggler-target rounded-left-2 btn-with-aria-count btn-sm btn";
  5521. 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>');
  5522. starButton.style.float = "right";
  5523. document.querySelector(".Layout-main>h2").appendChild(starButton);
  5524. return true;
  5525. } else if (location.href === "https://github.com/hoothin/UserScripts#star") {
  5526. let starButton = document.querySelector(".starring-container:not(.on)>.unstarred>form>button");
  5527. if (starButton) emuClick(starButton);
  5528. return true;
  5529. }
  5530. }
  5531. let isGuidePage = checkGuidePage(href);
  5532. if (!isGuidePage) {
  5533. if (href.indexOf("PagetualGuide") != -1) return true;
  5534. if (location.hostname === "pagetual.hoothin.com") return true;
  5535. }
  5536.  
  5537. var click2import, importUrlPres;
  5538.  
  5539. let inConfig = isGuidePage;
  5540. if (!inConfig) {
  5541. for (let i = 0; i < configPage.length; i++) {
  5542. if (configPage[i] == location.href) {
  5543. inConfig = true;
  5544. break;
  5545. }
  5546. }
  5547. }
  5548. configCon = document.getElementById("configCon");
  5549. if (configCon) {
  5550. configCon.parentNode.removeChild(configCon);
  5551. }
  5552. if (ruleImportUrlReg.test(href) || inConfig) {
  5553. let importing = false;
  5554. if (!inUpdate && rulesData.uninited) {
  5555. setTimeout(() => {
  5556. if (!inUpdate && !importing) showTips(i18n("firstAlert"));
  5557. }, 3000);
  5558. showTips(i18n("firstAlert"));
  5559. }
  5560. let defaultOption = document.querySelector('#discussion_rating_4');
  5561. if (defaultOption) defaultOption.checked = true;
  5562. let createImportBtn = (pre) => {
  5563. let importBtn = document.createElement("button");
  5564. importBtn.id = "pagetualImport";
  5565. importBtn.innerText = i18n("import");
  5566. importBtn.style.marginTop = "100px";
  5567. importBtn.style.float = "right";
  5568. importBtn.style.position = "relative";
  5569. importBtn.style.display = "block";
  5570. importBtn.style.fontSize = "20px";
  5571. importBtn.addEventListener("click", e => {
  5572. let parentNode = importBtn.parentNode;
  5573. if (!parentNode) return;
  5574. parentNode.removeChild(importBtn);
  5575. try {
  5576. let rules = parentNode.innerText.trim();
  5577. let isContent = /['"]name['"]/i.test(rules);
  5578. if (isContent) {
  5579. let ruleList = JSON.parse(`[${rules}]`);
  5580. for (let i in ruleList) {
  5581. let hasRule = false;
  5582. let r = ruleList[i];
  5583. for (let j in ruleParser.customRules) {
  5584. if (ruleParser.customRules[j].name == r.name) {
  5585. ruleParser.customRules[j] = r;
  5586. hasRule = true;
  5587. break;
  5588. }
  5589. }
  5590. if (!hasRule) ruleParser.customRules.push(r);
  5591. ruleParser.hpRules.unshift(r);
  5592. }
  5593. storage.setItem("customRules", ruleParser.customRules);
  5594. storage.setItem("hpRules", ruleParser.hpRules);
  5595. storage.setItem("smartRules", []);
  5596. showTips(i18n("importSucc"));
  5597. } else {
  5598. rules = rules.split("\n");
  5599. let diff = false;
  5600. for (let c = 0; c < rules.length; c++) {
  5601. let urlArr = rules[c].split("|"), url, type = 1;
  5602. if (urlArr.length == 1) {
  5603. url = urlArr[0].trim();
  5604. if (!/^http/.test(url)) {
  5605. showTips(i18n("errorWrongUrl"));
  5606. return;
  5607. }
  5608. } else if (urlArr.length == 2) {
  5609. type = urlArr[0].trim();
  5610. url = urlArr[1].trim();
  5611. if (!/^http/.test(url)) {
  5612. showTips(i18n("errorWrongUrl"));
  5613. return;
  5614. }
  5615. } else {
  5616. break;
  5617. }
  5618. let maxId = 1, hasUrl = false;
  5619. if (!rulesData.urls) {
  5620. rulesData.urls = [];
  5621. maxId = 1;
  5622. } else {
  5623. rulesData.urls.forEach(u => {
  5624. if (maxId < u.id) {
  5625. maxId = u.id;
  5626. }
  5627. if (u.url == url) {
  5628. hasUrl = true;
  5629. }
  5630. });
  5631. if (hasUrl) break;
  5632. }
  5633. diff = true;
  5634. if (!rulesData.sort) rulesData.sort = [1];
  5635. rulesData.urls.push({id: maxId + 1, url: url, type: type});
  5636. rulesData.sort.unshift(maxId + 1);
  5637. }
  5638. if (!diff) {
  5639. showTips(i18n("errorAlreadyExists"));
  5640. setTimeout(() => {
  5641. showTips(i18n("beginUpdate"), "", 50000);
  5642. updateRules(() => {
  5643. showTips(i18n("updateSucc"));
  5644. location.reload();
  5645. }, (rule, err) => {
  5646. showTips(`Failed to update ${rule.url} rules!`);
  5647. debug(err);
  5648. });
  5649. }, 500);
  5650. return;
  5651. }
  5652. storage.setItem("rulesData", rulesData);
  5653.  
  5654. if (rulesData.urls) ruleUrls = ruleUrls.concat(rulesData.urls);
  5655. if (rulesData.sort) {
  5656. let urls = [];
  5657. rulesData.sort.forEach(id => {
  5658. for (let s = 0; s < ruleUrls.length; s++) {
  5659. if (id == ruleUrls[s].id) {
  5660. urls.push(ruleUrls[s]);
  5661. break;
  5662. }
  5663. }
  5664. });
  5665. ruleUrls = urls;
  5666. }
  5667. showTips(i18n("beginUpdate"), "", 30000);
  5668. updateRules(() => {
  5669. showTips(i18n("updateSucc"));
  5670. location.reload();
  5671. }, (rule, err) => {
  5672. showTips(`Failed to update ${rule.url} rules!`);
  5673. debug(err);
  5674. });
  5675. importing = true;
  5676. }
  5677. } catch (e) {
  5678. _GM_notification(e.toString());
  5679. }
  5680. });
  5681. if (pre) {
  5682. let clientHeight = 35 - pre.clientHeight;
  5683. if (clientHeight > -20) clientHeight = -20;
  5684. importBtn.style.marginTop = `${clientHeight}px`;
  5685. pre.appendChild(importBtn);
  5686. }
  5687. return importBtn;
  5688. };
  5689. [].forEach.call(document.querySelectorAll('pre[name=pagetual],pre[name=user-content-pagetual]'), pre => {
  5690. let importBtn = createImportBtn(pre);
  5691. });
  5692. if (!importHandler) {
  5693. importHandler = e => {
  5694. if (compareNodeName(e.target, ["pre"])) {
  5695. let nameAttr = e.target.getAttribute("name");
  5696. if (nameAttr == "pagetual" || nameAttr == "user-content-pagetual") {
  5697. if (e.target.querySelector('#pagetualImport')) return;
  5698. let importBtn = createImportBtn(e.target);
  5699. }
  5700. }
  5701. };
  5702. }
  5703. document.removeEventListener("mouseover", importHandler);
  5704. document.addEventListener("mouseover", importHandler);
  5705.  
  5706. if (inConfig) {
  5707. if (!inUpdate && _GM_info.script && _GM_info.script.version && _GM_info.script.version !== '1.0.0') {
  5708. let versionEle = document.querySelector('.markdown-body>h1[id],article>h1');
  5709. let latestVer = versionEle && versionEle.innerText.match(/\d[\d\.]+/)[0];
  5710. if (latestVer && latestVer != _GM_info.script.version) {
  5711. showTips(i18n('outOfDate'), "", 3000);
  5712. }
  5713. }
  5714. _GM_addStyle(`
  5715. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  5716. cursor: pointer;
  5717. user-select: none;
  5718. display: inline-block;
  5719. margin-right: 5px;
  5720. -moz-transition:color 0.3s ease, transform 0.3s;
  5721. -webkit-transition:color 0.3s ease, transform 0.3s;
  5722. transition:color 0.3s ease, transform 0.3s;
  5723. }
  5724. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  5725. color:red;
  5726. transform: scale(1.5);
  5727. -webkit-transform: scale(1.5);
  5728. }
  5729. .updateDate{
  5730. cursor: pointer;
  5731. user-select: none;
  5732. -moz-transition:color 0.3s ease, transform 0.3s;
  5733. -webkit-transition:color 0.3s ease, transform 0.3s;
  5734. transition:color 0.3s ease, transform 0.3s;
  5735. transform-origin: left;
  5736. -webkit-transform-origin: left;
  5737. }
  5738. .updateDate:hover{
  5739. color:red;
  5740. transform: scale(1.1);
  5741. -webkit-transform: scale(1.1);
  5742. }
  5743. input[type=number]::-webkit-inner-spin-button,
  5744. input[type=number]::-webkit-outer-spin-button {
  5745. -webkit-appearance: none;
  5746. margin: 0;
  5747. }
  5748. input[type=number] {
  5749. -moz-appearance:textfield;
  5750. }
  5751. table td>h3 {
  5752. margin: 16px!important;
  5753. padding: 0!important;
  5754. }
  5755. table td>h4 {
  5756. padding: 0!important;
  5757. }
  5758. #saveBtn {
  5759. width: 60vw;
  5760. position: fixed;
  5761. z-index: 999;
  5762. bottom: 0;
  5763. left: 20vw;
  5764. font-size: xx-large;
  5765. opacity: 0.6;
  5766. cursor: pointer;
  5767. -moz-transition:all 0.3s ease;
  5768. -webkit-transition:all 0.3s ease;
  5769. transition:all 0.3s ease;
  5770. }
  5771. #configCon #saveBtn:hover {
  5772. opacity: 1;
  5773. margin-bottom: 0px;
  5774. }
  5775. #configCon #saveBtn {
  5776. margin-bottom: -30px;
  5777. }
  5778. #configCon.showSave #saveBtn {
  5779. margin-bottom: 0px;
  5780. }
  5781. `);
  5782. click2import = document.querySelector("[name='user-content-click2import'],[name='click2import']");
  5783. if (click2import) click2import.innerText = i18n("click2ImportRule")
  5784. configCon = document.querySelector(".markdown-body,.theme-default-content");
  5785. if (!configCon) {
  5786. setTimeout(() => {
  5787. location.reload();
  5788. }, 1000);
  5789. return true;
  5790. }
  5791. let insertPos = configCon.querySelector("hr,#jsoneditor");
  5792. configCon = document.createElement("div");
  5793. configCon.id = "configCon";
  5794. insertPos.parentNode.insertBefore(configCon, insertPos);
  5795.  
  5796. importUrlPres = document.querySelectorAll("pre[name='user-content-pagetual'],pre[name='pagetual']");
  5797. if (importUrlPres) {
  5798. [].forEach.call(importUrlPres, importUrlPre => {
  5799. importUrlPre.style.overflow = "hidden";
  5800. importUrlPre.style.display = rulesData.uninited ? "block" : "none";
  5801. });
  5802. }
  5803. if (click2import) click2import.style.display = rulesData.uninited ? "block" : "none";
  5804. let otherconfig = document.querySelector("a[name='user-content-otherconfig'],a[name='otherconfig']");
  5805. if (otherconfig) otherconfig.parentNode.removeChild(otherconfig);
  5806. let rulesExample = document.querySelector("#user-content-rules-example+a,#rules-example>a");
  5807. if (rulesExample) {
  5808. rulesExample.innerText = i18n("rulesExample");
  5809. if (lang == "zh-CN") {
  5810. rulesExample.href = rulesExample.href.replace("en", "cn");
  5811. } else if (lang == "zh-TW" || lang == "zh-HK") {
  5812. rulesExample.href = rulesExample.href.replace("/en", "");
  5813. }
  5814. }
  5815.  
  5816. let newPos, lastPos = 0;
  5817. window.addEventListener('scroll', function(e) {
  5818. newPos = window.scrollY;
  5819. if (newPos > lastPos) {
  5820. configCon.classList.add("showSave");
  5821. } else {
  5822. configCon.classList.remove("showSave");
  5823. }
  5824. lastPos = newPos;
  5825. });
  5826. } else return false;
  5827. } else return false;
  5828. let ruleBarInsertPos = document.createTextNode(' ');
  5829. configCon.appendChild(ruleBarInsertPos);
  5830. class Rulebar {
  5831. init(ruleUrl) {
  5832. let id = ruleUrl.id;
  5833. this.ruleUrl = ruleUrl;
  5834. this.item = document.createElement("p");
  5835. this.item.dataset.id = id;
  5836. let url = document.createElement("a");
  5837. url.href = ruleUrl.url;
  5838. url.innerHTML = ruleUrl.url;
  5839. url.title = ruleUrl.url;
  5840. let up = document.createElement("span");
  5841. up.innerHTML = "↑ ";
  5842. up.title = i18n("sortTitle");
  5843. let down = document.createElement("span");
  5844. down.innerHTML = "↓ ";
  5845. down.title = i18n("sortTitle");
  5846. let del = document.createElement("span");
  5847. del.innerHTML = "× ";
  5848. up.onclick = e => {
  5849. this.moveUp();
  5850. };
  5851. down.onclick = e => {
  5852. this.moveDown();
  5853. };
  5854. del.onclick = e => {
  5855. this.del();
  5856. };
  5857. this.item.appendChild(up);
  5858. this.item.appendChild(down);
  5859. this.item.appendChild(del);
  5860. this.item.appendChild(url);
  5861. if (ruleParser.rules) {
  5862. url.style.maxWidth = "calc(100% - 150px)";
  5863. url.style.overflow = "hidden";
  5864. url.style.display = "inline-block";
  5865. url.style.textOverflow = "ellipsis";
  5866. url.style.verticalAlign = "bottom";
  5867. url.style.whiteSpace = "nowrap";
  5868. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == id ? 1 : 0), 0);
  5869. let idSpan = document.createElement("span");
  5870. idSpan.style.float = "right";
  5871. idSpan.innerHTML = `[rules: ${rulesLength}]`;
  5872. this.item.appendChild(idSpan);
  5873. this.idSpan = idSpan;
  5874. }
  5875. configCon.insertBefore(this.item, ruleBarInsertPos);
  5876. }
  5877. updateNum() {
  5878. if (ruleParser.rules) {
  5879. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == this.item.dataset.id ? 1 : 0), 0);
  5880. this.idSpan.innerHTML = `[rules: ${rulesLength}]`;
  5881. }
  5882. }
  5883. saveSort() {
  5884. let sort = [];
  5885. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i => {
  5886. sort.push(i.dataset.id);
  5887. });
  5888. rulesData.sort = sort;
  5889. let urls = [];
  5890. sort.forEach(id => {
  5891. for (let s = 0; s < ruleUrls.length; s++) {
  5892. if (id == ruleUrls[s].id) {
  5893. urls.push(ruleUrls[s]);
  5894. break;
  5895. }
  5896. }
  5897. });
  5898. ruleUrls = urls;
  5899. storage.setItem("rulesData", rulesData);
  5900. showTips(i18n("sortTitle"));
  5901. }
  5902. moveUp() {
  5903. let preE = this.item.previousElementSibling;
  5904. if (compareNodeName(preE, ["p"]) && preE.children.length > 1) {
  5905. this.item.parentNode.insertBefore(this.item, preE);
  5906. this.saveSort();
  5907. }
  5908. }
  5909. moveDown() {
  5910. let nextE = this.item.nextElementSibling;
  5911. if (compareNodeName(nextE, ["p"]) && nextE.children.length > 1) {
  5912. this.item.parentNode.insertBefore(nextE, this.item);
  5913. this.saveSort();
  5914. }
  5915. }
  5916. del() {
  5917. if (this.ruleUrl.id < 2) {
  5918. showTips(i18n("cantDel"));
  5919. } else if (window.confirm(i18n("confirmDel"))) {
  5920. for (let u = 0; u < rulesData.urls.length; u++) {
  5921. if (this.ruleUrl.id == rulesData.urls[u].id) {
  5922. rulesData.urls.splice(u, 1);
  5923. break;
  5924. }
  5925. }
  5926. for (let u = 0; u < ruleUrls.length; u++) {
  5927. if (this.ruleUrl.id == ruleUrls[u].id) {
  5928. ruleUrls.splice(u, 1);
  5929. break;
  5930. }
  5931. }
  5932. for (let u = 0; u < rulesData.sort.length; u++) {
  5933. if (this.ruleUrl.id == rulesData.sort[u]) {
  5934. rulesData.sort.splice(u, 1);
  5935. break;
  5936. }
  5937. }
  5938. rulesData.ruleVersion = 0;
  5939. storage.setItem("rulesData", rulesData);
  5940. ruleParser.rules = ruleParser.rules.filter(item => {return item.from != this.ruleUrl.id});
  5941. storage.setItem("rules", ruleParser.rules);
  5942. this.item.parentNode.removeChild(this.item);
  5943. //location.reload();
  5944. }
  5945. }
  5946. }
  5947. let langSelect = document.createElement("select");
  5948. langSelect.style.float = "right";
  5949. langSelect.style.position = "relative";
  5950. langSelect.style.zIndex = "1";
  5951. let option = document.createElement("option");
  5952. option.value = "";
  5953. option.innerText = "Language";
  5954. langSelect.appendChild(option);
  5955. for (let key in langList) {
  5956. let option = document.createElement("option");
  5957. option.value = key;
  5958. option.innerText = langList[key];
  5959. langSelect.appendChild(option);
  5960. }
  5961. langSelect.value = rulesData.lang || "";
  5962. configCon.appendChild(langSelect);
  5963.  
  5964. let updateP = document.createElement("p"), i = 0;
  5965. let now = new Date().getTime();
  5966.  
  5967.  
  5968. let pastDate = (new Date(updateDate)).toString(), passStr;
  5969. let passTime = (now - updateDate) / 1000;
  5970. if (isNaN(passTime)) {
  5971. passStr = i18n("firstUpdate");
  5972. } else {
  5973. if (passTime < 60) {
  5974. passStr = i18n("passSec", parseInt(passTime));
  5975. } else if (passTime < 60 * 60) {
  5976. passStr = i18n("passMin", parseInt(passTime / 60));
  5977. } else if (passTime < 60 * 60 * 24) {
  5978. passStr = i18n("passHour", parseInt(passTime / 3600));
  5979. } else {
  5980. passStr = i18n("passDay", parseInt(passTime / 86400));
  5981. }
  5982. passStr += " 🖱 " + i18n("click2update");
  5983. }
  5984.  
  5985. let rulebarList = [], updateFail = false;
  5986. updateP.className = "updateDate";
  5987. updateP.innerHTML = passStr;
  5988. updateP.title = i18n("update") + " - " + pastDate;
  5989. configCon.appendChild(updateP);
  5990. if (ruleUrls) {
  5991. ruleUrls.forEach(ruleUrl => {
  5992. let rulebar = new Rulebar();
  5993. rulebar.init(ruleUrl);
  5994. rulebarList.push(rulebar);
  5995. });
  5996. }
  5997. let customUrlsTitle = document.createElement("h2");
  5998. customUrlsTitle.innerHTML = i18n("customUrls");
  5999. configCon.appendChild(customUrlsTitle);
  6000. let customUrlsInput = document.createElement("textarea");
  6001. customUrlsInput.style.width = "100%";
  6002. customUrlsInput.style.position = "relative";
  6003. customUrlsInput.placeholder = "http://wedata.net/databases/AutoPagerize/items_all.json \nhttps://hoothin.github.io/UserScripts/Pagetual/pagetualRules.json";
  6004. customUrlsInput.spellcheck = false;
  6005. configCon.appendChild(customUrlsInput);
  6006.  
  6007. let btns = document.createElement("div");
  6008. btns.style.display = "flex";
  6009. configCon.appendChild(btns);
  6010. let upBtnImg = document.createElement("div");
  6011. upBtnImg.style.width = "33%";
  6012. let upBtnImgTitle = document.createElement("h2");
  6013. upBtnImgTitle.style.whiteSpace = "nowrap";
  6014. upBtnImgTitle.style.overflow = "auto";
  6015. upBtnImgTitle.innerHTML = i18n("upBtnImg");
  6016. upBtnImg.appendChild(upBtnImgTitle);
  6017. let upBtnImgInput = document.createElement("input");
  6018. upBtnImgInput.style.width = "100%";
  6019. upBtnImgInput.style.position = "relative";
  6020. upBtnImgInput.placeholder = "data:image/png;base64,UpBtn";
  6021. upBtnImgInput.value = rulesData.upBtnImg || '';
  6022. upBtnImgInput.spellcheck = false;
  6023. upBtnImg.appendChild(upBtnImgInput);
  6024. btns.appendChild(upBtnImg);
  6025.  
  6026. let downBtnImg = document.createElement("div");
  6027. downBtnImg.style.width = "33%";
  6028. let downBtnImgTitle = document.createElement("h2");
  6029. downBtnImgTitle.style.whiteSpace = "nowrap";
  6030. downBtnImgTitle.style.overflow = "auto";
  6031. downBtnImgTitle.innerHTML = i18n("downBtnImg");
  6032. downBtnImg.appendChild(downBtnImgTitle);
  6033. let downBtnImgInput = document.createElement("input");
  6034. downBtnImgInput.style.width = "100%";
  6035. downBtnImgInput.style.position = "relative";
  6036. downBtnImgInput.placeholder = "data:image/png;base64,DownBtn";
  6037. downBtnImgInput.value = rulesData.downBtnImg || '';
  6038. downBtnImgInput.spellcheck = false;
  6039. downBtnImg.appendChild(downBtnImgInput);
  6040. btns.appendChild(downBtnImg);
  6041.  
  6042. let sideControllerIconDiv = document.createElement("div");
  6043. sideControllerIconDiv.style.width = "33%";
  6044. let sideControllerIconTitle = document.createElement("h2");
  6045. sideControllerIconTitle.style.whiteSpace = "nowrap";
  6046. sideControllerIconTitle.style.overflow = "auto";
  6047. sideControllerIconTitle.innerHTML = i18n("sideControllerIcon");
  6048. sideControllerIconDiv.appendChild(sideControllerIconTitle);
  6049. let sideControllerIconInput = document.createElement("input");
  6050. sideControllerIconInput.style.width = "100%";
  6051. sideControllerIconInput.style.position = "relative";
  6052. sideControllerIconInput.placeholder = "📄";
  6053. sideControllerIconInput.value = rulesData.sideControllerIcon || '';
  6054. sideControllerIconInput.spellcheck = false;
  6055. sideControllerIconDiv.appendChild(sideControllerIconInput);
  6056. btns.appendChild(sideControllerIconDiv);
  6057.  
  6058. let otherBtns = document.createElement("div");
  6059. otherBtns.style.display = "flex";
  6060. configCon.appendChild(otherBtns);
  6061. let loadingText = document.createElement("div");
  6062. loadingText.style.width = "100%";
  6063. let loadingTextTitle = document.createElement("h2");
  6064. loadingTextTitle.style.whiteSpace = "nowrap";
  6065. loadingTextTitle.style.overflow = "auto";
  6066. loadingTextTitle.innerHTML = i18n("loadingTextTitle");
  6067. loadingText.appendChild(loadingTextTitle);
  6068. let loadingTextInput = document.createElement("input");
  6069. loadingTextInput.value = rulesData.loadingText || '';
  6070. loadingTextInput.placeholder = i18n("loadingText");
  6071. loadingTextInput.style.width = "100%";
  6072. loadingTextInput.style.position = "relative";
  6073. loadingTextInput.style.margin = "0";
  6074. loadingTextInput.spellcheck = false;
  6075. loadingText.appendChild(loadingTextInput);
  6076. otherBtns.appendChild(loadingText);
  6077.  
  6078. let opacity = document.createElement("div");
  6079. let opacityTitle = document.createElement("h2");
  6080. opacityTitle.style.whiteSpace = "nowrap";
  6081. opacityTitle.style.overflow = "visible";
  6082. opacityTitle.innerHTML = i18n("opacity");
  6083. opacity.appendChild(opacityTitle);
  6084. let opacityInput = document.createElement("input");
  6085. opacityInput.value = rulesData.opacity * 100;
  6086. opacityInput.type = "number";
  6087. opacityInput.min = 0;
  6088. opacityInput.max = 100;
  6089. opacityInput.style.width = "110px";
  6090. opacityInput.style.position = "relative";
  6091. opacityInput.style.margin = "0";
  6092. opacityInput.placeholder = i18n("opacityPlaceholder");
  6093. opacityInput.spellcheck = false;
  6094. opacityInput.oninput = e => {
  6095. if (opacityInput.value > 100) opacityInput.value = 100;
  6096. else if (opacityInput.value < 0) opacityInput.value = 0;
  6097. };
  6098. opacity.appendChild(opacityInput);
  6099. otherBtns.appendChild(opacity);
  6100.  
  6101. let pageElementCss = document.createElement("div");
  6102. pageElementCss.style.marginBottom = "30px";
  6103. let pageElementCssTitle = document.createElement("h2");
  6104. pageElementCssTitle.innerHTML = i18n("pageElementCss");
  6105. pageElementCss.appendChild(pageElementCssTitle);
  6106. let pageElementCssInput = document.createElement("input");
  6107. pageElementCssInput.value = rulesData.pageElementCss || '';
  6108. pageElementCssInput.style.width = "100%";
  6109. pageElementCssInput.style.position = "relative";
  6110. pageElementCssInput.style.margin = "0";
  6111. pageElementCssInput.placeholder = "font-size: xx-large;";
  6112. pageElementCssInput.spellcheck = false;
  6113. pageElementCss.appendChild(pageElementCssInput);
  6114. configCon.appendChild(pageElementCss);
  6115.  
  6116. let customCss = document.createElement("div");
  6117. customCss.style.marginBottom = "50px";
  6118. let customCssTitle = document.createElement("h2");
  6119. customCssTitle.innerHTML = i18n("customCss");
  6120. customCss.appendChild(customCssTitle);
  6121. let customCssInput = document.createElement("textarea");
  6122. customCssInput.value = rulesData.customCss || '';
  6123. customCssInput.style.width = "100%";
  6124. customCssInput.style.position = "relative";
  6125. customCssInput.style.margin = "0";
  6126. customCssInput.placeholder = ".pagetual {\n}";
  6127. customCssInput.spellcheck = false;
  6128. customCss.appendChild(customCssInput);
  6129. configCon.appendChild(customCss);
  6130.  
  6131. let configTable = document.createElement("table");
  6132. configTable.style.width = "100%";
  6133. let configTbody = document.createElement("tbody");
  6134. configTbody.style.width = "99%";
  6135. configTbody.style.display = "inline-table";
  6136. configTable.appendChild(configTbody);
  6137. configCon.appendChild(configTable);
  6138. function createCheckbox(innerText, val, tag, parentCheck, otherType, alwaysShow) {
  6139. if (typeof val == 'undefined') val = "";
  6140. let title = document.createElement(tag || "h3");
  6141. title.innerHTML = innerText;
  6142. title.style.overflowWrap = "normal";
  6143. let input = document.createElement("input");
  6144. if (otherType === 'key') {
  6145. input.type = 'text';
  6146. input.setAttribute('readOnly', 'readonly');
  6147. input.addEventListener("keydown", e => {
  6148. if (e.key === 'Escape' || e.key === 'Backspace') input.value = '';
  6149. else input.value = e.key;
  6150. e.stopPropagation();
  6151. e.preventDefault();
  6152. });
  6153. } else {
  6154. input.type = otherType || "checkbox";
  6155. }
  6156. input.style.width = "35px";
  6157. input.style.height = "20px";
  6158. input.style.float = "left";
  6159. input.style.margin = "0 2px";
  6160. input.value = val;
  6161. input.checked = val;
  6162. let td = document.createElement("td");
  6163. td.appendChild(input);
  6164. if (parentCheck) {
  6165. title.appendChild(input);
  6166. title.style.margin = "0";
  6167. td.appendChild(title);
  6168. let parent = parentCheck.parentNode.nextElementSibling;
  6169. let tr = parent.querySelector("tr");
  6170. if (!tr) {
  6171. tr = document.createElement("tr");
  6172. parent.appendChild(tr);
  6173. }
  6174. tr.appendChild(td);
  6175. if (!alwaysShow) {
  6176. if (!parentCheck.checked) {
  6177. td.style.display = "none";
  6178. }
  6179. parentCheck.addEventListener("click", e => {
  6180. td.style.display = parentCheck.checked ? "" : "none";
  6181. });
  6182. }
  6183. } else {
  6184. let tr = document.createElement("tr");
  6185. tr.appendChild(td);
  6186. td = document.createElement("td");
  6187. td.appendChild(title);
  6188. tr.appendChild(td);
  6189. configTable.children[0].appendChild(tr);
  6190. }
  6191. let xNodePos = innerText.indexOf('【X】');
  6192. if (xNodePos !== -1) {
  6193. input.style.float = "";
  6194. let xNode = title.firstChild.splitText(xNodePos);
  6195. xNode.splitText(3);
  6196. xNode.parentNode.replaceChild(input, xNode);
  6197. }
  6198. return input;
  6199. }
  6200.  
  6201. let setConfigPageInput = createCheckbox(i18n("setConfigPage"), false);
  6202. let enableWhiteListInput = createCheckbox(i18n("autoRun"), rulesData.enableWhiteList != true);
  6203. let sideControllerInput = createCheckbox(i18n("sideController"), rulesData.sideController);
  6204. let sideControllerAlwaysInput = createCheckbox(i18n("sideControllerAlways"), rulesData.sideControllerAlways, "h4", sideControllerInput);
  6205. let sideControllerScrollInput = createCheckbox(i18n("sideControllerScroll"), rulesData.sideControllerScroll !== false, "h4", sideControllerInput);
  6206. let sideControllerLoadNowInput = createCheckbox(i18n("loadNow"), rulesData.sideControllerLoadNow !== false, "h4", sideControllerInput);
  6207. let enableDebugInput = createCheckbox(i18n("enableDebug"), rulesData.enableDebug != false);
  6208. let enableHistoryInput = createCheckbox(i18n("enableHistory"), rulesData.enableHistory === true);
  6209. let enableHistoryAfterInsertInput = createCheckbox(i18n("enableHistoryAfterInsert"), rulesData.enableHistoryAfterInsert === true, "h4", enableHistoryInput);
  6210. let openInNewTabInput = createCheckbox(i18n("openInNewTab"), rulesData.openInNewTab != false);
  6211. let hidePageBarInput = createCheckbox(i18n("hideBarTips"), rulesData.opacity == 0);
  6212. let hidePageBarArrowInput = createCheckbox(i18n("hideBarArrow"), rulesData.hideBarArrow);
  6213. let hideLoadingIconInput = createCheckbox(i18n("hideLoadingIcon"), rulesData.hideLoadingIcon != false);
  6214. let initRunInput = createCheckbox(i18n("initRun"), rulesData.initRun != false);
  6215. let autoLoadNumInput = createCheckbox(i18n("autoLoadNum"), rulesData.autoLoadNum, "h4", initRunInput, "number");
  6216. let preloadInput = createCheckbox(i18n("preload"), rulesData.preload != false);
  6217. let rateInput = createCheckbox(i18n("turnRate"), rulesData.rate, "h4", preloadInput, "number", true);
  6218. let dbClick2StopInput = createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  6219. let manualModeInput = createCheckbox(i18n("manualMode"), rulesData.manualMode);
  6220. let clickModeInput = createCheckbox(i18n("clickMode"), rulesData.clickMode);
  6221. let pageBarMenuInput = createCheckbox(i18n("pageBarMenu"), rulesData.pageBarMenu != false);
  6222. let arrowToScrollInput = createCheckbox(i18n("arrowToScroll"), rulesData.arrowToScroll);
  6223. let contentVisibilityInput = createCheckbox(i18n("contentVisibility"), rulesData.contentVisibility);
  6224. let wedata2githubInput = createCheckbox(i18n("wedata2github"), rulesData.wedata2github);
  6225. let customFirstInput = createCheckbox(i18n("customFirst"), rulesData.customFirst);
  6226. let lastPageTipsInput = createCheckbox(i18n("lastPageTips"), rulesData.lastPageTips);
  6227. let updateNotificationInput = createCheckbox(i18n("updateNotification"), rulesData.updateNotification != false);
  6228.  
  6229. let hideBarInput = createCheckbox(i18n("hideBar"), rulesData.hideBar && !rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  6230. hideBarInput.name = 'hideBar';
  6231. let hideBarButNoStopInput = createCheckbox(i18n("hideBarButNoStop"), rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  6232. hideBarButNoStopInput.name = 'hideBar';
  6233. hideBarInput.addEventListener('mouseup', e => {
  6234. if (hideBarInput.checked) {
  6235. setTimeout(() => {hideBarInput.checked = false}, 0);
  6236. }
  6237. });
  6238. hideBarButNoStopInput.addEventListener('mouseup', e => {
  6239. if (hideBarButNoStopInput.checked) {
  6240. setTimeout(() => {hideBarButNoStopInput.checked = false}, 0);
  6241. }
  6242. });
  6243. hidePageBarInput.addEventListener('click', e => {
  6244. opacityInput.value = hidePageBarInput.checked ? 0 : 100;
  6245. });
  6246.  
  6247. let dbClick2StopCtrlInput = createCheckbox(i18n("dbClick2StopCtrl"), rulesData.dbClick2StopCtrl, "h4", dbClick2StopInput);
  6248. let dbClick2StopAltInput = createCheckbox(i18n("dbClick2StopAlt"), rulesData.dbClick2StopAlt, "h4", dbClick2StopInput);
  6249. let dbClick2StopShiftInput = createCheckbox(i18n("dbClick2StopShift"), rulesData.dbClick2StopShift, "h4", dbClick2StopInput);
  6250. let dbClick2StopMetaInput = createCheckbox(i18n("dbClick2StopMeta"), rulesData.dbClick2StopMeta, "h4", dbClick2StopInput);
  6251. let dbClick2StopKeyInput = createCheckbox(i18n("dbClick2StopKey"), rulesData.dbClick2StopKey, "h4", dbClick2StopInput, "key");
  6252.  
  6253. let otherConfigPage = (rulesData.configPage || configPage[0]) != location.href.replace(/#.*/, "");
  6254. if (!otherConfigPage) {
  6255. setConfigPageInput.parentNode.parentNode.style.display = "none";
  6256. }
  6257.  
  6258. updateP.onclick = e => {
  6259. updateFail = false;
  6260. //ruleParser.rules = [];
  6261. showTips(i18n("beginUpdate"), "", 30000);
  6262. updateRules(() => {
  6263. if (!updateFail) {
  6264. showTips(i18n("updateSucc"));
  6265. if (importUrlPres) {
  6266. [].forEach.call(importUrlPres, importUrlPre => {
  6267. importUrlPre.style.display = "none";
  6268. });
  6269. }
  6270. if (click2import) click2import.style.display = "none";
  6271. }
  6272. updateP.innerHTML = i18n("passSec", 0);
  6273. updateP.title = i18n("update");
  6274. rulebarList.forEach(rulebar => {
  6275. rulebar.updateNum();
  6276. });
  6277. }, (rule, err) => {
  6278. if (rule.id == 1) {
  6279. showTips(`Failed to update wedata rules! Try to switch to wedata mirror!`);
  6280. wedata2githubInput.scrollIntoView({ behavior: "smooth" });
  6281. } else {
  6282. showTips(`Failed to update ${rule.url} rules!`);
  6283. }
  6284. debug(err);
  6285. updateFail = true;
  6286. });
  6287. };
  6288. let customRulesTitle = document.createElement("h2");
  6289. 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');
  6290. configCon.appendChild(customRulesTitle);
  6291. customRulesInput = document.createElement("textarea");
  6292. customRulesInput.spellcheck = false;
  6293. configCon.appendChild(customRulesInput);
  6294. if (rulesData.editTemp) {
  6295. if (!ruleParser.customRules) {
  6296. ruleParser.customRules = [];
  6297. }
  6298. for (let i in ruleParser.customRules) {
  6299. if (ruleParser.customRules[i].url == rulesData.editTemp.url) {
  6300. ruleParser.customRules.splice(i, 1);
  6301. break;
  6302. }
  6303. }
  6304. ruleParser.customRules.unshift(rulesData.editTemp);
  6305. rulesData.editTemp = null;
  6306. storage.setItem("rulesData", rulesData);
  6307. customRulesInput.previousElementSibling.scrollIntoView();
  6308. }
  6309. customRulesInput.style.width = "100%";
  6310. customRulesInput.style.height = "800px";
  6311. 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]`;
  6312. let preCustom = getFormatJSON(ruleParser.customRules);
  6313. customRulesInput.value = preCustom;
  6314. if (isGuidePage) customRulesInput.style.display = "none";
  6315. let blacklistInput = document.createElement("textarea");
  6316. blacklistInput.style.width = "100%";
  6317. blacklistInput.style.height = "500px";
  6318. blacklistInput.style.display = "none";
  6319. blacklistInput.spellcheck = false;
  6320. 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";
  6321. blacklistInput.value = rulesData.blacklist ? rulesData.blacklist.join("\n") : "";
  6322. let blacklistBtn = document.createElement("button");
  6323. blacklistBtn.innerText = i18n("editBlacklist");
  6324. blacklistBtn.style.width = "100%";
  6325. blacklistBtn.onclick = e => {
  6326. blacklistInput.style.display = blacklistInput.style.display == "none" ? "" : "none";
  6327. };
  6328. configCon.appendChild(blacklistBtn);
  6329. configCon.appendChild(blacklistInput);
  6330. let saveBtn = document.createElement("button");
  6331. saveBtn.innerHTML = i18n("save");
  6332. saveBtn.id = "saveBtn";
  6333. configCon.appendChild(saveBtn);
  6334. saveBtn.onclick = e => {
  6335. try {
  6336. let customRules;
  6337. if (editor) {
  6338. if (editorChanged) {
  6339. editorChanged = false;
  6340. storage.setItem("hpRules", []);
  6341. storage.setItem("smartRules", []);
  6342. }
  6343. customRules = editor.get();
  6344. if (!customRules) {
  6345. customRules = "";
  6346. } else {
  6347. if (Array && Array.isArray && !Array.isArray(customRules)) {
  6348. showTips(i18n("errorRulesMustBeArray"));
  6349. return;
  6350. }
  6351. }
  6352. } else {
  6353. if (customRulesInput.value != preCustom) {
  6354. storage.setItem("hpRules", []);
  6355. storage.setItem("smartRules", []);
  6356. }
  6357. if (customRulesInput.value == "") {
  6358. customRules = "";
  6359. } else {
  6360. customRules = JSON.parse(customRulesInput.value);
  6361. if (Array && Array.isArray && !Array.isArray(customRules)) {
  6362. showTips(i18n("errorRulesMustBeArray"));
  6363. return;
  6364. }
  6365. customRulesInput.value = JSON.stringify(customRules, null, 4);
  6366. }
  6367. }
  6368. debug(customRules);
  6369. storage.setItem("customRules", customRules);
  6370. } catch(e) {
  6371. debug(e);
  6372. let pos = e && e.message && e.message.match(/position (\d+)/);
  6373. if (pos && !editor) {
  6374. pos = parseInt(pos[1]);
  6375. customRulesInput.value = customRulesInput.value.slice(0, pos) + "➡️" + customRulesInput.value.slice(pos);
  6376. }
  6377. showTips(i18n("errorJson"));
  6378. return;
  6379. }
  6380. rulesData.lang = langSelect.value || "";
  6381. if (setConfigPageInput.checked) rulesData.configPage = location.href;
  6382. rulesData.wedata2github = wedata2githubInput.checked;
  6383. let opacity = parseInt(opacityInput.value) || 0;
  6384. if (opacity > 100) opacity = 100;
  6385. else if (opacity < 0) opacity = 0;
  6386. rulesData.opacity = opacity / 100;
  6387. rulesData.blacklist = blacklistInput.value ? blacklistInput.value.trim().split("\n") : "";
  6388. rulesData.hideBar = hideBarInput.checked;
  6389. rulesData.hideBarButNoStop = hideBarButNoStopInput.checked;
  6390. rulesData.dbClick2Stop = dbClick2StopInput.checked;
  6391. rulesData.enableWhiteList = !enableWhiteListInput.checked;
  6392. rulesData.enableDebug = enableDebugInput.checked;
  6393. rulesData.updateNotification = updateNotificationInput.checked;
  6394. rulesData.enableHistory = enableHistoryInput.checked;
  6395. rulesData.enableHistoryAfterInsert = enableHistoryAfterInsertInput.checked;
  6396. rulesData.openInNewTab = openInNewTabInput.checked;
  6397. rulesData.hideLoadingIcon = hideLoadingIconInput.checked;
  6398. rulesData.hideBarArrow = hidePageBarArrowInput.checked;
  6399. rulesData.customFirst = customFirstInput.checked;
  6400. rulesData.lastPageTips = lastPageTipsInput.checked;
  6401. rulesData.initRun = initRunInput.checked;
  6402. rulesData.autoLoadNum = autoLoadNumInput.value !== "0" ? autoLoadNumInput.value : '';
  6403. rulesData.rate = parseFloat(rateInput.value) || 0;
  6404. rulesData.preload = preloadInput.checked;
  6405. rulesData.manualMode = manualModeInput.checked;
  6406. rulesData.clickMode = clickModeInput.checked;
  6407. rulesData.pageBarMenu = pageBarMenuInput.checked;
  6408. rulesData.arrowToScroll = arrowToScrollInput.checked;
  6409. rulesData.contentVisibility = contentVisibilityInput.checked;
  6410. if (rulesData.sideController != sideControllerInput.checked) {
  6411. rulesData.sideControllerPos = false;
  6412. }
  6413. rulesData.sideController = sideControllerInput.checked;
  6414. rulesData.sideControllerScroll = sideControllerScrollInput.checked;
  6415. rulesData.sideControllerLoadNow = sideControllerLoadNowInput.checked;
  6416. rulesData.sideControllerAlways = sideControllerAlwaysInput.checked;
  6417. rulesData.pageElementCss = pageElementCssInput.value;
  6418. rulesData.customCss = customCssInput.value;
  6419. rulesData.upBtnImg = upBtnImgInput.value;
  6420. rulesData.downBtnImg = downBtnImgInput.value;
  6421. rulesData.sideControllerIcon = sideControllerIconInput.value;
  6422. rulesData.loadingText = loadingTextInput.value;
  6423. rulesData.dbClick2StopCtrl = dbClick2StopCtrlInput.checked;
  6424. rulesData.dbClick2StopAlt = dbClick2StopAltInput.checked;
  6425. rulesData.dbClick2StopShift = dbClick2StopShiftInput.checked;
  6426. rulesData.dbClick2StopMeta = dbClick2StopMetaInput.checked;
  6427. rulesData.dbClick2StopKey = dbClick2StopKeyInput.value;
  6428. storage.setItem("rulesData", rulesData);
  6429. let customUrls = customUrlsInput.value.trim(), urlImported = false;
  6430. if (customUrls) {
  6431. customUrls = customUrls.split(/\n/);
  6432. for (let c = 0; c < customUrls.length; c++) {
  6433. let url;
  6434. if (/^0\s*\|/.test(customUrls[c])) {
  6435. url = customUrls[c].replace(/^0\s*\|\s*/, "").trim();
  6436. if (!/^http/.test(url)) {
  6437. showTips(i18n("errorWrongUrl"));
  6438. return;
  6439. }
  6440. } else {
  6441. url = customUrls[c].trim();
  6442. if (!/^http/.test(url)) {
  6443. showTips(i18n("errorWrongUrl"));
  6444. return;
  6445. }
  6446. }
  6447. let maxId = 1, hasUrl = false;
  6448. if (!rulesData.urls) {
  6449. rulesData.urls = [];
  6450. }
  6451. ruleUrls.forEach(u => {
  6452. if (maxId < u.id) {
  6453. maxId = u.id;
  6454. }
  6455. if (u.url == url) {
  6456. hasUrl = true;
  6457. }
  6458. });
  6459. if (hasUrl) break;
  6460. if (!rulesData.sort) rulesData.sort = [1];
  6461. let newRule = {id: maxId + 1, url: url};
  6462. ruleUrls.push(newRule);
  6463. rulesData.urls.push(newRule);
  6464. rulesData.sort.push(maxId + 1);
  6465. storage.setItem("rulesData", rulesData);
  6466. let rulebar = new Rulebar();
  6467. rulebar.init(newRule);
  6468. rulebarList.push(rulebar);
  6469. }
  6470. }
  6471. showTips(i18n("settingsSaved"));
  6472. };
  6473. return true;
  6474. }
  6475.  
  6476. function updateRules (success, fail, keepCache) {
  6477. if (!storage.supportCrossSave()) {
  6478. fail({url:''}, "Not support cross storage");
  6479. showTips("Current platform do not support cross storage!");
  6480. return;
  6481. }
  6482. if (inUpdate) return;
  6483. inUpdate = true;
  6484. let ruleIndex = ruleUrls.length - 1;
  6485. if (!keepCache) {
  6486. storage.setItem("hpRules", []);
  6487. storage.setItem("smartRules", []);
  6488. }
  6489. let allOk = true;
  6490. let preLength = ruleParser.rules.length;
  6491. let fetchVersion = -1;
  6492. async function needUpdate(url, id) {
  6493. if (!/^https:\/\/hoothin\.github\.io\/|\/hoothin\/UserScripts\/.*\/Pagetual\/pagetualRules\.json/i.test(url)) {
  6494. return true;
  6495. }
  6496. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == id ? 1 : 0), 0);
  6497. if (rulesLength === 0) return true;
  6498. if (fetchVersion >= 0) {
  6499. return fetchVersion > (rulesData.ruleVersion || 0);
  6500. }
  6501. fetchVersion = await new Promise(resolve => {
  6502. _GM_xmlhttpRequest({
  6503. url: url.replace(/\/\w+\.json/i, "/version"),
  6504. method: 'GET',
  6505. timeout: 20000,
  6506. headers: {
  6507. 'accept': 'application/json,text/html'
  6508. },
  6509. onload: function(res) {
  6510. let version = parseInt(res.response || res.responseText);
  6511. resolve(version || -1);
  6512. },
  6513. onerror: function(e) {
  6514. resolve(-1);
  6515. },
  6516. ontimeout: function(e) {
  6517. resolve(-1);
  6518. }
  6519. });
  6520. });
  6521. return fetchVersion > (rulesData.ruleVersion || 0);
  6522. }
  6523. async function addNextRule() {
  6524. if (ruleIndex < 0) {
  6525. let now = new Date().getTime();
  6526. storage.setItem("ruleLastUpdate", now);
  6527. storage.setItem("rules", ruleParser.rules);
  6528. let curLength = ruleParser.rules.length;
  6529. if (curLength !== preLength && rulesData.updateNotification) {
  6530. _GM_notification({
  6531. text: `Rules has updated( ${preLength} => ${curLength} )`,
  6532. title: "Pagetual rules updated",
  6533. onclick: (event) => {
  6534. event.preventDefault();
  6535. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  6536. }
  6537. });
  6538. }
  6539. inUpdate = false;
  6540. let rulesDataChanged = false;
  6541. if (fetchVersion >= 0 && rulesData.ruleVersion !== fetchVersion) {
  6542. rulesData.ruleVersion = fetchVersion;
  6543. rulesDataChanged = true;
  6544. }
  6545. if (rulesData.uninited && allOk && ruleUrls.length > 1) {
  6546. rulesData.uninited = false;
  6547. rulesDataChanged = true;
  6548. }
  6549. if (rulesDataChanged) {
  6550. storage.setItem("rulesData", rulesData);
  6551. }
  6552. success();
  6553. } else {
  6554. let rule = ruleUrls[ruleIndex--];
  6555. if (await needUpdate(rule.url, rule.id)) {
  6556. ruleParser.addRuleByUrl(rule.url, rule.id, (json, err) => {
  6557. if (!json) {
  6558. allOk = false;
  6559. fail(rule, err);
  6560. }
  6561. addNextRule();
  6562. });
  6563. } else {
  6564. addNextRule();
  6565. }
  6566. }
  6567. }
  6568. addNextRule();
  6569. }
  6570.  
  6571. function objIsArr(obj) {
  6572. return obj &&
  6573. typeof obj === 'object' &&
  6574. typeof obj.length === 'number' &&
  6575. !(obj.propertyIsEnumerable('length'));
  6576. }
  6577.  
  6578. function isVisible(el, win) {
  6579. if(!el || !el.offsetParent)return false;
  6580. var loopable = true,
  6581. visible = el.nodeName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  6582. while(loopable && visible) {
  6583. el = el.parentNode;
  6584.  
  6585. if(el && !compareNodeName(el, ["body"])) {
  6586. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  6587. }else {
  6588. loopable = false;
  6589. }
  6590. }
  6591. return visible;
  6592. }
  6593.  
  6594. function getElementTop(ele) {
  6595. if (!ele) return 0;
  6596. if (ele.getBoundingClientRect) {
  6597. return ele.getBoundingClientRect().top + document.documentElement.scrollTop;
  6598. }
  6599. var actualTop = ele.offsetTop;
  6600. var current = ele.offsetParent;
  6601. while (current) {
  6602. actualTop += current.offsetTop;
  6603. current = current.offsetParent;
  6604. }
  6605. return actualTop;
  6606. }
  6607.  
  6608. function getElementLeft(ele) {
  6609. if (!ele) return 0;
  6610. if (ele.getBoundingClientRect) {
  6611. return ele.getBoundingClientRect().left + document.documentElement.scrollLeft;
  6612. }
  6613. var actualLeft = ele.offsetLeft;
  6614. var current = ele.offsetParent;
  6615. while (current) {
  6616. actualLeft += current.offsetLeft;
  6617. current = current.offsetParent;
  6618. }
  6619. return actualLeft;
  6620. }
  6621.  
  6622. function getElementBottom(ele) {
  6623. return getElementTop(ele) + (ele.offsetHeight || ele.scrollHeight);
  6624. }
  6625.  
  6626. function getFormatJSON(obj){
  6627. if(!objIsArr(obj) || obj.length === 0)return "";
  6628. return JSON.stringify(obj, null, 4);
  6629. }
  6630.  
  6631. function globMatch(first, second) {
  6632. if (first === '*') {
  6633. return true;
  6634. }
  6635. if (first.length == 0 && second.length == 0){
  6636. return true;
  6637. }
  6638.  
  6639. if (first.length > 1 && first[0] == '*' &&
  6640. second.length == 0){
  6641. return false;
  6642. }
  6643.  
  6644. if ((first.length > 1 && first[0] == '?') ||
  6645. (first.length != 0 && second.length != 0 &&
  6646. first[0] == second[0])){
  6647. return globMatch(first.substring(1),
  6648. second.substring(1));
  6649. }
  6650.  
  6651. if (first.length > 0 && first[0] == '*'){
  6652. return globMatch(first.substring(1), second) ||
  6653. globMatch(first, second.substring(1));
  6654. }
  6655.  
  6656. return false;
  6657. }
  6658.  
  6659. let pageReady = false;
  6660. function initRules(callback) {
  6661. charset = (document.characterSet || document.charset || document.inputEncoding);
  6662. let equiv = document.querySelector('[http-equiv="Content-Type"]');
  6663. if (equiv && equiv.content) {
  6664. let innerCharSet = equiv.content.match(/charset\=([^;]+)/);
  6665. if (!innerCharSet) {
  6666. charsetValid = false;
  6667. } else if (innerCharSet[1].replace("-", "").toLowerCase() != charset.replace("-", "").toLowerCase()) {
  6668. charsetValid = false;
  6669. }
  6670. } else charsetValid = false;
  6671. storage.getItem("rulesData", data => {
  6672. /*0 wedata格式,1 pagetual格式*/
  6673. ruleUrls = [{
  6674. id: 1,
  6675. url: data && data.wedata2github ? 'https://hoothin.github.io/UserScripts/Pagetual/items_all.json' : 'http://wedata.net/databases/AutoPagerize/items_all.json',
  6676. type: 0,
  6677. }];
  6678. if (data) {
  6679. rulesData = data;
  6680. if (data.urls) ruleUrls = ruleUrls.concat(data.urls);
  6681. if (data.sort) {
  6682. let urls = [];
  6683. data.sort.forEach(id => {
  6684. for (let s = 0; s < ruleUrls.length; s++) {
  6685. if (id == ruleUrls[s].id) {
  6686. urls.push(ruleUrls[s]);
  6687. break;
  6688. }
  6689. }
  6690. });
  6691. ruleUrls = urls;
  6692. }
  6693. }
  6694. if (rulesData.lang) {
  6695. setLang(rulesData.lang);
  6696. }
  6697. if (rulesData.firstRun) {
  6698. rulesData.firstRun = false;
  6699. storage.setItem("rulesData", rulesData);
  6700. setTimeout(() => {
  6701. storage.getItem("rulesData", data => {
  6702. if (data.firstRun === false) {
  6703. _GM_openInTab(firstRunPage, {active: true});
  6704. }
  6705. });
  6706. }, 100);
  6707. }
  6708. _GM_registerMenuCommand(i18n("configure"), () => {
  6709. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  6710. });
  6711. if (rulesData.blacklist && rulesData.blacklist.length > 0) {
  6712. let href = location.href.slice(0, 500);
  6713. let commentStart = false;
  6714. for (let i = 0; i < rulesData.blacklist.length; i++) {
  6715. let curGlob = rulesData.blacklist[i];
  6716. if (!curGlob) continue;
  6717. if (curGlob.indexOf("//") == 0) continue;
  6718. if (commentStart) {
  6719. if (/\*\/$/.test(curGlob)) {
  6720. commentStart = false;
  6721. }
  6722. continue;
  6723. }
  6724. if (curGlob.indexOf("/*") == 0) {
  6725. commentStart = true;
  6726. continue;
  6727. }
  6728. if (curGlob.indexOf("/") == 0) {
  6729. let regMatch = curGlob.match(/^\/(.*)\/(\w*)$/);
  6730. if (regMatch && new RegExp(regMatch[1], regMatch[2]).test(href)) {
  6731. forceState == 1;
  6732. return;
  6733. }
  6734. } else if (globMatch(curGlob, href)) {
  6735. forceState == 1;
  6736. return;
  6737. }
  6738. }
  6739. }
  6740. _GM_registerMenuCommand(i18n("editCurrent"), () => {
  6741. picker.start();
  6742. });
  6743. ruleParser.initSavedRules(async () => {
  6744. let upBtnImg = rulesData.upBtnImg, downBtnImg = rulesData.downBtnImg, _sideControllerIcon = rulesData.sideControllerIcon;
  6745. if (upBtnImg && downBtnImg) {
  6746. downSvgCSS = downSvgCSS.replace("transform: rotate(180deg);", "");
  6747. } else if (upBtnImg && !downBtnImg) {
  6748. downBtnImg = upBtnImg;
  6749. } else if(downBtnImg && !upBtnImg) {
  6750. upBtnImg = downBtnImg;
  6751. }
  6752. if (upBtnImg) {
  6753. upSvg = /https?:|data/.test(upBtnImg) ? `<img class="pagetual" src="${upBtnImg}"/>` : `<span>${upBtnImg}</span>`;
  6754. }
  6755. if (downBtnImg) {
  6756. downSvg = /https?:|data/.test(downBtnImg) ? `<img class="pagetual" src="${downBtnImg}"/>` : `<span>${downBtnImg}</span>`;
  6757. }
  6758. if (_sideControllerIcon) {
  6759. sideControllerIcon = /https?:|data/.test(_sideControllerIcon) ? `<img class="pagetual" src="${_sideControllerIcon}"/>` : `<span>${_sideControllerIcon}</span>`;
  6760. }
  6761. setLoadingDiv(rulesData.loadingText || i18n("loadingText"));
  6762. if (typeof(rulesData.opacity) == "undefined") {
  6763. rulesData.opacity = 1;
  6764. }
  6765. if (typeof(rulesData.hideBar) == "undefined") {
  6766. rulesData.hideBar = false;
  6767. }
  6768. if (typeof(rulesData.dbClick2Stop) == "undefined") {
  6769. rulesData.dbClick2Stop = true;
  6770. }
  6771. if (typeof(rulesData.enableWhiteList) == "undefined") {
  6772. rulesData.enableWhiteList = false;
  6773. }
  6774. if (typeof(rulesData.enableHistory) == "undefined") {
  6775. rulesData.enableHistory = false;
  6776. }
  6777. if (typeof(rulesData.openInNewTab) == "undefined") {
  6778. rulesData.openInNewTab = false;
  6779. }
  6780. if (typeof(rulesData.enableDebug) == "undefined") {
  6781. rulesData.enableDebug = true;
  6782. }
  6783. if (typeof(rulesData.updateNotification) == "undefined") {
  6784. rulesData.updateNotification = true;
  6785. }
  6786. if (typeof(rulesData.initRun) == "undefined") {
  6787. rulesData.initRun = true;
  6788. }
  6789. if (typeof(rulesData.preload) == "undefined") {
  6790. rulesData.preload = true;
  6791. }
  6792. if (typeof(rulesData.customFirst) == "undefined") {
  6793. rulesData.customFirst = false;
  6794. }
  6795. if (typeof(rulesData.manualMode) == "undefined") {
  6796. rulesData.manualMode = false;
  6797. }
  6798. if (typeof(rulesData.clickMode) == "undefined") {
  6799. rulesData.clickMode = false;
  6800. }
  6801. if (typeof(rulesData.pageBarMenu) == "undefined") {
  6802. rulesData.pageBarMenu = true;
  6803. }
  6804. if (typeof(rulesData.arrowToScroll) == "undefined") {
  6805. rulesData.arrowToScroll = false;
  6806. }
  6807. if (typeof(rulesData.hideLoadingIcon) == "undefined") {
  6808. rulesData.hideLoadingIcon = false;
  6809. }
  6810. if (typeof(rulesData.hideBarArrow) == "undefined") {
  6811. rulesData.hideBarArrow = false;
  6812. }
  6813. if (typeof(rulesData.lastPageTips) == "undefined") {
  6814. rulesData.lastPageTips = true;
  6815. }
  6816. if (typeof(rulesData.rate) == "undefined") {
  6817. rulesData.rate = 1;
  6818. }
  6819. rate = rulesData.rate;
  6820. if (rulesData.autoLoadNum && rulesData.initRun) {
  6821. autoLoadNum = parseInt(rulesData.autoLoadNum);
  6822. }
  6823. openInNewTab = rulesData.openInNewTab ? 1 : 0;
  6824. enableDebug = rulesData.enableDebug;
  6825.  
  6826. let _nextSwitch = await getListData("nextSwitch", location.host);
  6827. if (typeof(_nextSwitch) !== "undefined") {
  6828. nextIndex = _nextSwitch || 0;
  6829. }
  6830.  
  6831. let _forceState = await getListData("forceState", location.host);
  6832. if (typeof(_forceState) == "undefined") {
  6833. _forceState = await getData("forceState_" + location.host);
  6834. }
  6835. if (typeof(_forceState) == "undefined") {
  6836. _forceState = (rulesData.enableWhiteList ? 1 : 0);
  6837. }
  6838. forceState = _forceState;
  6839.  
  6840. autoScroll = await getListData("autoScroll", location.host + location.pathname) || 0;
  6841.  
  6842. updateDate = await getData("ruleLastUpdate");
  6843.  
  6844. let _loadNowNum = await getData("loadNowNum");
  6845. if (typeof(_loadNowNum) != "undefined") {
  6846. loadNowNum = _loadNowNum;
  6847. }
  6848. let _autoScrollRate = await getData("autoScrollRate");
  6849. if (_autoScrollRate) {
  6850. autoScrollRate = _autoScrollRate;
  6851. }
  6852.  
  6853. author = await getData("author") || "";
  6854.  
  6855. manualPause = !!await getListData("pauseState", location.host);
  6856.  
  6857. let href = location.href.slice(0, 100);
  6858. try {
  6859. if (_unsafeWindow.initedPagetual) {
  6860. if (ruleImportUrlReg.test(href)) {
  6861. showTips(i18n('duplicate'));
  6862. }
  6863. return;
  6864. }
  6865. _unsafeWindow.initedPagetual = true;
  6866. } catch(e) {showTips(e)}
  6867. listenUrl();
  6868. _GM_registerMenuCommand(i18n("update"), () => {
  6869. showTips(i18n("beginUpdate"), "", 60000);
  6870. updateRules(() => {
  6871. showTips(i18n("updateSucc"));
  6872. location.reload();
  6873. },(rule, err) => {
  6874. showTips(`Failed to update ${rule.url} rules!`);
  6875. debug(err);
  6876. });
  6877. });
  6878. _GM_registerMenuCommand(i18n(forceState == 1 ? "enable" : "disableSite"), () => {
  6879. if (forceState == 1) {
  6880. forceState = 0;
  6881. showTips(i18n("enableSiteTips"));
  6882. changeStop(false, true);
  6883. } else {
  6884. forceState = 1;
  6885. showTips(i18n("disableSiteTips"));
  6886. changeStop(true, true);
  6887. sideController.remove();
  6888. }
  6889. setListData("forceState", location.host, forceState);
  6890. if (!ruleParser.curSiteRule.url) {
  6891. setTimeout(() => {
  6892. location.reload();
  6893. }, 500);
  6894. }
  6895. });
  6896. _GM_registerMenuCommand(i18n("toggleAutoScroll"), () => {
  6897. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  6898. autoScroll = parseInt(autoScroll) || 0;
  6899. if (autoScroll < 0) autoScroll = 0;
  6900. if (autoScroll && autoScroll != autoScrollRate) {
  6901. autoScrollRate = autoScroll;
  6902. storage.setItem("autoScrollRate", autoScrollRate);
  6903. }
  6904. setListData("autoScroll", location.host + location.pathname, autoScroll);
  6905. startAutoScroll();
  6906. });
  6907. startAutoScroll();
  6908.  
  6909.  
  6910. if (initConfig(href)) return;
  6911. pageReady = true;
  6912. if (forceState == 1) return;
  6913. let now = new Date().getTime();
  6914. if (!updateDate || now - updateDate > 2 * 24 * 60 * 60 * 1000) {
  6915. updateRules(() => {
  6916. }, (rule, err) => {}, true);
  6917. storage.setItem("ruleLastUpdate", now);
  6918. }
  6919. callback();
  6920. });
  6921. });
  6922. }
  6923.  
  6924. function requestDoc(url, callback) {
  6925. let postParams = url.match(/#p{(.*)}$/);
  6926. if (postParams) {
  6927. postParams = postParams[1];
  6928. url = url.replace(/#p{.*/, "");
  6929. }
  6930. let ruleHeaders = ruleParser.curSiteRule.headers;
  6931. let headers = {
  6932. 'Referer': location.href,
  6933. 'User-Agent': navigator.userAgent,
  6934. 'accept': 'text/html,application/xhtml+xml,application/xml',
  6935. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + charset,
  6936. };
  6937. if (ruleHeaders) {
  6938. if (ruleHeaders.referer) {
  6939. headers.referer = ruleHeaders.referer;
  6940. }
  6941. if (ruleHeaders.userAgent) {
  6942. headers.userAgent = ruleHeaders.userAgent;
  6943. }
  6944. if (ruleHeaders.accept) {
  6945. headers.accept = ruleHeaders.accept;
  6946. }
  6947. if (ruleHeaders.contentType) {
  6948. headers.contentType = ruleHeaders.contentType;
  6949. let ruleCharset = ruleHeaders.contentType.match(/charset\=([^;]+)/);
  6950. if (ruleCharset) charset = ruleCharset[1];
  6951. }
  6952. if (ruleHeaders.cookie) {
  6953. headers.cookie = ruleHeaders.cookie;
  6954. }
  6955. }
  6956. _GM_xmlhttpRequest({
  6957. url: url,
  6958. method: postParams ? 'POST' : 'GET',
  6959. data: postParams,
  6960. overrideMimeType: 'text/html;charset=' + charset,
  6961. headers: headers,
  6962. timeout: 50000,
  6963. onload: async function(res) {
  6964. if (isPause) return callback(false);
  6965. var doc = null, response = res.response;
  6966. try {
  6967. doc = document.implementation.createHTMLDocument('');
  6968. doc.documentElement.innerHTML = response;
  6969. } catch (e) {
  6970. debug('parse error:' + e.toString());
  6971. }
  6972. let pageElement = null;
  6973. let preCode = ruleParser.curSiteRule.pagePre;
  6974. if (preCode) {
  6975. try {
  6976. let preResult;
  6977. if (typeof preCode == 'function') {
  6978. preResult = await preCode(response, doc);
  6979. } else if (preCode.length == 2) {
  6980. preResult = response.replace(new RegExp(preCode[0], "gi"), preCode[1]);
  6981. } else {
  6982. preResult = await new AsyncFunction("response", "doc", '"use strict";' + preCode)(response, doc);
  6983. }
  6984. if (preResult) {
  6985. if (typeof preResult === "string") {
  6986. doc.documentElement.innerHTML = preResult;
  6987. } else pageElement = preResult;
  6988. }
  6989. } catch(e) {
  6990. debug(e);
  6991. }
  6992. }
  6993. let base = doc.querySelector("base");
  6994. ruleParser.basePath = base ? base.href : url;
  6995. if (charsetValid && !ruleHeaders) {
  6996. let equiv = doc.querySelector('[http-equiv="Content-Type"]');
  6997. if (equiv && equiv.content) {
  6998. let innerCharSet = equiv.content.match(/charset\=([^;]+)/);
  6999. if (innerCharSet && innerCharSet[1].replace("-", "").toLowerCase() != charset.replace("-", "").toLowerCase()) {
  7000. charset = innerCharSet[1];
  7001. return requestDoc(url, callback);
  7002. }
  7003. }
  7004. }
  7005. if (pageElement === null) {
  7006. pageElement = ruleParser.getPageElement(doc);
  7007. }
  7008. if ((!pageElement || pageElement.length == 0) && res.status >= 400) {
  7009. debug(res.status + " " + url, "Error status");
  7010. return callback(false);
  7011. }
  7012. if (inCors && (!pageElement || pageElement.length == 0) && ruleParser.curSiteRule.smart) {
  7013. let article;
  7014. for (let i = 0; i < mainSel.length; i++) {
  7015. article = doc.querySelectorAll(mainSel[i]);
  7016. if (article && article.length === 1) break;
  7017. }
  7018. if (article && article.length == 1) {
  7019. article = article[0];
  7020. ruleParser.curSiteRule.pageElement = article.nodeName.toLowerCase() + (article.id ? "#" + article.id : "") + (article.className ? "." + article.className.replace(/ /g, ".") : "") + ">*";
  7021. pageElement = article.children;
  7022. } else {
  7023. ruleParser.curSiteRule.pageElement = allOfBody;
  7024. pageElement = ruleParser.getPageElement(doc);
  7025. }
  7026. ruleParser.getInsert(true);
  7027. }
  7028. //只有1的話怕不是圖片哦
  7029. if (pageElement && (pageElement.length > 1 || (pageElement.length == 1 && !compareNodeName(pageElement[0], ["img"])))) {
  7030. await ruleParser.insertPage(doc, pageElement, url, callback, false);
  7031. if (ruleParser.curSiteRule.action == 1) {
  7032. isLoading = true;
  7033. requestFromIframe(url, async (doc, eles) => {
  7034. if (eles) {
  7035. await ruleParser.insertPage(doc, eles, url, callback, true);
  7036. } else isLoading = false;
  7037. });
  7038. } else ruleParser.curSiteRule.action = 0;
  7039. } else if ((ruleParser.curSiteRule.smart || curPage == 1) && !inCors) {
  7040. ruleParser.curSiteRule.action = 1;
  7041. requestFromIframe(url, async (doc, eles) => {
  7042. if (eles) {
  7043. await ruleParser.insertPage(doc, eles, url, callback, true);
  7044. } else isLoading = false;
  7045. });
  7046. } else {
  7047. debug("Stop as no page element");
  7048. ruleParser.noValidContent(url);
  7049. changeStop(true);
  7050. callback(false);
  7051. }
  7052. },
  7053. onerror: function(e) {
  7054. debug(e, "NetError");
  7055. callback(false);
  7056. },
  7057. ontimeout: function(e) {
  7058. debug(e, "NetTimeout");
  7059. callback(false);
  7060. }
  7061. });
  7062. }
  7063.  
  7064. function initPage() {
  7065. ruleParser.initPage(() => {
  7066. if (ruleParser.curSiteRule.autoLoadNum) {
  7067. autoLoadNum = ruleParser.curSiteRule.autoLoadNum;
  7068. }
  7069. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  7070. _GM_registerMenuCommand(i18n("nextSwitch"), () => {
  7071. nextSwitch.start();
  7072. });
  7073. }
  7074. if (ruleParser.nextLinkHref) {
  7075. let isJs = ruleParser.hrefIsJs(ruleParser.nextLinkHref);
  7076. if (!isJs) {
  7077. let inForce = (forceState == 2 || forceState == 3);
  7078. _GM_registerMenuCommand(i18n(inForce ? "cancelForceIframe" : "forceIframe"), () => {
  7079. if (inForce) {
  7080. setListData("forceState", location.host, "");
  7081. } else {
  7082. let _state = ruleParser.curSiteRule.action > 0 || confirm(i18n("forceAllBody")) ? 2 : 3;
  7083. setListData("forceState", location.host, _state);
  7084. }
  7085. setTimeout(() => {
  7086. location.reload();
  7087. }, 500);
  7088. });
  7089. }
  7090. _GM_registerMenuCommand(i18n("loadNow"), () => {
  7091. if (autoLoadNum != -1) {
  7092. autoLoadNum = -1;
  7093. return;
  7094. }
  7095. let loadNum = window.prompt(i18n("loadConfirm"), loadNowNum);
  7096. if (loadNum === "" || loadNum === null) return;
  7097. loadNum = Math.abs(parseInt(loadNum)) || 0;
  7098. if (loadNowNum != loadNum) {
  7099. loadNowNum = loadNum;
  7100. storage.setItem("loadNowNum", loadNowNum);
  7101. }
  7102. autoLoadNum = loadNum;
  7103. nextPage();
  7104. });
  7105. }
  7106. initListener();
  7107. });
  7108. }
  7109.  
  7110. var pageBarStyle, mainStyleEle, mainStyleStyle;
  7111. function initView() {
  7112. if (!mainStyleStyle) {
  7113. mainStyleStyle = `
  7114. .pagetual_pageBar{
  7115. -moz-transition:all 0.3s ease-in-out 0s;
  7116. -webkit-transition:all 0.3s ease-in-out 0s;
  7117. transition:all 0.3s ease-in-out 0s;
  7118. font-family: Arial,sans-serif !important;
  7119. text-align: center !important;
  7120. }
  7121. .pagetual_pageBar.stop {
  7122. -webkit-filter: invert(100%);
  7123. filter: invert(100%);
  7124. opacity: 1!important;
  7125. }
  7126. .pagetual_pageBar.hide {
  7127. display: none!important;
  7128. }
  7129. .pagetual-hide {
  7130. display: none!important;
  7131. }
  7132. .pagetual_pageBar:hover {
  7133. opacity: 1!important;
  7134. box-shadow: 0px 0px 10px 0px #000000aa;
  7135. border-radius: 20px;
  7136. background-color: rgb(240 240 240 / 80%);
  7137. border-color: transparent!important;
  7138. }
  7139. .pagetual_pageBar span {
  7140. vertical-align: super;
  7141. }
  7142. .pagetual_pageBar a::before,
  7143. .pagetual_pageBar a::after {
  7144. content: none;
  7145. }
  7146. .pagetual_pageBar a>span {
  7147. margin-top: 0!important;
  7148. pointer-events: none;
  7149. padding: unset;
  7150. opacity: 0;
  7151. -moz-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  7152. -webkit-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  7153. transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  7154. transform: none;
  7155. left: 0;
  7156. margin-left: calc(50% - 20px);
  7157. }
  7158. .pagetual_pageBar a>span:hover {
  7159. color: red;
  7160. }
  7161. .pagetual_pageBar a:hover>span {
  7162. opacity: 1!important;
  7163. }
  7164. .pagetual_pageBar span.prevScreen,
  7165. .pagetual_pageBar span.nextScreen {
  7166. display: block!important;
  7167. top: unset !important;
  7168. padding: unset !important;
  7169. opacity: 0!important;
  7170. }
  7171. .pagetual_pageBar a:hover>span.prevScreen {
  7172. margin-top: -${rulesData.opacity == 1 ? 31 : 30}px!important;
  7173. pointer-events: all;
  7174. }
  7175. .pagetual_pageBar span.refreshRing {
  7176. position: absolute;
  7177. top: 0;
  7178. opacity: 0;
  7179. height: 30px;
  7180. margin-left: calc(50% - 23px);
  7181. display: block!important;
  7182. }
  7183. .pagetual_pageBar span.refreshRing>svg {
  7184. background: white;
  7185. border-radius: 50%;
  7186. }
  7187. .pagetual_pageBar a:hover>span.refreshRing {
  7188. opacity: 0.3;
  7189. -webkit-animation: pagetual_ring 2.0s infinite linear;
  7190. animation: pagetual_ring 2.0s infinite linear;
  7191. }
  7192. @-webkit-keyframes pagetual_ring {
  7193. 0% { -webkit-transform: rotate(0deg) }
  7194. 100% {
  7195. -webkit-transform: rotate(360deg);
  7196. }
  7197. }
  7198. @keyframes pagetual_ring {
  7199. 0% {
  7200. transform: rotate(0deg);
  7201. -webkit-transform: rotate(0deg);
  7202. } 100% {
  7203. transform: rotate(360deg);
  7204. -webkit-transform: rotate(360deg);
  7205. }
  7206. }
  7207. .pagetual_pageBar a:hover>span.nextScreen {
  7208. margin-top: 30px!important;
  7209. pointer-events: all;
  7210. }
  7211. .pagetual_pageBar span>svg {
  7212. -moz-transition:transform 0.5s ease, opacity 0.3s ease;
  7213. -webkit-transition:transform 0.5s ease, opacity 0.3s ease;
  7214. transition:transform 0.5 ease, opacity 0.3s ease;
  7215. opacity: 0;
  7216. }
  7217. .pagetual_pageBar.stop span>svg{
  7218. opacity: 1;
  7219. }
  7220. .pagetual_pageBar.stop span>svg>path{
  7221. transform: scale(.8);
  7222. transform-origin: center;
  7223. -moz-transition:transform 0.3s ease;
  7224. -webkit-transition:transform 0.3s ease;
  7225. transition:transform 0.3 ease;
  7226. }
  7227. .pagetual_pageBar.stop:hover span>svg>path{
  7228. transform: unset;
  7229. }
  7230. .pagetual_pageBar:hover span>svg {
  7231. opacity: 1;
  7232. }
  7233. .pagetual_pageBar span>svg.upSvg:hover {
  7234. transform: rotate(360deg) scale3d(1.2, 1.2, 1.2);
  7235. }
  7236. .pagetual_pageBar span>svg.downSvg:hover {
  7237. transform: rotate(540deg) scale3d(1.2, 1.2, 1.2)!important;
  7238. }
  7239. .pagetual_pageBar .pagetual_pageNum{
  7240. color: #55555f;
  7241. }
  7242. .pagetual_pageBar .pagetual_pageNum:hover{
  7243. color: #ff6464;
  7244. }
  7245. .pagetual_tipsWords {
  7246. font-size: 50px;
  7247. font-weight: bold;
  7248. font-family: "黑体", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
  7249. "Oxygen", "Ubuntu", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
  7250. "Segoe UI Emoji", "Segoe UI Symbol";
  7251. color: #ffffff;
  7252. min-height: 70px;
  7253. max-width: 80%;
  7254. line-height: 1.5;
  7255. position: fixed;
  7256. left: 50%;
  7257. top: 10%;
  7258. margin-left: -99999px;
  7259. padding: 0 15px;
  7260. z-index: 2147483647;
  7261. background-color: #000;
  7262. border: 1px solid #303030;
  7263. border-radius: 10px;
  7264. opacity: 0;
  7265. filter: alpha(opacity=65);
  7266. box-shadow: 5px 5px 20px 0px #000;
  7267. -moz-transition:opacity 0.3s ease-in-out 0s;
  7268. -webkit-transition:opacity 0.3s ease-in-out 0s;
  7269. transition:opacity 0.3s ease-in-out 0s;
  7270. pointer-events: none;
  7271. word-break: break-all;
  7272. }
  7273. .pagetual_tipsWords>a {
  7274. color: #ffffff;
  7275. }
  7276. .pagetual_loading {
  7277. width: 50px;
  7278. height: 50px;
  7279. margin: 10px auto;
  7280. border-radius: 100%;
  7281. display: flex;
  7282. -webkit-animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  7283. animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  7284. }
  7285. @-webkit-keyframes pagetual_loading_scaleout {
  7286. 0% { -webkit-transform: scale(0.0) }
  7287. 100% {
  7288. -webkit-transform: scale(1.0);
  7289. opacity: 0;
  7290. }
  7291. }
  7292. @keyframes pagetual_loading_scaleout {
  7293. 0% {
  7294. transform: scale(0.0);
  7295. -webkit-transform: scale(0.0);
  7296. } 100% {
  7297. transform: scale(1.0);
  7298. -webkit-transform: scale(1.0);
  7299. opacity: 0;
  7300. }
  7301. }
  7302. .pagetual_loading_text {
  7303. white-space: nowrap;
  7304. -webkit-animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  7305. animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  7306. }
  7307. @-webkit-keyframes pagetual_loading_opacity {
  7308. 0% { opacity: 1 }
  7309. 50% { opacity: 0.2 }
  7310. 100% { opacity: 1 }
  7311. }
  7312. @keyframes pagetual_loading_opacity {
  7313. 0% { opacity: 1 }
  7314. 50% { opacity: 0.2 }
  7315. 100% { opacity: 1 }
  7316. }
  7317. `;
  7318. 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%);"}`;
  7319. }
  7320. if (!mainStyleEle || !mainStyleEle.parentNode) {
  7321. mainStyleEle = _GM_addStyle(mainStyleStyle);
  7322. }
  7323. }
  7324. var loadingDiv = document.createElement("div");
  7325. 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;";
  7326.  
  7327. 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;`;
  7328. function setLoadingDiv(loadingText) {
  7329. 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>`}`);
  7330. }
  7331.  
  7332. 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>`;
  7333. 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;`;
  7334. 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>`;
  7335. 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);`;
  7336.  
  7337. 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;`;
  7338. 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;`;
  7339. var sideControllerIcon = '';
  7340.  
  7341. var tipsWords = document.createElement("div");
  7342. tipsWords.className = "pagetual_tipsWords";
  7343.  
  7344. function changeStop(stop, save) {
  7345. isPause = stop;
  7346. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar,#pagetual-sideController"), bar => {
  7347. if (isPause) {
  7348. bar.classList.add("stop");
  7349. } else {
  7350. bar.classList.remove("stop");
  7351. }
  7352. });
  7353. if (!isPause) ruleParser.showAddedElements();
  7354. manualPause = isPause;
  7355. if (save && sideController.inited) setListData("pauseState", location.host, isPause ? true : "");
  7356. }
  7357.  
  7358. function changeHideBar(hide) {
  7359. isHideBar = hide;
  7360. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar"), bar => {
  7361. if (isHideBar) {
  7362. bar.classList.add("hide");
  7363. } else {
  7364. bar.classList.remove("hide");
  7365. }
  7366. });
  7367. }
  7368.  
  7369. function isInViewPort(element) {
  7370. if (!getBody(document).contains(element)) return false;
  7371. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  7372. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  7373. const {
  7374. top,
  7375. right,
  7376. bottom,
  7377. left,
  7378. } = element.getBoundingClientRect();
  7379.  
  7380. return (
  7381. top >= 0 &&
  7382. left >= 0 &&
  7383. right <= viewWidth + 1 &&
  7384. top <= viewHeight * rate &&
  7385. isVisible(element, _unsafeWindow)
  7386. );
  7387. }
  7388.  
  7389. function getPageBar() {
  7390. let preBar = null, nextBar = null;
  7391. let pageBars = [].slice.call(document.querySelectorAll(".pagetual_pageBar"));
  7392. for (let i = 0; i < pageBars.length; i++) {
  7393. let pageBar = pageBars[i];
  7394. if (!pageBar || !getBody(document).contains(pageBar)) continue;
  7395. let {
  7396. top,
  7397. right,
  7398. bottom,
  7399. left,
  7400. } = pageBar.getBoundingClientRect();
  7401. if (top > 500) {
  7402. nextBar = pageBar;
  7403. preBar = (i - 1 >= 0 ? pageBars[i - 1] : null);
  7404. if (pageBar && getBody(document).contains(pageBar)) {
  7405. let {
  7406. top,
  7407. right,
  7408. bottom,
  7409. left,
  7410. } = pageBar.getBoundingClientRect();
  7411. if (top < -500) {
  7412. preBar = pageBar;
  7413. } else preBar = (i - 2 >= 0 ? pageBars[i - 2] : null);
  7414. }
  7415. break;
  7416. }
  7417. }
  7418. if (!nextBar) preBar = pageBars[pageBars.length - 2];
  7419. return {preBar: preBar, nextBar: nextBar};
  7420. }
  7421.  
  7422. var urlChanged = false;
  7423. var urlChanging = false;
  7424. var urlchangeHandler = e => {
  7425. if (ruleParser && ruleParser.curSiteRule && ruleParser.curSiteRule.listenUrlChange == false) return;
  7426. isPause = true;
  7427. setTimeout(() => {
  7428. lastActiveUrl = location.href;
  7429. if (urlChanging) return;
  7430. urlChanging = true;
  7431. let href = location.href.slice(0, 60);
  7432. if (href == configPage[1]) {
  7433. setTimeout(() => {
  7434. initConfig(href);
  7435. urlChanging = false;
  7436. }, 1000);
  7437. } else {
  7438. setTimeout(() => {
  7439. if (guidePage.test(href)) {
  7440. setTimeout(() => {
  7441. initConfig(href);
  7442. urlChanging = false;
  7443. }, 1000);
  7444. } else {
  7445. ruleParser.urlChanged();
  7446. if (!ruleParser.nextLinkHref) {
  7447. isLoading = false;
  7448. }
  7449. urlChanging = false;
  7450. //if (!pageReady && !ruleImportUrlReg.test(href)) location.reload();
  7451. }
  7452. }, 500);
  7453. }
  7454. }, 1);
  7455. };
  7456. window.addEventListener('pagetual_pushState', urlchangeHandler);
  7457. /*var _wr = function(type) {
  7458. var orig = history[type];
  7459. return function() {
  7460. var rv = orig.apply(this, arguments);
  7461. var e = new Event('pagetual_' + type);
  7462. e.arguments = arguments;
  7463. window.dispatchEvent(e);
  7464. return rv;
  7465. };
  7466. };
  7467. history.pushState = _wr('pushState');*/
  7468.  
  7469. function listenUrl() {
  7470. var prevPathname = window.location.pathname;
  7471. var prevSearch = window.location.search;
  7472. var checkUrlTime = 100;
  7473. var checkUrlTimer;
  7474. var checkClickedEle = null;
  7475. var checkFunc = () => {
  7476. if (forceState == 1) return;
  7477. if (checkClickedEle) {
  7478. if (!clickedSth && checkClickedEle && checkClickedEle.nodeName) {
  7479. if (compareNodeName(checkClickedEle, ["a", "button"])) {
  7480. clickedSth = true;
  7481. } else {
  7482. let targetStyle = _unsafeWindow.getComputedStyle(checkClickedEle);
  7483. if (targetStyle.cursor == "pointer") clickedSth = true;
  7484. }
  7485. }
  7486. checkClickedEle = null;
  7487. }
  7488. if (checkUrlTime < 5000) {
  7489. checkUrlTime += checkUrlTime>>1;
  7490. }
  7491. clearTimeout(checkUrlTimer);
  7492. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7493. if (document.hidden) return;
  7494. if (!ruleParser.canListenUrlChange()) {
  7495. return;
  7496. }
  7497. if ((prevPathname !== window.location.pathname || prevSearch !== window.location.search) && window.location.href != ruleParser.historyUrl) {
  7498. checkUrlTime = 2000;
  7499. urlWillChange = true;
  7500. var e = new Event('pagetual_pushState');
  7501. e.arguments = arguments;
  7502. window.dispatchEvent(e);
  7503. clickedSth = false;
  7504. }
  7505. prevPathname = window.location.pathname;
  7506. prevSearch = window.location.search;
  7507. };
  7508. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7509.  
  7510. document.addEventListener("click", e => {
  7511. if (!checkClickedEle) {
  7512. checkClickedEle = e.target;
  7513. checkUrlTime = 300;
  7514. clearTimeout(checkUrlTimer);
  7515. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7516. }
  7517. });
  7518. }
  7519.  
  7520. let scrollContainer;
  7521. function distToBottom () {
  7522. let scrolly = window.scrollY;
  7523. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  7524. if (!scrollContainer || !document.documentElement.contains(scrollContainer)) {
  7525. if (curPage > 1 || ruleParser.nextLinkHref) {
  7526. let pageEle = ruleParser.getPageElement(document);
  7527. if (pageEle && pageEle.length) {
  7528. let parent = pageEle[0].parentNode, pageScrollY = parent.scrollTop;
  7529. while (parent && pageScrollY == 0) {
  7530. parent = parent.parentNode;
  7531. pageScrollY = parent.scrollTop;
  7532. }
  7533. if (pageScrollY) {
  7534. scrollContainer = parent;
  7535. return scrollContainer.scrollHeight - pageScrollY - windowHeight;
  7536. }
  7537. }
  7538. }
  7539. }
  7540. if (scrollContainer) {
  7541. return scrollContainer.scrollHeight - scrollContainer.scrollTop - windowHeight;
  7542. }
  7543.  
  7544. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7545. return scrollH - scrolly - windowHeight;
  7546. }
  7547.  
  7548. let scrollHandler, clickToResetHandler, dblclickHandler, keydownHandler, hashchangeHandler, manualModeKeyHandler, pagetualNextHandler, keyupHandler, messageHandler;
  7549. function initListener () {
  7550. document.removeEventListener('scroll', scrollHandler, true);
  7551. document.removeEventListener('wheel', scrollHandler, true);
  7552. document.removeEventListener('dblclick', dblclickHandler);
  7553. document.removeEventListener('keydown', keydownHandler);
  7554. window.removeEventListener('hashchange', hashchangeHandler, false);
  7555. document.removeEventListener('keydown', manualModeKeyHandler);
  7556. document.removeEventListener('pagetual.next', pagetualNextHandler, false);
  7557. document.removeEventListener('keyup', keyupHandler);
  7558. _unsafeWindow.removeEventListener('message', messageHandler, true);
  7559. let loadmoreBtn, loadingMore = true, lastScroll = 0, checkLoadMoreTimes = 0, loadMoreInv;
  7560. if (ruleParser.curSiteRule.smart) {
  7561. loadingMore = false;
  7562. } else if (ruleParser.curSiteRule.loadMore) {
  7563. loadingMore = false;
  7564. }
  7565. clickMode = typeof ruleParser.curSiteRule.clickMode == 'undefined' ? rulesData.clickMode : ruleParser.curSiteRule.clickMode;
  7566. let clickingNext = false;
  7567. let clickNext = async () => {
  7568. if (clickingNext) return;
  7569. clickingNext = true;
  7570. setTimeout(() => {
  7571. clickingNext = false;
  7572. }, 1500);
  7573. let nextLink = ruleParser.nextLinkHref;
  7574. if (!nextLink) return;
  7575. let isJs = ruleParser.hrefIsJs(nextLink);
  7576. if (isJs) {
  7577. let nextBtn = ruleParser.nextLinkEle;
  7578. if (!nextBtn || !nextBtn.offsetParent) nextBtn = await ruleParser.getNextLink(document, true);
  7579. if (nextBtn) emuClick(nextBtn);
  7580. } else {
  7581. window.location.href = nextLink;
  7582. }
  7583. };
  7584. let checkScrollReach = () => {
  7585. let dist = distToBottom();
  7586. if (clickMode) {
  7587. if (dist < 10) {
  7588. clickNext();
  7589. }
  7590. } else if (dist < bottomGap) {
  7591. nextPage();
  7592. }
  7593. };
  7594. messageHandler = e => {
  7595. if (e.data.command === 'pagetual') {
  7596. let action = e.data.action;
  7597. let detail = e.data.detail;
  7598. switch (action) {
  7599. case "config":
  7600. if (!detail || typeof detail !== 'object') return;
  7601. rulesData = {
  7602. ...rulesData,
  7603. ...detail
  7604. }
  7605. storage.setItem("rulesData", rulesData);
  7606. break;
  7607. case "nextPage":
  7608. if (detail === "" || detail === null) return;
  7609. detail = parseInt(detail) || 0;
  7610. if (loadNowNum != detail) {
  7611. loadNowNum = detail;
  7612. }
  7613. autoLoadNum = detail;
  7614. nextPage();
  7615. break;
  7616. case "loadMore":
  7617. clearInterval(loadMoreInv);
  7618. if (detail === -1) return;
  7619. loadmoreBtn = getLoadMore(document, loadmoreBtn);
  7620. loadmoreBtn && emuClick(loadmoreBtn);
  7621. if (detail === 0) {
  7622. loadMoreInv = setInterval(() => {
  7623. loadmoreBtn = getLoadMore(document, loadmoreBtn);
  7624. loadmoreBtn && emuClick(loadmoreBtn);
  7625. }, 500);
  7626. }
  7627. break;
  7628. }
  7629. }
  7630. return true;
  7631. }
  7632. _unsafeWindow.addEventListener('message', messageHandler, true);
  7633. scrollHandler = e => {
  7634. if (urlChanged && !isLoading) {
  7635. ruleParser.initPage(() => {});
  7636. urlChanged = false;
  7637. loadingMore = false;
  7638. return;
  7639. }
  7640. if (isPause) return;
  7641. if (!loadingMore) {
  7642. loadmoreBtn = getLoadMore(document, loadmoreBtn);
  7643. if (loadmoreBtn) {
  7644. if (isInViewPort(loadmoreBtn)) {
  7645. emuClick(loadmoreBtn);
  7646. loadingMore = true;
  7647. setTimeout(() => {loadingMore = false}, 200);
  7648. }
  7649. } else {
  7650. loadingMore = true;
  7651. if (!ruleParser.curSiteRule.smart || checkLoadMoreTimes++ < 3) {
  7652. setTimeout(() => {loadingMore = false}, 200);
  7653. }
  7654. }
  7655. }
  7656. if (!isLoading && !stopScroll) {
  7657. checkScrollReach();
  7658. }
  7659. ruleParser.changeVisibility();
  7660. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  7661. if (ruleParser.curSiteRule.lockScroll) {
  7662. if (isLoading && Math.abs(lastScroll - curScroll) > 350) {
  7663. getBody(document).scrollTop = lastScroll;
  7664. document.documentElement.scrollTop = lastScroll;
  7665. } else {
  7666. lastScroll = curScroll;
  7667. }
  7668. }
  7669. if (targetY >= 0) {
  7670. if (Math.abs(targetY - curScroll) < 100) {
  7671. targetY = -1;
  7672. }
  7673. }
  7674. };
  7675. dblclickHandler = e => {
  7676. if (forceState == 1 || compareNodeName(e.target, ["input", "textarea", "select", "a", "button", "svg", "use", "img", "path"])) return;
  7677. if (!rulesData.dbClick2StopKey) {
  7678. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  7679. (rulesData.dbClick2StopAlt && !e.altKey) ||
  7680. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  7681. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  7682. return;
  7683. }
  7684. }
  7685. if (!compareNodeName(e.target, ["body"]) && !e.target.classList.contains('pagetual_pageBar')) {
  7686. try {
  7687. let selection = window.getSelection();
  7688. let selStr = selection.toString().trim();
  7689. if (!selStr) {
  7690. selection = selection.getRangeAt(0);
  7691. selStr = selection && selection.cloneContents().children[0];
  7692. if (selStr && !compareNodeName(selStr, ["img"])) selStr = false;
  7693. }
  7694. if (selStr) {
  7695. return;
  7696. }
  7697. } catch (e) {}
  7698. }
  7699. if (rulesData.dbClick2Stop && (ruleParser.nextLinkHref || loadmoreBtn)) {
  7700. setTimeout(() => {
  7701. if (rulesData.hideBarButNoStop || rulesData.hideBar) {
  7702. changeHideBar(!isHideBar);
  7703. }
  7704. if (!rulesData.hideBarButNoStop) {
  7705. changeStop(!isPause, true);
  7706. showTips(i18n(isPause ? "disable" : "enable"));
  7707. }
  7708. if (!isPause) {
  7709. checkScrollReach();
  7710. }
  7711. }, 10);
  7712. }
  7713. };
  7714. document.addEventListener('dblclick', dblclickHandler);
  7715. clickToResetHandler = e => {
  7716. if (!ruleParser.nextLinkHref) isLoading = false;
  7717. };
  7718. document.addEventListener('click', clickToResetHandler);
  7719. if (rulesData.dbClick2StopKey) {
  7720. keydownHandler = e => {
  7721. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  7722. (rulesData.dbClick2StopAlt && !e.altKey) ||
  7723. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  7724. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  7725. return;
  7726. }
  7727. if (document.activeElement &&
  7728. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  7729. document.activeElement.contentEditable == 'true')) {
  7730. return;
  7731. }
  7732. var key = e.key.toLowerCase();
  7733. if (rulesData.dbClick2StopKey.toLowerCase() == key) {
  7734. if (forceState == 1) {
  7735. forceState = 0;
  7736. showTips(i18n("enableSiteTips"));
  7737. changeStop(false, true);
  7738. } else {
  7739. forceState = 1;
  7740. showTips(i18n("disableSiteTips"));
  7741. changeStop(true, true);
  7742. sideController.remove();
  7743. }
  7744. if (!ruleParser.curSiteRule.url) {
  7745. setListData("forceState", location.host, forceState);
  7746. setTimeout(() => {
  7747. location.reload();
  7748. }, 500);
  7749. }
  7750. }
  7751. };
  7752. document.addEventListener('keydown', keydownHandler);
  7753. }
  7754. if (ruleParser.curSiteRule.listenHashChange) {
  7755. hashchangeHandler = () => {
  7756. isPause = true;
  7757. ruleParser.urlChanged();
  7758. if (!ruleParser.nextLinkHref) isLoading = false;
  7759. };
  7760. window.addEventListener('hashchange', hashchangeHandler, false);
  7761. }
  7762. let manualMode = typeof ruleParser.curSiteRule.manualMode == 'undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode;
  7763. if (manualMode) {
  7764. manualModeKeyHandler = e => {
  7765. if (document.activeElement &&
  7766. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  7767. document.activeElement.contentEditable == 'true')) {
  7768. return;
  7769. }
  7770. if (e.keyCode == 39) {
  7771. clickNext();
  7772. } else if (e.keyCode == 37) {
  7773. history.back();
  7774. }
  7775. };
  7776. document.addEventListener('keydown', manualModeKeyHandler);
  7777. pagetualNextHandler = () => {
  7778. clickNext();
  7779. };
  7780. document.addEventListener('pagetual.next', pagetualNextHandler, false);
  7781. return;
  7782. }
  7783. if (rulesData.arrowToScroll) {
  7784. keyupHandler = e => {
  7785. if (document.activeElement &&
  7786. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  7787. document.activeElement.contentEditable == 'true')) {
  7788. return;
  7789. }
  7790. if (e.keyCode == 39) {
  7791. let nextPageBar=getPageBar().nextBar;
  7792. if (nextPageBar) {
  7793. scrollToPageBar(nextPageBar);
  7794. } else {
  7795. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  7796. window.scrollTo({ top: scrollTop + (window.innerHeight || document.documentElement.clientHeight), behavior: 'instant'});
  7797. }
  7798. } else if (e.keyCode == 37) {
  7799. let prePageBar = getPageBar().preBar;
  7800. if (prePageBar) {
  7801. scrollToPageBar(prePageBar);
  7802. } else {
  7803. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  7804. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'instant'});
  7805. }
  7806. }
  7807. };
  7808. document.addEventListener('keyup', keyupHandler);
  7809. }
  7810. if (!ruleParser.curSiteRule.wheel) {
  7811. document.addEventListener('scroll', scrollHandler, true);
  7812. }
  7813. document.addEventListener('wheel', scrollHandler, true);
  7814. }
  7815.  
  7816. let hideTipsTimeout;
  7817. function showTips(content, href, time, wordColor, backColor) {
  7818. initView();
  7819. document.documentElement.appendChild(tipsWords);
  7820. tipsWords.style.color = wordColor || 0xFFFFFF;
  7821. tipsWords.style.backgroundColor = backColor || 0x000;
  7822. let _time = 1500;
  7823. if (href) {
  7824. _time = 3500;
  7825. tipsWords.innerHTML = createHTML(`<a href='${href}' target='_blank'>${content}</a>`);
  7826. tipsWords.style.pointerEvents = 'all';
  7827. } else {
  7828. tipsWords.innerHTML = createHTML(content);
  7829. }
  7830. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  7831. setTimeout(() => {
  7832. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  7833. }, 0);
  7834. setTimeout(() => {
  7835. tipsWords.style.opacity = 0.8;
  7836. clearTimeout(hideTipsTimeout);
  7837. hideTipsTimeout = setTimeout(() => {
  7838. tipsWords.style.opacity = 0;
  7839. tipsWords.style.pointerEvents = '';
  7840. }, time || _time);
  7841. }, 1);
  7842. }
  7843.  
  7844. const loadmoreReg = /^\s*((点击)?加载更多|(點擊)?加載更多|(load|view)\s*more|もっと読み込む)[.…▼\s]*$/i;
  7845. 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";
  7846. function getLoadMore(doc, loadmoreBtn) {
  7847. if (!loadmoreBtn || !getBody(doc).contains(loadmoreBtn) || /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  7848. if (!ruleParser.curSiteRule.smart && !ruleParser.curSiteRule.loadMore) return null;
  7849. if (loadmoreBtn) return loadmoreBtn;
  7850. let btnSel = ruleParser.curSiteRule.loadMore || defaultLoadmoreSel;
  7851. if (btnSel) {
  7852. loadmoreBtn = getElement(btnSel, doc, null, true);
  7853. }
  7854. if (!loadmoreBtn) {
  7855. let buttons = doc.querySelectorAll("input,button,a,div[onclick]");
  7856. for (let i = 0; i < buttons.length; i++) {
  7857. let button = buttons[i];
  7858. if (!button.innerText || button.innerText.length > 20) continue;
  7859. if (button && loadmoreReg.test(button.innerText)) {
  7860. loadmoreBtn = button;
  7861. break;
  7862. }
  7863. }
  7864. }
  7865. if (loadmoreBtn && !ruleParser.curSiteRule.loadMore && loadmoreBtn.dataset.ajax !== "true") {
  7866. let href = loadmoreBtn.getAttribute("href");
  7867. if (href && href != "/" && !ruleParser.hrefIsJs(href)) {
  7868. loadmoreBtn = null;
  7869. }
  7870. }
  7871. if (loadmoreBtn && /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  7872. if (loadmoreBtn) debug(loadmoreBtn, 'Load more button');
  7873. return loadmoreBtn;
  7874. }
  7875.  
  7876. var targetY = -1;
  7877. function scrollToPageBar(bar) {
  7878. if (window.pageYOffset == 0) {
  7879. bar.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" });
  7880. } else {
  7881. let yOffset = -20;
  7882. if (typeof ruleParser.curSiteRule.pageBarTop !== 'undefined') {
  7883. yOffset = -ruleParser.curSiteRule.pageBarTop;
  7884. }
  7885. targetY = bar.getBoundingClientRect().top + window.pageYOffset + yOffset;
  7886. window.scrollTo({ top: targetY, behavior: 'smooth'});
  7887. }
  7888. }
  7889.  
  7890. const pageNumReg=/[&\/\?](p=|page[=\/_-]?)\d+|[_-]\d+\./;
  7891. function createPageBar(url) {
  7892. curPage++;
  7893. sideController.setup();
  7894. let posEle = null;
  7895. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7896. let insert = ruleParser.getInsert();
  7897. if (!insert || !insert.parentNode) return;
  7898. if (forceState == 2) {
  7899. posEle = getBody(document);
  7900. posEle = posEle.children[posEle.children.length - 1];
  7901. } else {
  7902. posEle = insert;
  7903. }
  7904. while (posEle && !posEle.offsetParent) {
  7905. posEle = posEle.previousElementSibling || posEle.parentNode;
  7906. }
  7907. if (posEle) {
  7908. let actualBottom = getElementBottom(posEle);
  7909. bottomGap = scrollH - actualBottom + (window.innerHeight || document.documentElement.clientHeight) * rate;
  7910. if (bottomGap < 100) bottomGap = 100;
  7911. } else {
  7912. bottomGap = 1000;
  7913. }
  7914. if (rulesData.opacity == 0 || ruleParser.curSiteRule.pageBar === 0) return null;
  7915. url = url.replace(/#p{.*/, "");
  7916. let example = (ruleParser.curSiteRule.insertPos == 2 || ruleParser.curSiteRule.insertPos == "in") ? insert.children[0] : (insert.parentNode.children[0] || insert);
  7917. while (example && (compareNodeName(example, ["script", "style"]) || example.className == "pagetual_pageBar")) {
  7918. example = example.nextElementSibling;
  7919. }
  7920. if (!example || !example.parentNode) example = insert;
  7921. if (example.nodeType != 1) {
  7922. example = example.previousElementSibling || example.parentNode;
  7923. if (!example || example.nodeType != 1) return;
  7924. }
  7925. let exampleStyle = _unsafeWindow.getComputedStyle(example);
  7926. let inTable, inLi;
  7927. if (forceState == 2) {
  7928. inTable = inLi = false;
  7929. } else {
  7930. inTable = compareNodeName(example.parentNode, ["table", "tbody"]) ||
  7931. compareNodeName(example, ["tr", "tbody"]) ||
  7932. exampleStyle.display == "table-row" ||
  7933. (example.nextElementSibling && compareNodeName(example.nextElementSibling, ["tr", "tbody"]));
  7934. inLi = compareNodeName(example, ["li"]) || (example.nextElementSibling && compareNodeName(example.nextElementSibling, ["li"]));
  7935. }
  7936. let pageBar = document.createElement(inTable ? "tr" : (inLi ? "li" : "div"));
  7937. let upSpan = document.createElement("span");
  7938. let downSpan = document.createElement("span");
  7939. let pageText = document.createElement("a");
  7940. let pageNum;
  7941. pageBar.className = isHideBar ? "pagetual_pageBar hide" : "pagetual_pageBar";
  7942. pageBar.id = "pagetual_pageBar" + curPage;
  7943. pageBar.setAttribute("translate", "no");
  7944. if (isPause) {
  7945. pageBar.classList.add("stop");
  7946. }
  7947. pageBar.style.cssText = pageBarStyle;
  7948. pageBar.title = i18n(isPause ? "enable" : "disable");
  7949. upSpan.innerHTML = createHTML(upSvg);
  7950. upSpan.children[0].style.cssText = upSvgCSS;
  7951. upSpan.title = i18n("toTop");
  7952. downSpan.innerHTML = createHTML(downSvg);
  7953. downSpan.children[0].style.cssText = downSvgCSS;
  7954. downSpan.title = i18n("toBottom");
  7955. upSpan.style.cssText = initStyle;
  7956. downSpan.style.cssText = initStyle;
  7957. pageText.href = url;
  7958. pageText.style.cssText = pageTextStyle;
  7959. pageText.title = i18n("current");
  7960. if (openInNewTab == 1) pageText.target = "_blank";
  7961. pageBar.appendChild(upSpan);
  7962. pageBar.appendChild(pageText);
  7963. let touched = false;
  7964. let touchBodyHandler = e => {
  7965. touched = false;
  7966. getBody(document).removeEventListener('touchstart', touchBodyHandler, { passive: false, capture: false });
  7967. };
  7968. pageText.addEventListener("touchstart", e => {
  7969. if (touched) return;
  7970. touched = true;
  7971. pageText.style.pointerEvents = 'none';
  7972. setTimeout(() => {
  7973. pageText.style.pointerEvents = 'all';
  7974. }, 250);
  7975. getBody(document).addEventListener("touchstart", touchBodyHandler, { passive: false, capture: false });
  7976. }, { passive: false, capture: false });
  7977. if (ruleParser.nextTitle) {
  7978. pageText.innerHTML = createHTML(ruleParser.nextTitle + " ");
  7979. pageText.title = ruleParser.nextTitle;
  7980. }
  7981. if (ruleParser.curSiteRule.pageNum || pageNumReg.test(url)) {
  7982. pageText.innerHTML = createHTML(pageText.innerHTML + i18n("page"));
  7983. pageNum = document.createElement("span");
  7984. let num = ruleParser.getPageNumFromUrl(url, curPage);
  7985. pageNum.innerHTML = createHTML(num + "<i style='font-size: 0;'>&nbsp;</i>");
  7986. pageNum.className = "pagetual_pageNum";
  7987. pageNum.title = i18n("inputPageNum");
  7988. pageNum.style.cssText = pageTextStyle;
  7989. pageNum.style.cursor = "pointer";
  7990. pageNum.style.color = "";
  7991. pageNum.style.marginLeft = "5px";
  7992. pageNum.addEventListener("click", e => {
  7993. let pageInput = prompt(i18n("inputPageNum"), num || "1");
  7994. if (pageInput) {
  7995. let localPageBar = document.querySelector("#pagetual_pageBar" + pageInput);
  7996. if (localPageBar) {
  7997. scrollToPageBar(localPageBar);
  7998. } else {
  7999. let pageLink = ruleParser.getLinkByPage(url, pageInput);
  8000. if (pageLink) {
  8001. _GM_openInTab(pageLink, {active:true});
  8002. }
  8003. }
  8004. }
  8005. e.preventDefault();
  8006. e.stopPropagation();
  8007. });
  8008. pageBar.appendChild(pageNum);
  8009. } else {
  8010. pageText.innerHTML = createHTML(pageText.innerHTML + i18n("page") + curPage + "<i style='font-size: 0;'>&nbsp;</i>");
  8011. }
  8012. let preBtn = document.createElement("span");
  8013. preBtn.innerHTML = createHTML("∧");
  8014. preBtn.title = i18n("prevPage");
  8015. preBtn.className = "prevScreen";
  8016. 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; ";
  8017. let nextBtn = document.createElement("span");
  8018. nextBtn.innerHTML = createHTML("∨");
  8019. nextBtn.title = i18n("nextPage");
  8020. nextBtn.className = "nextScreen";
  8021. 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; ";
  8022. let localPage = curPage;
  8023. preBtn.addEventListener("click", e => {
  8024. e.stopPropagation();
  8025. e.preventDefault();
  8026. let prePageBar = document.querySelector("#pagetual_pageBar" + (localPage - 1));
  8027. if (prePageBar) {
  8028. scrollToPageBar(prePageBar);
  8029. } else {
  8030. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  8031. targetY = scrollTop - (window.innerHeight || document.documentElement.clientHeight);
  8032. window.scrollTo({ top: targetY, behavior: 'smooth'});
  8033. }
  8034. });
  8035. nextBtn.addEventListener("click", e => {
  8036. e.stopPropagation();
  8037. e.preventDefault();
  8038. let nextPageBar = document.querySelector("#pagetual_pageBar" + (localPage + 1));
  8039. if (nextPageBar) {
  8040. scrollToPageBar(nextPageBar);
  8041. } else {
  8042. scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  8043. targetY = scrollH || 9999999;
  8044. window.scrollTo({ top: targetY, behavior: 'smooth'});
  8045. }
  8046. });
  8047. if (!rulesData.hideBarArrow) {
  8048. pageText.insertBefore(preBtn, pageText.firstChild);
  8049. pageText.insertBefore(nextBtn, pageText.firstChild);
  8050. }
  8051. if (curForceIframe) {
  8052. let bgRing = document.createElement("span");
  8053. bgRing.className = "refreshRing";
  8054. bgRing.style.display = "none";
  8055. bgRing.innerHTML = createHTML(upSvg);
  8056. pageText.title = "Refresh";
  8057. pageText.appendChild(bgRing);
  8058. pageText.addEventListener("click", e => {
  8059. e.stopPropagation();
  8060. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  8061. e.preventDefault();
  8062. let nextEle = pageBar && pageBar.nextElementSibling;
  8063. if (nextEle && nextEle.name == 'pagetual-iframe') {
  8064. if (curForceIframe == nextEle) {
  8065. nextEle.setAttribute("loaded", "refresh");
  8066. }
  8067. nextEle.src = nextEle.src;
  8068. }
  8069. });
  8070. } else if (rulesData.pageBarMenu) {
  8071. pageText.addEventListener("click", e => {
  8072. e.stopPropagation();
  8073. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  8074. e.preventDefault();
  8075. picker.start();
  8076. });
  8077. }
  8078. pageBar.appendChild(downSpan);
  8079. if (forceState == 2) {
  8080. pageBar.style.width = "99%";
  8081. } else {
  8082. let parentStyle = _unsafeWindow.getComputedStyle(example.parentNode);
  8083. let parentWidth = example.parentNode.offsetWidth || parseInt(parentStyle.width);
  8084. pageBar.style.width = parentWidth - parseInt(parentStyle.paddingLeft) - parseInt(parentStyle.paddingRight) - 10 + "px";
  8085. pageBar.style.margin = '10px 5px';
  8086. if (parentStyle.display == "grid" || parentStyle.display == "inline-grid") {
  8087. pageBar.style.gridColumn = "1/-1";
  8088. }
  8089. if (inTable) {
  8090. example = compareNodeName(example, ["tr", "tbody"]) ? example : example.nextElementSibling || example;
  8091. if (compareNodeName(example, ["tbody"])) example = example.querySelector("tr");
  8092. let nextTr = example;
  8093. while (nextTr && nextTr.children.length == 0) nextTr = nextTr.nextElementSibling;
  8094. if (nextTr) example = nextTr;
  8095. let tdNum = 0;
  8096. if (exampleStyle.display == "table-row") {
  8097. [].forEach.call(example.children, el => {
  8098. tdNum += el.colSpan || 1;
  8099. });
  8100. } else {
  8101. [].forEach.call(example.children, el => {
  8102. if (compareNodeName(el, ["td", "th"])) {
  8103. tdNum += el.colSpan || 1;
  8104. }
  8105. });
  8106. }
  8107. pageBar.style.cssText = "";
  8108. pageBar.style.display = "table-row";
  8109. pageBar.style.backgroundColor = "unset";
  8110. pageBar.style.lineHeight = "20px";
  8111. pageBar.style.boxShadow = "";
  8112. let td = document.createElement("td");
  8113. td.colSpan = tdNum || 1;
  8114. let inTd = document.createElement("div");
  8115. inTd.style.cssText = pageBarStyle;
  8116. inTd.style.display = "";
  8117. inTd.className = pageBar.className;
  8118. pageBar.className = "";
  8119. inTd.appendChild(upSpan);
  8120. inTd.appendChild(pageText);
  8121. if (pageNum) inTd.appendChild(pageNum);
  8122. inTd.appendChild(downSpan);
  8123. td.appendChild(inTd);
  8124. pageBar.appendChild(td);
  8125. } else if (inLi) {
  8126. example = compareNodeName(example, ["li"]) ? example : example.nextElementSibling || example;
  8127. pageBar.style.opacity = 1;
  8128. pageBar.style.display = getComputedStyle(example).display;
  8129. pageBar.style.backgroundColor = "unset";
  8130. pageBar.style.lineHeight = "20px";
  8131. pageBar.style.boxShadow = "";
  8132. pageBar.style.border = "";
  8133. pageBar.style.width = "";
  8134. pageBar.style.maxWidth = "unset";
  8135. pageBar.style.flex = "auto";
  8136. let inTd = document.createElement("div");
  8137. inTd.style.cssText = pageBarStyle;
  8138. inTd.style.display = "";
  8139. inTd.style.margin = "0"
  8140. inTd.style.padding = "0 0";
  8141. inTd.style.textAlign = "center";
  8142. inTd.style.minWidth = "150px";
  8143. inTd.style.width = 'calc(100% - 20px)';
  8144. inTd.className = pageBar.className;
  8145. pageBar.className = "";
  8146. inTd.appendChild(upSpan);
  8147. inTd.appendChild(pageText);
  8148. if (pageNum) inTd.appendChild(pageNum);
  8149. inTd.appendChild(downSpan);
  8150. if (pageBar.style.display === 'table-row') {
  8151. let td = document.createElement("td");
  8152. td.colSpan = example.children.length;
  8153. td.style.width = '100%';
  8154. td.appendChild(inTd);
  8155. pageBar.appendChild(td);
  8156. } else {
  8157. inTd.style.width = '100%';
  8158. pageBar.appendChild(inTd);
  8159. }
  8160. }
  8161. }
  8162.  
  8163. upSpan.addEventListener("click", e => {
  8164. getBody(document).scrollTop = 0;
  8165. document.documentElement.scrollTop = 0;
  8166. e.preventDefault();
  8167. e.stopPropagation();
  8168. });
  8169. downSpan.addEventListener("click", e => {
  8170. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  8171. changeStop(true, true);
  8172. }
  8173. pageBar.title = i18n(isPause ? "enable" : "disable");
  8174. scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  8175. getBody(document).scrollTop = scrollH || 9999999;
  8176. document.documentElement.scrollTop = scrollH || 9999999;
  8177. e.preventDefault();
  8178. e.stopPropagation();
  8179. });
  8180. pageBar.addEventListener("click", e => {
  8181. changeStop(!isPause, true);
  8182. pageBar.title = i18n(isPause ? "enable" : "disable");
  8183. });
  8184. ruleParser.insertElement(pageBar);
  8185. ruleParser.runPageBar(pageBar);
  8186.  
  8187. return pageBar;
  8188. }
  8189.  
  8190. async function waitForElement(sel, doc) {
  8191. if (!sel) return null;
  8192. return new Promise((resolve) => {
  8193. let checkInv = setInterval(() => {
  8194. let result = getElement(sel, doc, null, true);
  8195. if (result) {
  8196. clearInterval(checkInv);
  8197. resolve(result);
  8198. }
  8199. }, 100);
  8200. });
  8201. }
  8202.  
  8203. async function clickAction(sel, doc) {
  8204. let btn = await waitForElement(sel, doc);
  8205. emuClick(btn, doc);
  8206. }
  8207.  
  8208. async function enterAction(sel, doc) {
  8209. let btn = await waitForElement(sel, doc);
  8210. let eventParam = { key: "Enter", keyCode: 13, bubbles: true };
  8211. let event = new KeyboardEvent('keydown', eventParam);
  8212. btn.dispatchEvent(event);
  8213. event = new KeyboardEvent('keyup', eventParam);
  8214. btn.dispatchEvent(event);
  8215. event = new KeyboardEvent('keypress', eventParam);
  8216. btn.dispatchEvent(event);
  8217. }
  8218.  
  8219. async function inputAction(sel, v, doc) {
  8220. let input = await waitForElement(sel, doc);
  8221. let event = new Event('focus', { bubbles: true });
  8222. input.dispatchEvent(event);
  8223. let lastValue = input.value;
  8224. if (input.nodeName.toUpperCase() == "INPUT") {
  8225. var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
  8226. nativeInputValueSetter.call(input, v);
  8227. } else if (input.nodeName.toUpperCase() == "TEXTAREA") {
  8228. var nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
  8229. nativeTextareaValueSetter.call(input, v);
  8230. } else {
  8231. input.innerHTML = createHTML(v);
  8232. }
  8233. event = new Event('input', { bubbles: true });
  8234. let tracker = input._valueTracker;
  8235. if (tracker) {
  8236. tracker.setValue(lastValue);
  8237. }
  8238. input.dispatchEvent(event);
  8239. event = new Event('change', { bubbles: true });
  8240. input.dispatchEvent(event);
  8241. debug(input, `input ${sel}`);
  8242. }
  8243.  
  8244. function emuClick(btn, doc) {
  8245. if (!doc) doc = document;
  8246. let curScroll = getBody(doc).scrollTop || doc.documentElement.scrollTop;
  8247. let orgHref = btn.getAttribute('href');
  8248. if (orgHref && orgHref.replace(location.origin + location.pathname, "").indexOf("#") === 0) {
  8249. let hashAction = e => {
  8250. e.preventDefault();
  8251. getBody(doc).scrollTop = curScroll;
  8252. doc.documentElement.scrollTop = curScroll;
  8253. btn.removeEventListener('click', hashAction, false);
  8254. };
  8255. btn.addEventListener('click', hashAction, false);
  8256. }
  8257. if (!PointerEvent) return btn.click();
  8258. let eventParam = {
  8259. isTrusted: true,
  8260. altKey: false,
  8261. azimuthAngle: 0,
  8262. bubbles: true,
  8263. button: 0,
  8264. buttons: 0,
  8265. clientX: 1,
  8266. clientY: 1,
  8267. cancelBubble: false,
  8268. cancelable: true,
  8269. composed: true,
  8270. ctrlKey: false,
  8271. defaultPrevented: false,
  8272. detail: 1,
  8273. eventPhase: 2,
  8274. fromElement: null,
  8275. height: 1,
  8276. isPrimary: false,
  8277. metaKey: false,
  8278. pointerId: 1,
  8279. pointerType: "mouse",
  8280. pressure: 0,
  8281. relatedTarget: null,
  8282. returnValue: true,
  8283. shiftKey: false,
  8284. toElement: null,
  8285. twist: 0,
  8286. which: 1
  8287. };
  8288. let mouseEvent = new PointerEvent("mousedown", eventParam);
  8289. btn.dispatchEvent(mouseEvent);
  8290. mouseEvent = new PointerEvent("mouseup", eventParam);
  8291. btn.dispatchEvent(mouseEvent);
  8292. let dispatchTouchEvent = (ele, type) => {
  8293. let touchEvent;
  8294. try {
  8295. touchEvent = document.createEvent('TouchEvent')
  8296. touchEvent.initTouchEvent(type, true, true)
  8297. } catch (err) {
  8298. try {
  8299. touchEvent = document.createEvent('UIEvent')
  8300. touchEvent.initUIEvent(type, true, true)
  8301. } catch (err) {
  8302. touchEvent = document.createEvent('Event')
  8303. touchEvent.initEvent(type, true, true)
  8304. }
  8305. }
  8306. if (touchEvent) {
  8307. try {
  8308. touchEvent.targetTouches = [{
  8309. pageX: 1,
  8310. pageY: 1,
  8311. clientX: 1,
  8312. clientY: 1,
  8313. target: btn
  8314. }];
  8315. touchEvent.touches = [{
  8316. pageX: 1,
  8317. pageY: 1,
  8318. clientX: 1,
  8319. clientY: 1,
  8320. target: btn
  8321. }];
  8322. touchEvent.changedTouches = [{
  8323. pageX: 1,
  8324. pageY: 1,
  8325. clientX: 1,
  8326. clientY: 1,
  8327. target: btn
  8328. }];
  8329. } catch (err) {}
  8330. ele.dispatchEvent(touchEvent);
  8331. }
  8332. }
  8333. dispatchTouchEvent(btn, "touchstart");
  8334. dispatchTouchEvent(btn, "touchend");
  8335.  
  8336. btn.click();
  8337. }
  8338.  
  8339. function emuInput(input, v) {
  8340. let result = false;
  8341. if (!input) return true;
  8342. let event = new Event('focus', { bubbles: true });
  8343. input.dispatchEvent(event);
  8344. let lastValue = input.value;
  8345. if (input.type == 'file') {
  8346. let file = v;
  8347. let blob = new Blob([file], {
  8348. type: 'text/plain'
  8349. });
  8350. file = new File([blob], 'noname.txt', { type: blob.type });
  8351. let dataTransfer = new DataTransfer();
  8352. dataTransfer.items.add(file);
  8353. input.files = dataTransfer.files;
  8354. v = "c:/fakepath/fakefile";
  8355. } else if (/INPUT/i.test(input.nodeName)) {
  8356. var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
  8357. nativeInputValueSetter.call(input, v);
  8358. } else if (/SELECT/i.test(input.nodeName)) {
  8359. var nativeSelectValueSetter = Object.getOwnPropertyDescriptor(window.HTMLSelectElement.prototype, "value").set;
  8360. nativeSelectValueSetter.call(input, v);
  8361. } else if (input.nodeName.toUpperCase() == "TEXTAREA") {
  8362. var nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
  8363. nativeTextareaValueSetter.call(input, v);
  8364. } else {
  8365. input.innerHTML = createHTML(v);
  8366. }
  8367. event = new Event('input', { bubbles: true });
  8368. let tracker = input._valueTracker;
  8369. if (tracker) {
  8370. tracker.setValue(lastValue);
  8371. }
  8372. input.dispatchEvent(event);
  8373. event = new Event('change', { bubbles: true });
  8374. input.dispatchEvent(event);
  8375. return result;
  8376. }
  8377.  
  8378. var failFromIframe = 0;
  8379. var inCors = false;
  8380. var checkRemoveIntv;
  8381. function requestFromIframe(url, callback){
  8382. if (location.protocol === 'https:' && !/^https:/.test(url)) {
  8383. ruleParser.noValidContent(url);
  8384. }
  8385. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  8386. let iframe = document.createElement('iframe');
  8387. iframe.name = 'pagetual-iframe';
  8388. iframe.width = '100%';
  8389. iframe.height = '1000';
  8390. iframe.frameBorder = '0';
  8391. if (ruleParser.curSiteRule.sandbox != false) {
  8392. iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  8393. }
  8394. 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;';
  8395. let waitTime = 100, checkEval;
  8396. ruleParser.runWait((_checkEval, _waitTime) => {
  8397. if (_checkEval) {
  8398. checkEval = _checkEval;
  8399. }
  8400. if (_waitTime) {
  8401. waitTime = _waitTime;
  8402. }
  8403. });
  8404. if (checkRemoveIntv) clearInterval(checkRemoveIntv);
  8405. checkRemoveIntv = setInterval(() => {
  8406. if (!iframe || !getBody(document).contains(iframe)) {
  8407. clearInterval(checkRemoveIntv);
  8408. loadPageOver();
  8409. }
  8410. }, 500);
  8411. let loadedHandler = async e => {
  8412. if (e.data != 'pagetual-iframe:DOMLoaded' && e.type != 'load') return;
  8413. clearInterval(checkRemoveIntv);
  8414. window.removeEventListener('message', loadedHandler, false);
  8415. iframe.removeEventListener('load', loadedHandler, false);
  8416. let pageEleTryTimes = 0;
  8417. async function checkIframe() {
  8418. if (urlChanged || isPause) {
  8419. return callback(false, false);
  8420. }
  8421. try {
  8422. let doc = iframe.contentDocument || iframe.contentWindow.document;
  8423. if (checkEval && !await checkEval(doc)) {
  8424. setTimeout(() => {
  8425. checkIframe();
  8426. }, waitTime);
  8427. return;
  8428. } else {
  8429. let preCode = ruleParser.curSiteRule.pagePre, eles = null;
  8430. if (preCode) {
  8431. try {
  8432. let preResult;
  8433. if (typeof preCode == 'function') {
  8434. preResult = await preCode(doc.documentElement.innerHTML, doc);
  8435. } else if (preCode.length == 2) {
  8436. preResult = doc.documentElement.innerHTML.replace(new RegExp(preCode[0], "gi"), preCode[1]);
  8437. } else {
  8438. preResult = await new AsyncFunction("response", "doc", '"use strict";' + preCode)(doc.documentElement.innerHTML, doc);
  8439. }
  8440. if (preResult) {
  8441. if (typeof preResult === "string") {
  8442. doc.documentElement.innerHTML = preResult;
  8443. } else eles = preResult;
  8444. }
  8445. } catch(e) {
  8446. debug(e);
  8447. }
  8448. }
  8449. let base = doc.querySelector("base");
  8450. ruleParser.basePath = base ? base.href : url;
  8451. if (eles === null) eles = ruleParser.getPageElement(doc, iframe.contentWindow, pageEleTryTimes < 25);
  8452. if (eles && eles.length > 0) {
  8453. await ruleParser.hookUrl(doc);
  8454. await callback(doc, eles);
  8455. } else if (pageEleTryTimes++ < 100) {
  8456. getBody(doc).scrollTop = 9999999;
  8457. doc.documentElement.scrollTop = 9999999;
  8458. setTimeout(() => {
  8459. checkIframe();
  8460. }, waitTime);
  8461. return;
  8462. } else {
  8463. if (failFromIframe++ > 2) {
  8464. failFromIframe = 0;
  8465. debug("Stop as failFromIframe");
  8466. changeStop(true);
  8467. callback(false, false);
  8468. } else {
  8469. ruleParser.noValidContent(url);
  8470. callback(false, false);
  8471. }
  8472. }
  8473. }
  8474. } catch(e) {
  8475. inCors = true;
  8476. if (forceState === 3) {
  8477. debug("Stop as cors");
  8478. isPause = true;
  8479. }
  8480. if (!ruleParser.curSiteRule.pageElement) {
  8481. ruleParser.curSiteRule.pageElement = allOfBody;
  8482. ruleParser.getInsert(true);
  8483. }
  8484. ruleParser.curSiteRule.action = 0;
  8485. ruleParser.nextLinkHref = url;
  8486. callback(false, false);
  8487. nextPage();
  8488. }
  8489. if (iframe && iframe.parentNode) iframe.parentNode.removeChild(iframe);
  8490. }
  8491. setTimeout(() => {
  8492. checkIframe();
  8493. }, waitTime);
  8494. };
  8495. let code = ruleParser.curSiteRule.iframeInit;
  8496. if (code) {
  8497. let checkReady = setInterval(() => {
  8498. let doc;
  8499. try {
  8500. doc = iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document);
  8501. } catch(e) {
  8502. clearInterval(checkReady);
  8503. return;
  8504. }
  8505. if (doc) {
  8506. clearInterval(checkReady);
  8507. try {
  8508. Function('win', 'iframe', '"use strict";' + code)(iframe.contentWindow, iframe);
  8509. } catch(e) {
  8510. debug(e);
  8511. }
  8512. }
  8513. }, 50);
  8514. }
  8515. window.addEventListener('message', loadedHandler, false);
  8516. iframe.addEventListener('load', loadedHandler, false);
  8517. iframe.src = url;
  8518. try {
  8519. getBody(document).appendChild(iframe);
  8520. } catch (e) {
  8521. return callback(false, false);
  8522. }
  8523. }
  8524.  
  8525. var emuIframe, lastActiveUrl, orgContent, meetCors = false;
  8526. function emuPage(callback) {
  8527. let orgPage = null, preContent = null, iframeDoc, checkTimes = 0, loadmoreBtn, pageEle, nextLink, loadmoreEnd = false, waitTimes = 80, changed = false;
  8528. function returnFalse(log) {
  8529. if (curPage > 1) {
  8530. if (rulesData.lastPageTips) showTips(i18n("lastPage"), "", 800);
  8531. _unsafeWindow.postMessage({
  8532. action: "lastPage",
  8533. command: 'pagetual'
  8534. }, '*');
  8535. } else {
  8536. sideController.remove();
  8537. }
  8538. debug(log);
  8539. isPause = true;
  8540. callback(false, false);
  8541. if (emuIframe && emuIframe.parentNode) {
  8542. emuIframe.parentNode.removeChild(emuIframe);
  8543. emuIframe = null;
  8544. }
  8545. }
  8546. function cloneStatus() {
  8547. if (!iframeDoc) return;
  8548. let inputs = document.querySelectorAll("input:not([type=button],[type=image],[type=reset],[type=submit])");
  8549. let selectOptions = document.querySelectorAll("select>option");
  8550. [...inputs].forEach(input => {
  8551. let sel = geneSelector(input, true, true);
  8552. let mirrorEle = iframeDoc.querySelector(sel);
  8553. if (!mirrorEle) return;
  8554. emuInput(mirrorEle, input.value);
  8555. });
  8556. [...selectOptions].forEach(option => {
  8557. let sel = geneSelector(option, true, true);
  8558. let mirrorEle = iframeDoc.querySelector(sel);
  8559. if (!mirrorEle) return;
  8560. let selected = option.selected;
  8561. mirrorEle.selected = !!selected;
  8562. mirrorEle.parentNode.dispatchEvent(new Event('change'));
  8563. });
  8564. }
  8565. async function checkPage() {
  8566. if (isPause) return loadPageOver();
  8567. try {
  8568. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  8569. } catch(e) {
  8570. returnFalse("Stop as cors");
  8571. return;
  8572. }
  8573.  
  8574. let waitTime = 200, checkEval;
  8575. ruleParser.runWait((_checkEval, _waitTime) => {
  8576. if (_checkEval) {
  8577. checkEval = _checkEval;
  8578. }
  8579. if (_waitTime) {
  8580. waitTime = _waitTime;
  8581. }
  8582. });
  8583.  
  8584. if (!orgPage) {
  8585. if (!loadmoreEnd) {
  8586. loadmoreBtn = getLoadMore(iframeDoc);
  8587. if (loadmoreBtn && isVisible(loadmoreBtn, emuIframe.contentWindow)) {
  8588. emuClick(loadmoreBtn, iframeDoc);
  8589. let intv = setInterval(() => {
  8590. loadmoreBtn = getLoadMore(iframeDoc);
  8591. if (!loadmoreBtn || !getBody(document).contains(loadmoreBtn) || !isVisible(loadmoreBtn, emuIframe.contentWindow)) {
  8592. clearInterval(intv);
  8593. loadmoreEnd = true;
  8594. setTimeout(() => {
  8595. checkPage();
  8596. }, 500);
  8597. } else if (isInViewPort(loadmoreBtn)) {
  8598. emuClick(loadmoreBtn, iframeDoc);
  8599. }
  8600. }, 200);
  8601. return;
  8602. } else {
  8603. loadmoreEnd = true;
  8604. }
  8605. }
  8606. if (checkEval && !await checkEval(iframeDoc)) {
  8607. waitTimes = 50;
  8608. setTimeout(() => {
  8609. checkPage();
  8610. }, waitTime);
  8611. return;
  8612. } else {
  8613. if (!nextLink || !nextLink.offsetParent) nextLink = await ruleParser.getNextLink(iframeDoc, true);
  8614. if (nextLink) pageEle = ruleParser.getPageElement(iframeDoc, emuIframe.contentWindow, true);
  8615. if (!pageEle || pageEle.length == 0 || !nextLink) {
  8616. getBody(iframeDoc).scrollTop = 9999999;
  8617. iframeDoc.documentElement.scrollTop = 9999999;
  8618. if (waitTimes-- > 0) {
  8619. setTimeout(() => {
  8620. checkPage();
  8621. }, waitTime);
  8622. return;
  8623. }
  8624. }
  8625. }
  8626. if (!pageEle || pageEle.length == 0) {
  8627. returnFalse("Stop as no page when emu");
  8628. return;
  8629. }
  8630. pageEle = [].filter.call(pageEle, ele => {return ele && !compareNodeName(ele, ["style", "script", "meta"])});
  8631. if (compareNodeName(pageEle[0], ["ul"]) || pageEle.length == 1) pageEle = pageEle[0];
  8632. else if (pageEle[0].parentNode == pageEle[1].parentNode) {
  8633. pageEle = pageEle[0].parentNode;
  8634. } else {
  8635. pageEle = pageEle[0];
  8636. }
  8637. if (ruleParser.curSiteRule.smart && orgContent != pageEle.innerHTML) {
  8638. orgContent = pageEle.innerHTML;
  8639. if (waitTimes-- > 0) {
  8640. setTimeout(() => {
  8641. checkPage();
  8642. }, 500);
  8643. return;
  8644. }
  8645. }
  8646. orgPage = pageEle;
  8647. if (nextLink) {
  8648. if (compareNodeName(orgPage, ["img"])) {
  8649. if (!ruleParser.curSiteRule.lazyImgSrc) ruleParser.curSiteRule.lazyImgSrc = "0";
  8650. if (orgPage.src) {
  8651. orgContent = orgPage.src;
  8652. } else {
  8653. setTimeout(() => {
  8654. checkPage();
  8655. }, 500);
  8656. return;
  8657. }
  8658. } else {
  8659. orgContent = orgPage.innerHTML;
  8660. }
  8661. preContent = orgContent;
  8662. if (!isVisible(nextLink, emuIframe.contentWindow)) {
  8663. returnFalse("Stop as next hide when emu");
  8664. } else {
  8665. emuClick(nextLink, iframeDoc);
  8666. setTimeout(() => {
  8667. checkPage();
  8668. }, 500);
  8669. }
  8670. } else {
  8671. returnFalse("Stop as no next when emu");
  8672. }
  8673. return;
  8674. }
  8675. if (!ruleParser.checkStopSign(nextLink, iframeDoc)) {
  8676. return returnFalse("Stop as stopSign");
  8677. }
  8678. if (checkTimes++ > 200) {
  8679. returnFalse("Stop as timeout when emu");
  8680. return;
  8681. }
  8682. if (checkEval && !await checkEval(iframeDoc)) {
  8683. checkTimes = 0;
  8684. setTimeout(() => {
  8685. checkPage();
  8686. }, waitTime);
  8687. return;
  8688. }
  8689. let eles = ruleParser.getPageElement(iframeDoc, emuIframe.contentWindow, true), checkItem;
  8690. if (eles && eles.length > 0) {
  8691. eles = [].filter.call(eles, ele => {return ele && !compareNodeName(ele, ["style", "script", "meta"])});
  8692. if (compareNodeName(eles[0], ["ul"]) || eles.length == 1) checkItem = eles[0];
  8693. else if (eles[0].parentNode == eles[1].parentNode) {
  8694. checkItem = eles[0].parentNode;
  8695. } else {
  8696. checkItem = eles[0];
  8697. }
  8698. }
  8699. if (!checkItem) {
  8700. setTimeout(() => {
  8701. checkPage();
  8702. }, waitTime);
  8703. } else {
  8704. let checkInner;
  8705. if (compareNodeName(checkItem, ["img"])) {
  8706. if (checkItem.src) {
  8707. checkInner = checkItem.src;
  8708. } else {
  8709. setTimeout(() => {
  8710. checkPage();
  8711. }, waitTime);
  8712. return;
  8713. }
  8714. } else {
  8715. checkInner = checkItem.innerHTML;
  8716. }
  8717. if (orgPage != checkItem || checkInner != preContent) {
  8718. changed = true;
  8719. orgPage = checkItem;
  8720. preContent = checkInner;
  8721. setTimeout(() => {
  8722. checkPage();
  8723. }, 500);
  8724. } else if (changed) {
  8725. checkTimes = 0;
  8726. if (orgContent == preContent && (ruleParser.curSiteRule.smart || ruleParser.curSiteRule.stopSame)) {
  8727. returnFalse("Stop as same content");
  8728. } else {
  8729. orgContent = preContent;
  8730. await ruleParser.hookUrl(iframeDoc);
  8731. callback(iframeDoc, eles);
  8732. }
  8733. } else {
  8734. if (checkTimes % 10 === 5) {
  8735. if (!nextLink || !nextLink.offsetParent) {
  8736. nextLink = await ruleParser.getNextLink(iframeDoc, true);
  8737. }
  8738. if (nextLink) {
  8739. emuClick(nextLink, iframeDoc);
  8740. }
  8741. }
  8742. setTimeout(() => {
  8743. checkPage();
  8744. }, waitTime);
  8745. }
  8746. }
  8747. }
  8748. if (!emuIframe) {
  8749. let loaded = false;
  8750. emuIframe = document.createElement('iframe');
  8751. emuIframe.name = 'pagetual-iframe';
  8752. let notSetSandbox = typeof ruleParser.curSiteRule.sandbox == 'undefined';
  8753. if (notSetSandbox || ruleParser.curSiteRule.sandbox == true) {
  8754. emuIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  8755. } else if (ruleParser.curSiteRule.sandbox) {
  8756. emuIframe.sandbox = ruleParser.curSiteRule.sandbox;
  8757. }
  8758. emuIframe.width = '100%';
  8759. emuIframe.height = '100%';
  8760. emuIframe.frameBorder = '0';
  8761. 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;';
  8762. emuIframe.addEventListener("load", e => {
  8763. try {
  8764. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  8765. } catch(e) {
  8766. if (e.message && e.message.indexOf("cross-origin") != -1 && notSetSandbox && emuIframe.hasAttribute("sandbox")) {
  8767. emuIframe.removeAttribute("sandbox");
  8768. meetCors = true;
  8769. callback(false, false);
  8770. if (ruleParser.curSiteRule.smart) {
  8771. ruleParser.findNoNext();
  8772. }
  8773. } else {
  8774. returnFalse("Stop as cors");
  8775. }
  8776. return;
  8777. }
  8778. setTimeout(async () => {
  8779. if (meetCors && ruleParser.curSiteRule.smart) {
  8780. ruleParser.smartRules = ruleParser.smartRules.filter(item => {return item && item.url !== ruleParser.curSiteRule.url;});
  8781. storage.setItem("smartRules", ruleParser.smartRules);
  8782. }
  8783. meetCors = false;
  8784. let code = ruleParser.curSiteRule.init;
  8785. if (code) {
  8786. try {
  8787. 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)});
  8788. } catch(e) {
  8789. debug(e);
  8790. }
  8791. } else {
  8792. let refreshByClickSel = ruleParser.curSiteRule.refreshByClick;
  8793. if (iframeDoc && refreshByClickSel) {
  8794. let clickBtn = await waitForElement(refreshByClickSel, iframeDoc);
  8795. await sleep(500);
  8796. cloneStatus();
  8797. emuClick(clickBtn, iframeDoc);
  8798. await sleep(500);
  8799. }
  8800. }
  8801. if (loaded) return;
  8802. loaded = true;
  8803. checkPage();
  8804. }, 500);
  8805. });
  8806. let code = ruleParser.curSiteRule.iframeInit;
  8807. if (code) {
  8808. let checkReady = setInterval(() => {
  8809. try {
  8810. iframeDoc = emuIframe.contentDocument || (emuIframe.contentWindow && emuIframe.contentWindow.document);
  8811. } catch(e) {
  8812. clearInterval(checkReady);
  8813. return;
  8814. }
  8815. if (iframeDoc) {
  8816. clearInterval(checkReady);
  8817. try {
  8818. Function('win', 'iframe', '"use strict";' + code)(emuIframe.contentWindow, emuIframe);
  8819. } catch(e) {
  8820. debug(e);
  8821. }
  8822. }
  8823. }, 50);
  8824. }
  8825. if (!lastActiveUrl) lastActiveUrl = location.href;
  8826. emuIframe.src = lastActiveUrl;
  8827. getBody(document).appendChild(emuIframe);
  8828. } else {
  8829. if (emuIframe.src != lastActiveUrl || meetCors) {
  8830. emuIframe.src = lastActiveUrl;
  8831. return;
  8832. }
  8833. checkPage();
  8834. }
  8835. }
  8836.  
  8837. var scrollToResizeInited = false;
  8838. var resizePool = [];
  8839. var scrollingToResize = false;
  8840.  
  8841. function isTouchViewPort(element) {
  8842. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  8843. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  8844. const {
  8845. top,
  8846. right,
  8847. bottom,
  8848. left,
  8849. } = element.getBoundingClientRect();
  8850.  
  8851. return (
  8852. top < viewHeight &&
  8853. left < viewWidth &&
  8854. right > 0 &&
  8855. bottom > 0
  8856. );
  8857. }
  8858.  
  8859. function resizeIframe(iframe, frameDoc, pageEle) {
  8860. if (targetY >= 0) {
  8861. window.scrollTo({ top: targetY, behavior: 'instant'});
  8862. targetY = -1;
  8863. }
  8864. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  8865. if (ruleParser.curSiteRule.smart || forceState === 2) {
  8866. let height = (getBody(frameDoc).scrollHeight || getBody(frameDoc).offsetHeight || 500);
  8867. if (!iframe.style.height || parseInt(iframe.style.height) === 0 || height - parseInt(iframe.style.height) > window.innerHeight) {
  8868. iframe.style.height = height + "px";
  8869. iframe.style.minHeight = iframe.style.height;
  8870. }
  8871. iframe.style.width = "100%";
  8872. frameDoc.documentElement.scrollTop = 0;
  8873. frameDoc.documentElement.scrollLeft = 0;
  8874. } else {
  8875. if (pageEle) {
  8876. if (document.body.scrollWidth) frameDoc.documentElement.style.width = document.body.scrollWidth + "px";
  8877. let fitWidth = ruleParser.curSiteRule.fitWidth !== false;
  8878. let targetElement = pageEle[0];
  8879. if (!targetElement) return;
  8880. if (pageEle.length > 1) {
  8881. targetElement = targetElement.parentNode;
  8882. }
  8883. let scrollHeight = targetElement.scrollHeight || targetElement.offsetHeight || 500;
  8884. iframe.style.height = scrollHeight + "px";
  8885. let scrollTop = 0, scrollLeft = 0;
  8886. getBody(frameDoc).scrollTop = 0;
  8887. getBody(frameDoc).scrollLeft = 0;
  8888. while (targetElement && targetElement.offsetParent) {
  8889. targetElement.offsetParent.scrollTop = targetElement.offsetTop;
  8890. if (targetElement.offsetParent.scrollTop == 0) {
  8891. scrollTop += targetElement.offsetTop;
  8892. }
  8893. if (fitWidth) {
  8894. targetElement.offsetParent.scrollLeft = targetElement.offsetLeft;
  8895. if (targetElement.offsetParent.scrollLeft == 0) {
  8896. scrollLeft += targetElement.offsetLeft;
  8897. }
  8898. }
  8899. targetElement = targetElement.offsetParent;
  8900. }
  8901. frameDoc.documentElement.scrollTop = scrollTop;
  8902. frameDoc.documentElement.scrollLeft = scrollLeft;
  8903. if (frameDoc.documentElement.scrollTop == 0 && frameDoc.documentElement.scrollLeft == 0) {
  8904. getBody(frameDoc).scrollTop += scrollTop;
  8905. getBody(frameDoc).scrollLeft += scrollLeft;
  8906. }
  8907. if (!fitWidth && iframe.style.marginLeft == '0px') {
  8908. iframe.style.width = "100vw";
  8909. iframe.style.maxWidth = "100vw";
  8910. iframe.style.minWidth = "100vw";
  8911. var cWidth = document.body.clientWidth || document.documentElement.clientWidth;
  8912. var iWidth = window.innerWidth;
  8913. iframe.style.marginLeft = -iframe.getBoundingClientRect().left - (iWidth - cWidth) / 2 + "px";
  8914. }
  8915. }
  8916. }
  8917. let newScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  8918. if (newScroll != curScroll) {
  8919. getBody(document).scrollTop = curScroll;
  8920. document.documentElement.scrollTop = curScroll;
  8921. }
  8922. }
  8923.  
  8924. function scrollToResize(e) {
  8925. if (scrollingToResize) return;
  8926. else {
  8927. scrollingToResize = true;
  8928. let resizeHandler = () => {
  8929. let touched = 0;
  8930. for (let i = 0; i < resizePool.length; i++) {
  8931. let resizeArr = resizePool[i];
  8932. let iframe = resizeArr[1]();
  8933. if (isTouchViewPort(iframe)) {
  8934. touched++;
  8935. let pageEle = resizeArr[0]();
  8936. let frameDoc = resizeArr[2]();
  8937. resizeIframe(iframe, frameDoc, pageEle);
  8938. } else if (touched) {
  8939. if (touched == 1) {
  8940. let pageEle = resizeArr[0]();
  8941. let frameDoc = resizeArr[2]();
  8942. resizeIframe(iframe, frameDoc, pageEle);
  8943. }
  8944. break;
  8945. } else if (!iframe.parentNode) {
  8946. resizePool.splice(i, 1);
  8947. break;
  8948. }
  8949. }
  8950. };
  8951. setTimeout(() => {
  8952. scrollingToResize = false;
  8953. }, 300);
  8954. resizeHandler();
  8955. }
  8956. }
  8957.  
  8958. var curForceIframe;
  8959. function forceIframe(url, callback) {
  8960. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  8961. let curIframe = document.createElement('iframe'), iframeDoc, pageElement = null, inAction = true;
  8962. let loadedHandler = () => {
  8963. let getPageEle = () => {
  8964. if (ruleParser.curSiteRule.smart) {
  8965. return null;
  8966. } else {
  8967. if (!pageElement || pageElement.length === 0 || !pageElement[0].offsetParent) {
  8968. pageElement = ruleParser.getPageElement(iframeDoc, curIframe.contentWindow);
  8969. }
  8970. return pageElement;
  8971. }
  8972. };
  8973. resizeIframe(curIframe, iframeDoc, getPageEle());
  8974. let loaded = curIframe.getAttribute("loaded");
  8975. if (loaded == "true") {
  8976. return;
  8977. }
  8978. curIframe.setAttribute("loaded", "true");
  8979. let getIframe = () => {
  8980. return curIframe;
  8981. };
  8982. let getFrameDoc = () => {
  8983. return iframeDoc;
  8984. };
  8985. ruleParser.insertPage(iframeDoc, [], url, ele => {
  8986. callback(curIframe, loaded == "refresh");
  8987. inAction = false;
  8988. }, true);
  8989. if (!loaded) {
  8990. resizePool.push([getPageEle, getIframe, getFrameDoc]);
  8991. }
  8992. };
  8993. let checkIframeTimer = setInterval(() => {
  8994. if (!curIframe.parentNode) {
  8995. clearInterval(checkIframeTimer);
  8996. return curIframe.getAttribute("loaded") == "true" || callback(false);
  8997. }
  8998. }, 500);
  8999. let code = ruleParser.curSiteRule.iframeInit;
  9000. if (code) {
  9001. let checkReady = setInterval(() => {
  9002. try {
  9003. iframeDoc = curIframe.contentDocument || (curIframe.contentWindow && curIframe.contentWindow.document);
  9004. } catch(e) {
  9005. clearInterval(checkReady);
  9006. return;
  9007. }
  9008. if (iframeDoc) {
  9009. clearInterval(checkReady);
  9010. try {
  9011. Function('win', 'iframe', '"use strict";' + code)(curIframe.contentWindow, curIframe);
  9012. } catch(e) {
  9013. debug(e);
  9014. }
  9015. }
  9016. }, 50);
  9017. }
  9018. let waitTime = 300, checkEval;
  9019. ruleParser.runWait((_checkEval, _waitTime) => {
  9020. if (_checkEval) {
  9021. checkEval = _checkEval;
  9022. }
  9023. if (_waitTime) {
  9024. waitTime = _waitTime;
  9025. }
  9026. });
  9027. async function checkIframe() {
  9028. if (checkEval && !await checkEval(iframeDoc)) {
  9029. setTimeout(() => {
  9030. checkIframe();
  9031. }, waitTime);
  9032. return;
  9033. }
  9034. loadedHandler();
  9035. }
  9036. curIframe.name = 'pagetual-iframe';
  9037. curIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  9038. curIframe.frameBorder = '0';
  9039. curIframe.scrolling = "no";
  9040. 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;';
  9041. curIframe.addEventListener("load", async e => {
  9042. clearInterval(checkIframeTimer);
  9043. if (isPause) return callback(false);
  9044. try {
  9045. iframeDoc = curIframe.contentDocument || curIframe.contentWindow.document;
  9046. } catch(e) {
  9047. debug("Stop as cors");
  9048. isPause = true;
  9049. callback(false);
  9050. return;
  9051. }
  9052. let css = ruleParser.curSiteRule.css || rulesData.customCss;
  9053. if (css) {
  9054. let cssArr = css.split("inIframe:");
  9055. if (cssArr && cssArr.length > 1) {
  9056. let styleEle = iframeDoc.createElement("style");
  9057. styleEle.innerHTML = cssArr[1];
  9058. iframeDoc.head.appendChild(styleEle);
  9059. }
  9060. }
  9061. checkIframe();
  9062. iframeDoc.addEventListener('wheel', e => {
  9063. document.dispatchEvent(new Event('wheel'));
  9064. }, true);
  9065. });
  9066. let checkTimes = 0, findPageEle = false;
  9067. let forceRefresh = e => {
  9068. if (inAction || !iframeDoc) return;
  9069. inAction = true;
  9070. let foundNext = () => {
  9071. document.removeEventListener("scroll", forceRefresh);
  9072. }
  9073. setTimeout(async () => {
  9074. inAction = false;
  9075. if (!ruleParser.nextLinkHref && !isPause) {
  9076. checkTimes++;
  9077. await ruleParser.getNextLink(iframeDoc, true);
  9078. if (ruleParser.nextLinkHref) {
  9079. foundNext();
  9080. if (isLoading) isLoading = false;
  9081. } else if (checkTimes >= 10) {
  9082. foundNext();
  9083. } else if (checkTimes >= 3 && !findPageEle) {
  9084. if (!pageElement) pageElement = ruleParser.getPageElement(iframeDoc, curIframe.contentWindow);
  9085. if (!pageElement) {
  9086. inAction = true;
  9087. curIframe.contentWindow.location.reload();
  9088. } else {
  9089. findPageEle = true;
  9090. }
  9091. }
  9092. } else {
  9093. foundNext();
  9094. }
  9095. }, 100);
  9096. };
  9097. document.addEventListener("scroll", forceRefresh);
  9098. curIframe.src = url;
  9099. curForceIframe = curIframe;
  9100. let insert = ruleParser.getInsert();
  9101. let body = getBody(document);
  9102. let curScroll = body.scrollTop || document.documentElement.scrollTop;
  9103. if (forceState == 2) {
  9104. document.documentElement.appendChild(loadingDiv);
  9105. body.appendChild(curIframe);
  9106. let bodyStyle = getComputedStyle(body);
  9107. if (bodyStyle.display == "flex" || bodyStyle.display == "inline-flex") {
  9108. body.style.flexDirection = "column";
  9109. }
  9110. } else {
  9111. ruleParser.insertElement(curIframe);
  9112. }
  9113. body.scrollTop = curScroll;
  9114. document.documentElement.scrollTop = curScroll;
  9115.  
  9116. if (!scrollToResizeInited) {
  9117. scrollToResizeInited = true;
  9118. document.addEventListener("scroll", scrollToResize);
  9119. }
  9120. return curIframe;
  9121. }
  9122.  
  9123. function loadPageOver() {
  9124. isLoading = false;
  9125. stopScroll = true;
  9126. setTimeout(() => {stopScroll = false;}, 300);
  9127. if (loadingDiv.parentNode) {
  9128. loadingDiv.parentNode.removeChild(loadingDiv);
  9129. }
  9130. if (rate !== 1 && !clickMode) {
  9131. setTimeout(() => {
  9132. if (distToBottom() < bottomGap) {
  9133. nextPage();
  9134. }
  9135. }, 1);
  9136. }
  9137. }
  9138.  
  9139. function checkAutoLoadNum() {
  9140. if (autoLoadNum >= 0) {
  9141. if (autoLoadNum !== 0 && --autoLoadNum === 0) {
  9142. autoLoadNum = -1;
  9143. } else {
  9144. setTimeout(() => nextPage(), 1);
  9145. }
  9146. }
  9147. }
  9148.  
  9149. async function nextPage() {
  9150. if (isPause || isLoading || forceState === 1) return;
  9151. if (ruleParser.curSiteRule.delay) {
  9152. try {
  9153. let checkDelay = ((typeof ruleParser.curSiteRule.delay === 'function') ? ruleParser.curSiteRule.delay : Function('"use strict";' + ruleParser.curSiteRule.delay))();
  9154. if (!checkDelay) return;
  9155. } catch(e) {
  9156. debug(e);
  9157. }
  9158. }
  9159. let nextLink = ruleParser.nextLinkHref;
  9160. if (!nextLink) {
  9161. isLoading = true;
  9162. if (curPage === 1) {
  9163. await ruleParser.getNextLink(document, true);
  9164. nextLink = ruleParser.nextLinkHref;
  9165. }
  9166. if (!nextLink) {
  9167. if (curPage === 1) {
  9168. if (ruleParser.curSiteRule.pinUrl) {
  9169. setTimeout(() => {isLoading = false;}, 500);
  9170. } else if (tryTimes++ < 5) {
  9171. setTimeout(() => {isLoading = false;}, 1000);
  9172. } else {
  9173. ruleParser.findNoNext();
  9174. }
  9175. } else if (!showedLastPageTips) {
  9176. if (rulesData.lastPageTips) {
  9177. showTips(i18n("lastPage"), "", 800);
  9178. }
  9179. showedLastPageTips = true;
  9180. _unsafeWindow.postMessage({
  9181. action: "lastPage",
  9182. command: 'pagetual'
  9183. }, '*');
  9184. }
  9185. return;
  9186. }
  9187. isLoading = false;
  9188. }
  9189. showedLastPageTips = false;
  9190. let pvGallery = document.querySelector("span.pv-gallery-container");
  9191. if (pvGallery && pvGallery.style.display !== "none") return;
  9192. let insert = ruleParser.getInsert();
  9193. if (insert) {
  9194. if (curPage === 1) initView();
  9195. /*if (curPage == 1) {
  9196. window.postMessage({
  9197. command: 'pagetual.insert'
  9198. }, '*');
  9199. }*/
  9200. let isJs = ruleParser.curSiteRule.action == 3 || ruleParser.hrefIsJs(nextLink);
  9201. if (!isJs) {
  9202. emuIframe = null;
  9203. lastActiveUrl = nextLink;
  9204. if (location.protocol === "https:" && /^http:/.test(nextLink)) {
  9205. nextLink = nextLink.replace(/^http/, "https");
  9206. }
  9207. }
  9208. isLoading = true;
  9209. if (curPage !== 1 || !isJs || !ruleParser.curSiteRule.smart) {
  9210. ruleParser.beginLoading(loadingDiv);
  9211. }
  9212. let sleep = ruleParser.curSiteRule.sleep || 0;
  9213. setTimeout(() => {
  9214. if (ruleParser.curSiteRule.pageElementByJs) {
  9215. var over = eles => {
  9216. if (urlChanged || isPause) {
  9217. loadPageOver();
  9218. return;
  9219. }
  9220. if (eles) {
  9221. ruleParser.insertPage(document, eles, nextLink, () => {
  9222. createPageBar(nextLink);
  9223. checkAutoLoadNum();
  9224. }, true);
  9225. } else {
  9226. debug("Stop as no page when get by js");
  9227. isPause = true;
  9228. loadPageOver();
  9229. }
  9230. };
  9231. try {
  9232. ((typeof ruleParser.curSiteRule.pageElementByJs === 'function') ? ruleParser.curSiteRule.pageElementByJs : Function("over", "pageNum",'"use strict";' + ruleParser.curSiteRule.pageElementByJs))(over, curPage);
  9233. } catch(e) {
  9234. debug(e);
  9235. }
  9236. } else if ((forceState === 2 || ruleParser.curSiteRule.action == 2) && !isJs) {
  9237. forceIframe(nextLink, (iframe, refresh) => {
  9238. if (urlChanged || isPause) {
  9239. loadPageOver();
  9240. return;
  9241. }
  9242. if (!refresh) {
  9243. let pageBar = createPageBar(nextLink);
  9244. if (pageBar && iframe && iframe.parentNode) iframe.parentNode.insertBefore(pageBar, iframe);
  9245. }
  9246. loadPageOver();
  9247. checkAutoLoadNum();
  9248. });
  9249. } else if ((forceState === 3 || ruleParser.curSiteRule.action == 1) && !isJs) {
  9250. requestFromIframe(nextLink, async (doc, eles) => {
  9251. if (urlChanged || isPause) {
  9252. loadPageOver();
  9253. return;
  9254. }
  9255. if (eles) {
  9256. await ruleParser.insertPage(doc, eles, nextLink, () => {
  9257. createPageBar(nextLink);
  9258. checkAutoLoadNum();
  9259. }, true);
  9260. } else loadPageOver();
  9261. });
  9262. } else {
  9263. if (!isJs) {
  9264. requestDoc(nextLink, (eles) => {
  9265. if (urlChanged || isPause) {
  9266. loadPageOver();
  9267. return;
  9268. }
  9269. if (eles) {
  9270. createPageBar(nextLink);
  9271. checkAutoLoadNum();
  9272. } else loadPageOver();
  9273. });
  9274. } else {
  9275. emuPage((doc, eles) => {
  9276. if (urlChanged || isPause) {
  9277. loadPageOver();
  9278. return;
  9279. }
  9280. if (eles) {
  9281. ruleParser.insertPage(doc, eles, "", () => {
  9282. createPageBar(nextLink);
  9283. checkAutoLoadNum();
  9284. }, true);
  9285. } else loadPageOver();
  9286. });
  9287. }
  9288. }
  9289. }, sleep);
  9290. }
  9291. }
  9292.  
  9293. function init() {
  9294. if (document.readyState === 'loading' || document.readyState === 'uninitialized') {
  9295. let domReady = e => {
  9296. initRules(() => {
  9297. initPage();
  9298. });
  9299. document.removeEventListener("DOMContentLoaded", domReady, false);
  9300. };
  9301. document.addEventListener("DOMContentLoaded", domReady, false);
  9302. } else {
  9303. initRules(() => {
  9304. initPage();
  9305. });
  9306. }
  9307. }
  9308.  
  9309. function visibilitychangeHandler() {
  9310. document.removeEventListener('visibilitychange', visibilitychangeHandler);
  9311. init();
  9312. }
  9313.  
  9314. setTimeout(() => {
  9315. if (document.hidden) {
  9316. document.addEventListener('visibilitychange', visibilitychangeHandler);
  9317. } else {
  9318. init();
  9319. }
  9320. }, 300);
  9321. })();