东方永页机

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

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

  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.68
  14. // @description Perpetual pages - powerful auto-pager script. Auto fetching next paginated web pages and inserting into current page for infinite scroll. Support thousands of web sites without any rule.
  15. // @description:zh-CN 终极自动翻页 - 加载并拼接下一分页内容至当前页尾,智能适配任意网页
  16. // @description:zh-TW 終極自動翻頁 - 加載並拼接下一分頁內容至當前頁尾,智能適配任意網頁
  17. // @description:ja Webページを自動で読み込み継ぎ足し表示を行うブラウザ拡張です、次のページ付けされた Web ページの自動読み込みと現在のページへの挿入 ルールなしで何千もの Web サイトをサポートします。
  18. // @description:ko 페이지가 매겨진 다음 웹 페이지를 자동으로 로드하고 현재 페이지에 삽입합니다. 규칙 없이 수천 개의 웹 사이트를 지원합니다.
  19. // @description:ru Автоматическая подгрузка следующих страниц и вставка их содержимого в текущую страницу. Поддерживает тысячи сайтов даже с настройками по умолчанию.
  20. // @description:de Automatisches Laden der nächsten paginierten Webseiten und Einfügen in die aktuelle Seite. Unterstützen Sie Tausende von Websites ohne Regeln.
  21. // @description:es Carga automática de las siguientes páginas web paginadas e inserción en la página actual. Admite miles de sitios web sin ninguna regla.
  22. // @description:fr Chargement automatique des pages Web paginées suivantes et insertion dans la page en cours. Prend en charge des milliers de sites Web sans aucune règle.
  23. // @description:it Caricamento automatico delle pagine Web impaginate successive e inserimento nella pagina corrente. Supporta migliaia di siti web senza alcuna regola.
  24. // @author hoothin
  25. // @license MPL-2.0
  26. // @match *://*/*
  27. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAdVBMVEUAAAD3VU33VU32VEz8U073VU32VU33VU32VUz0Uk/3VE32VU32VUz2VU32VU32VU32VU33VU33U0z2VU34Wkv3VE32VUz/mpj/nJj2VUz2VU32VE33VEz2VU32VU32VUz3VE32VEz3VE3/mZf2Vkz2VU3/mpilFFolAAAAJXRSTlMA3Lp/GvTBT5YQLuawZ/DOyZwlPQeKc21N04+FX1bqpm9DNoB4T68ePwAAAitJREFUWMPt1tuasiAUBuCFCG5Rs3QybTPV1/1f4v/3PDkyIojn8x5qBrI+ltAfh32/yysmBKvyXb+njb6bDL9kzTd5SzjDAsYT8nFoGSxYe6BVqoNDp2jFDit25BRgVUAODB4YWcETWVTwVNGiGN5iWtBgg4YMCpsoI38dNunmmWyxUTvbPwwbsYR0fIzZLQ0pTG8eieRmBLMmpdH9uimQEf6TNRnXXKLZHixpJtywLzOgMHtFCqdM64DahHRnOE1dsrekm9wr2WtLcAlpdHwcp1pAJySXYnERclzp4+v19jXdmcTvQUJtz+ZaI4i05/V/UGYrCxbaAsOYoNfIKEQxpqQuzCgJJJ/3f42O8ywEZuMVWi/8hODxGj3GW2b0udkbGULLDOjimAG0S3fLGlBnXQM9irG1CiQdVQi0dqQsOSDlyEEz7Vy9OxxfR71VCXsSB23jMrKJYZXSjw57sqgLn5Z0wolsOCz0RyJkyeYjgz7pwwVq20eboZwtVUl2EnN5gJ50dQZFdryATvABRTr/tJXkUMdaAK5pwtCapwtFLskguwuyMh/Sd9WChQ4sIvIUYSk3PYqQvCQlOC04IfN7PkdjOyRKWhdKXMmiAFt9i3sJ5jxoRuR0vqAghxxwHuqfQE5OHGDKOrwEnqs1DgAZ2e4Eev1d45TN7JfhrQLKgfwMFYAsvp33dXII073aVQLI2gN5S58lfmGnKKFtah7nkgnBZB7zlP7Y/QNiTM6sYNzawwAAAABJRU5ErkJggg==
  28. // @grant GM_xmlhttpRequest
  29. // @grant GM_registerMenuCommand
  30. // @grant GM_notification
  31. // @grant GM_getValue
  32. // @grant GM_setValue
  33. // @grant GM_addStyle
  34. // @grant GM_openInTab
  35. // @grant GM_deleteValue
  36. // @grant GM_info
  37. // @grant GM_setClipboard
  38. // @grant GM.xmlHttpRequest
  39. // @grant GM.registerMenuCommand
  40. // @grant GM.notification
  41. // @grant GM.getValue
  42. // @grant GM.setValue
  43. // @grant GM.addStyle
  44. // @grant GM.openInTab
  45. // @grant GM.deleteValue
  46. // @grant GM.info
  47. // @grant GM.setClipboard
  48. // @homepage https://github.com/hoothin/UserScripts/tree/master/Pagetual
  49. // @supportURL https://github.com/hoothin/UserScripts/issues
  50. // @connect wedata.net
  51. // @connect githubusercontent.com
  52. // @connect ghproxy.com
  53. // @connect hoothin.github.io
  54. // @run-at document-idle
  55. // @connect *
  56. // @contributionURL https://ko-fi.com/hoothin
  57. // @contributionAmount 1
  58. // ==/UserScript==
  59.  
  60. (function() {
  61. 'use strict';
  62.  
  63. const pauseVideo = () => {
  64. setTimeout(() => {
  65. [].forEach.call(document.querySelectorAll("video"), video => {
  66. video.removeAttribute && video.removeAttribute("autoplay");
  67. video.pause && video.pause();
  68. });
  69. }, 1000);
  70. };
  71. if (window.name === 'pagetual-iframe' || (window.frameElement && window.frameElement.name === 'pagetual-iframe')) {
  72. [].forEach.call(document.querySelectorAll("iframe"), iframe => {
  73. iframe.name = 'pagetual-iframe';
  74. });
  75. var domloaded = function() {
  76. window.parent.postMessage('pagetual-iframe:DOMLoaded', '*');
  77. };
  78. if (window.opera) {
  79. document.addEventListener('DOMContentLoaded', domloaded, false);
  80. pauseVideo();
  81. } else {
  82. domloaded();
  83. if (document.readystate === 'complete') {
  84. pauseVideo();
  85. } else {
  86. window.addEventListener('load', () => {
  87. pauseVideo();
  88. }, false);
  89. }
  90. }
  91. if (getComputedStyle(document.documentElement).display === 'none') {
  92. document.documentElement.style.display = 'block';
  93. }
  94. if (document.body && getComputedStyle(document.body).display === 'none') {
  95. document.body.style.display = 'block';
  96. }
  97. return;
  98. }
  99.  
  100. if (window.top !== window.self) {
  101. try {
  102. if (window.self.innerWidth < 300 || window.self.innerHeight < 300) {
  103. return;
  104. }
  105. } catch(e) {
  106. return;
  107. }
  108. }
  109.  
  110. const noRuleTest = false;
  111. const lang = navigator.appName === "Netscape" ? navigator.language : navigator.userLanguage;
  112. const langData = [
  113. {
  114. name: "English",
  115. match: ["en"],
  116. lang: {
  117. enableDebug: "Enable debug output",
  118. updateNotification: "Notification after rules updated",
  119. disable: "Disable",
  120. disableSite: "Toggle disabled state",
  121. disableSiteTips: "Disabled on this site",
  122. enableSiteTips: "Enabled on this site",
  123. enable: "Enable",
  124. toTop: "To Top",
  125. toBottom: "To Bottom",
  126. current: "Current Page",
  127. forceIframe: "Force to join next page",
  128. cancelForceIframe: "Cancel Force join",
  129. configure: "Configure",
  130. firstUpdate: "Click here to initialize the rules",
  131. update: "Update online rules",
  132. click2update: "Click to update rules from url now",
  133. loadNow: "Load next automatically",
  134. loadConfirm: "How much pages do you want to load? (0 means infinite)",
  135. noNext: "No next link found, please create a new rule",
  136. passSec: "Updated #t# seconds ago",
  137. passMin: "Updated #t# minutes ago",
  138. passHour: "Updated #t# hours ago",
  139. passDay: "Updated #t# days ago",
  140. cantDel: "Can't delete buildin rules",
  141. confirmDel: "Are you sure you want to delete this rule?",
  142. updateSucc: "Update succeeded",
  143. beginUpdate: "Begin update, wait a minute please",
  144. customUrls: "Import Pagetual or AutoPagerize rule url, One url per line",
  145. customRules: "Input custom rules. <a href='#t#'>✍️Contribute rules</a>",
  146. save: "Save",
  147. loadingText: "Shojo Now Loading...",
  148. opacity: "Opacity",
  149. opacityPlaceholder: "0: hide spacer",
  150. hideBar: "Hide the paging spacer",
  151. hideBarButNoStop: "Hide but not stop",
  152. dbClick2Stop: "Double-click on the blank space to pause",
  153. sortTitle: "Sorting takes effect after the next rule update",
  154. autoRun: "Auto enable (blacklist mode)",
  155. autoLoadNum: "Amount for preload pages",
  156. turnRate: "Turn the next page when it's less than 【X】 times page height from the footer",
  157. inputPageNum: "Enter page number to jump",
  158. enableHistory: "Write browsing history after page turning",
  159. enableHistoryAfterInsert: "Write browsing history immediately after splicing, otherwise write after browsing",
  160. contentVisibility: "Automatically switch contentVisibility to improve rendering performance",
  161. initRun: "Turn pages immediately after opening",
  162. preload: "Preload next page for speeding up",
  163. click2ImportRule: "Click to import base rules link, then wait until the update is complete: ",
  164. forceAllBody: "Join full body of page?",
  165. openInNewTab: "Open urls of additions in new tab",
  166. importSucc: "Import completed",
  167. import: "Import",
  168. editCurrent: "Edit rule for current",
  169. editBlacklist: "Edit the blacklist urls, line by line, Support ? * for wildcard",
  170. upBtnImg: "Icon of back to top",
  171. downBtnImg: "Icon of go to footer",
  172. sideControllerIcon: "Icon of sidebar",
  173. loadingTextTitle: "Loading text",
  174. dbClick2StopCtrl: "Ctrl key",
  175. dbClick2StopAlt: "Alt key",
  176. dbClick2StopShift: "Shift key",
  177. dbClick2StopMeta: "Meta key",
  178. dbClick2StopKey: "Shortcut key",
  179. pageElementCss: "Custom style for main page elements",
  180. customCss: "Custom complete css",
  181. firstAlert: "You have not imported the base rule, please select the appropriate rule to import",
  182. picker: "Pagetual page element picker",
  183. closePicker: "Close Pagetual picker",
  184. pickerPlaceholder: "Element selector, Leave empty if you have no idea",
  185. pickerCheck: "Check selector and copy",
  186. switchSelector: "Click to switch element",
  187. gotoEdit: "Go to edit rule with current selector",
  188. manualMode: "Disable splicing, manually turn pages with the right arrow keys (or dispatch event 'pagetual.next')",
  189. clickMode: "Disable splicing, automatically click the next page when scrolling to the end of the page",
  190. pageBarMenu: "Click the center of the page bar to open the picker menu",
  191. nextSwitch: "Switch next link",
  192. arrowToScroll: "Press left arrow key to scroll prev and right arrow key to scroll next",
  193. sideController: "Display the paging control bar in the sidebar",
  194. sideControllerScroll: "Scroll toggle",
  195. sideControllerAlways: "Always show",
  196. hideLoadingIcon: "Hide loading animation",
  197. hideBarArrow: "Hide arrow for page bar",
  198. duplicate: "Duplicate Pagetual have been installed, check your script manager!",
  199. forceStateIframe: "Embed full page as iframe",
  200. forceStateDynamic: "Load dynamic content via iframe",
  201. forceStateDisable: "Disable page turning on this site",
  202. autoScrollRate: "Scroll speed (1~1000)",
  203. disableAutoScroll: "Stop Auto Scroll",
  204. enableAutoScroll: "Enable Auto Scroll",
  205. toggleAutoScroll: "Toggle Auto Scroll",
  206. ruleRequest: "Rule Request",
  207. page: "Page ",
  208. prevPage: "Prev page",
  209. nextPage: "Next page",
  210. errorRulesMustBeArray: "Rules must be a Array!",
  211. errorJson: "JSON error, check again!",
  212. editSuccess: "Edit successfully",
  213. errorWrongUrl: "Wrong url, check again!",
  214. errorAlreadyExists: "Already exists!",
  215. settingsSaved: "The settings are saved, refresh to view",
  216. iframe: "Iframe",
  217. dynamic: "Dynamic",
  218. reloadPage: "Edit completed, reload page now?",
  219. copied: "Copied",
  220. noValidContent: "No valid content detected, Captcha action may be required, click to view",
  221. outOfDate: "The script is outdated, update to the latest version in time!",
  222. hideBarTips: "Hide the pagination bar, toggle immersive experience",
  223. setConfigPage: "Set current page as the default configuration page",
  224. wedata2github: "Change the wedata address to the mirror address in the github repository",
  225. addOtherProp: "Add rule property",
  226. addNextSelector: "Add selector content as nextLink",
  227. addPageSelector: "Add selector content as pageElement",
  228. propName: "Enter rule property name",
  229. propValue: "Enter rule property value",
  230. customFirst: "Ignore cache for local custom rules",
  231. rulesExample: "Rules Example",
  232. lastPage: "Reached the last page",
  233. lastPageTips: "Show tips when reaching the last page"
  234. }
  235. },
  236. {
  237. //Translated by SrKalopsia (srkalopsia@gmail.com).
  238. name: "Español",
  239. match: ["es", "es-ES"],
  240. lang: {
  241. enableDebug: "Habilitar salida de depuración",
  242. updateNotification: "Notificación después de actualizar las reglas",
  243. disable: "Desactivar",
  244. disableSite: "Alternar estado desactivado",
  245. disableSiteTips: "Desactivado en este sitio",
  246. enableSiteTips: "Activado en este sitio",
  247. enable: "Habilitar",
  248. toTop: "Ir al inicio",
  249. toBottom: "Ir al final",
  250. current: "Página actual",
  251. forceIframe: "Forzar para unirse a la siguiente página",
  252. cancelForceIframe: "Cancelar unión forzada",
  253. configure: "Configurar",
  254. firstUpdate: "Haga clic aquí para inicializar las reglas",
  255. update: "Actualizar reglas en línea",
  256. click2update: "Haga clic para actualizar las reglas desde la URL ahora",
  257. loadNow: "Cargar el siguiente automáticamente",
  258. loadConfirm: "¿Cuántas páginas desea cargar? (0 significa infinito)",
  259. noNext: "No se encontró el enlace siguiente, por favor cree una nueva regla",
  260. passSec: "Actualizado hace #t# segundos",
  261. passMin: "Actualizado hace #t# minutos",
  262. passHour: "Actualizado hace #t# horas",
  263. passDay: "Actualizado hace #t# días",
  264. cantDel: "No se pueden eliminar las reglas incorporadas",
  265. confirmDel: "¿Está seguro de que desea eliminar esta regla?",
  266. updateSucc: "Actualización exitosa",
  267. beginUpdate: "Comenzar actualización, espere un momento por favor",
  268. customUrls: "Importar URL de reglas de Pagetual o AutoPagerize, una URL por línea",
  269. customRules: "Introduzca reglas personalizadas. <a href='#t#'>✍️Contribuir reglas</a>",
  270. save: "Guardar",
  271. loadingText: "Shojo Cargando...",
  272. opacity: "Opacidad",
  273. opacityPlaceholder: "0: ocultar espaciador",
  274. hideBar: "Ocultar el espaciador de paginación",
  275. hideBarButNoStop: "Ocultar pero no detener",
  276. dbClick2Stop: "Haga doble clic en el espacio en blanco para pausar",
  277. sortTitle: "La ordenación surtirá efecto después de la próxima actualización de reglas",
  278. autoRun: "Habilitar automáticamente (modo lista negra)",
  279. autoLoadNum: "Cantidad de páginas para precargar",
  280. turnRate: "Pasar a la siguiente página cuando esté a menos de 【X】 veces la altura de la página desde el pie de página",
  281. inputPageNum: "Ingrese el número de página para saltar",
  282. enableHistory: "Escribir historial de navegación después de pasar la página",
  283. enableHistoryAfterInsert: "Escribir historial de navegación inmediatamente después de unir, de lo contrario escribir después de navegar",
  284. contentVisibility: "Cambiar automáticamente la visibilidad del contenido para mejorar el rendimiento de renderización",
  285. initRun: "Pasar páginas inmediatamente después de abrir",
  286. preload: "Precargar la siguiente página para acelerar",
  287. click2ImportRule: "Haga clic para importar el enlace de reglas base, luego espere hasta que la actualización esté completa: ",
  288. forceAllBody: "¿Unir el cuerpo completo de la página?",
  289. openInNewTab: "Abrir URLs de adiciones en una nueva pestaña",
  290. importSucc: "Importación completada",
  291. import: "Importar",
  292. editCurrent: "Editar regla para la actual",
  293. editBlacklist: "Editar URLs de la lista negra, una por línea, admite ? * para comodín",
  294. upBtnImg: "Icono de volver al inicio",
  295. downBtnImg: "Icono de ir al pie de página",
  296. sideControllerIcon: "Icono de la barra lateral",
  297. loadingTextTitle: "Texto de carga",
  298. dbClick2StopCtrl: "Tecla Ctrl",
  299. dbClick2StopAlt: "Tecla Alt",
  300. dbClick2StopShift: "Tecla Shift",
  301. dbClick2StopMeta: "Tecla Meta",
  302. dbClick2StopKey: "Tecla de acceso rápido",
  303. pageElementCss: "Estilo personalizado para los elementos principales de la página",
  304. customCss: "CSS completo personalizado",
  305. firstAlert: "No ha importado la regla base, por favor seleccione la regla adecuada para importar",
  306. picker: "Selector de elementos de página de Pagetual",
  307. closePicker: "Cerrar selector de Pagetual",
  308. pickerPlaceholder: "Selector de elementos, déjelo vacío si no tiene idea",
  309. pickerCheck: "Comprobar selector y copiar",
  310. switchSelector: "Haga clic para cambiar el elemento",
  311. gotoEdit: "Ir a editar la regla con el selector actual",
  312. manualMode: "Deshabilitar unión, pasar páginas manualmente con las teclas de flecha derecha (o despachar evento 'pagetual.next')",
  313. clickMode: "Deshabilitar unión, hacer clic automáticamente en la siguiente página al desplazarse al final de la página",
  314. pageBarMenu: "Haga clic en el centro de la barra de página para abrir el menú del selector",
  315. nextSwitch: "Cambiar al siguiente enlace",
  316. arrowToScroll: "Presione la tecla de flecha izquierda para desplazarse anterior y la tecla de flecha derecha para desplazarse siguiente",
  317. sideController: "Mostrar la barra de control de paginación en la barra lateral",
  318. sideControllerScroll: "Alternar desplazamiento",
  319. sideControllerAlways: "Mostrar siempre",
  320. hideLoadingIcon: "Ocultar animación de carga",
  321. hideBarArrow: "Ocultar flecha para la barra de página",
  322. duplicate: "Pagetual duplicado ha sido instalado, ¡revise su gestor de scripts!",
  323. forceStateIframe: "Incrustar página completa como iframe",
  324. forceStateDynamic: "Cargar contenido dinámico a través de iframe",
  325. forceStateDisable: "Deshabilitar pasar páginas en este sitio",
  326. autoScrollRate: "Velocidad de desplazamiento (1~1000)",
  327. disableAutoScroll: "Detener desplazamiento automático",
  328. enableAutoScroll: "Habilitar desplazamiento automático",
  329. toggleAutoScroll: "Alternar desplazamiento automático",
  330. ruleRequest: "Solicitud de regla",
  331. page: "Página ",
  332. prevPage: "Página anterior",
  333. nextPage: "Página siguiente",
  334. errorRulesMustBeArray: "¡Las reglas deben ser un array!",
  335. errorJson: "Error JSON, ¡verifique de nuevo!",
  336. editSuccess: "Editado exitosamente",
  337. errorWrongUrl: "URL incorrecta, ¡verifique de nuevo!",
  338. errorAlreadyExists: "¡Ya existe!",
  339. settingsSaved: "La configuración se ha guardado, actualice para ver",
  340. iframe: "Iframe",
  341. dynamic: "Dinámico",
  342. reloadPage: "Edición completada, ¿recargar página ahora?",
  343. copied: "Copiado",
  344. noValidContent: "No se detectó contenido válido, puede ser necesario realizar una acción de Captcha, haga clic para ver",
  345. outOfDate: "El script está desactualizado, ¡actualice a la última versión a tiempo!",
  346. hideBarTips: "Ocultar la barra de paginación, alternar experiencia inmersiva",
  347. setConfigPage: "Establecer la página actual como la página de configuración predeterminada",
  348. wedata2github: "Cambiar la dirección de wedata a la dirección espejo en el repositorio de GitHub",
  349. addOtherProp: "Agregar propiedad de regla",
  350. addNextSelector: "Agregar contenido del selector como nextLink",
  351. addPageSelector: "Agregar contenido del selector como pageElement",
  352. propName: "Ingrese el nombre de la propiedad de la regla",
  353. propValue: "Ingrese el valor de la propiedad de la regla",
  354. customFirst: "Ignorar caché para reglas personalizadas locales",
  355. rulesExample: "Ejemplo de reglas",
  356. lastPage: "Llegó a la última página",
  357. lastPageTips: "Mostrar consejos al llegar a la última página"
  358. }
  359. },
  360. {
  361. //Translated by Prankster 199 (vfggf95565).
  362. name: "Arabic",
  363. match: ["ar", "ar-AE", "ar-BH", "ar-DZ", "ar-EG", "ar-IQ", "ar-JO", "ar-KW", "ar-LB", "ar-LY", "ar-MA", "ar-OM", "ar-QA", "ar-SA", "ar-SY", "ar-TN", "ar-YE"],
  364. lang: {
  365. enableDebug: "تمكين تصحيح الأخطاء",
  366. updateNotification: "إشعار بعد تحديث القواعد",
  367. disable: "معطل",
  368. disableSite: "تبديل حالة التعطيل/التفعيل للموقع",
  369. disableSiteTips: "معطل على هذا الموقع",
  370. enableSiteTips: "مفعل على هذا الموقع",
  371. enable: "مفعل",
  372. toTop: "إلى الأعلى",
  373. toBottom: "إلى الأسفل",
  374. current: "الصفحة الحالية",
  375. forceIframe: "إجبار على الانضمام للصفحة التالية",
  376. cancelForceIframe: "إلغاء الانضمام القسري",
  377. configure: "إعداد",
  378. firstUpdate: "انقر هنا لتفعيل القواعد لأول مرة",
  379. update: "تحديث القواعد عبر الإنترنت",
  380. click2update: "انقر لتحديث القواعد من الرابط الآن",
  381. loadNow: "تحميل التالي تلقائيًا",
  382. loadConfirm: "كم عدد الصفحات التي ترغب تحميلها؟ (0 يعني لانهائي)",
  383. noNext: "لم يتم العثور على رابط الصفحة التالية، يرجى إنشاء قاعدة جديدة",
  384. passSec: "تم التحديث منذ #t# ثانية",
  385. passMin: "تم التحديث منذ #t# دقيقة",
  386. passHour: "تم التحديث منذ #t# ساعة",
  387. passDay: "تم التحديث منذ #t# يوم",
  388. cantDel: "لا يمكن حذف القواعد المدمجة",
  389. confirmDel: "هل أنت متأكد من حذف هذه القاعدة؟",
  390. updateSucc: "تم التحديث بنجاح",
  391. beginUpdate: "بدأ التحديث، يرجى الانتظار لحظة",
  392. customUrls: "استيراد رابط قاعدة Pagetual أو AutoPagerize، رابط واحد لكل سطر",
  393. customRules: "إدخال القواعد المخصصة. <a href='#t#'>✍️ساهم بالقواعد</a>",
  394. save: "حفظ",
  395. /* From the creator hoothin :
  396. "Shojo Now Loading..." is a meme that refers to the game loading text in the Japanese Touhou (東方) game series. */
  397. loadingText: "جارٍ التحميل...",
  398. opacity: "الشفافية",
  399. opacityPlaceholder: "0: إخفاء الفاصل",
  400. hideBar: "إخفاء الفاصل التصفحي",
  401. hideBarButNoStop: "إخفاء، لكن لا تتوقف",
  402. dbClick2Stop: "انقر مزدوج على المساحة الفارغة للإيقاف",
  403. sortTitle: "يتم تفعيل الفرز بعد التحديث التالي للقواعد",
  404. autoRun: "تمكين تلقائي (وضع القائمة السوداء)",
  405. autoLoadNum: "عدد صفحات التحميل المسبق",
  406. turnRate: "الانتقال للصفحة التالية عندما تكون المسافة أقل من 【X】 مرات ارتفاع الصفحة من التذييل",
  407. inputPageNum: "أدخل رقم الصفحة للانتقال",
  408. enableHistory: "كتابة سجل التصفح بعد تحويل الصفحة",
  409. enableHistoryAfterInsert: "كتابة سجل التصفح فورًا بعد الدمج، أو بعد التصفح",
  410. contentVisibility: "التنقل التلقائي لرؤية المحتوى, لتحسين أداء العرض",
  411. initRun: "الانتقال بين الصفحات فور الفتح",
  412. preload: "تحميل الصفحة التالية مسبقًا لتسريع الأداء",
  413. click2ImportRule: "انقر لاستيراد رابط القواعد الأساسية، ثم انتظر حتى يكتمل التحديث",
  414. forceAllBody: "دمج كامل الصفحة كإطار؟",
  415. openInNewTab: "فتح الروابط الإضافية في علامة تبويب جديدة",
  416. importSucc: "تم الاستيراد بنجاح",
  417. import: "استيراد",
  418. editCurrent: "تحرير القاعدة للحالية",
  419. editBlacklist: "تحرير عناوين القائمة السوداء، سطر بسطر، دعم؟ * للرموز المتحركة",
  420. upBtnImg: "أيقونة العودة إلى الأعلى",
  421. downBtnImg: "أيقونة الانتقال إلى الأسفل",
  422. sideControllerIcon: "أيقونة الشريط الجانبي",
  423. loadingTextTitle: "تحميل النص",
  424. dbClick2StopCtrl: "مفتاح Ctrl",
  425. dbClick2StopAlt: "مفتاح Alt",
  426. dbClick2StopShift: "مفتاح Shift",
  427. dbClick2StopMeta: "مفتاح Meta",
  428. dbClick2StopKey: "مفاتيح الاختصار",
  429. pageElementCss: "نمط مخصص لعناصر الصفحة الرئيسية",
  430. customCss: "مخصص بالكامل CSS نمط",
  431. firstAlert: "لم تستورد القاعدة الأساسية بعد، يرجى اختيار القاعدة المناسبة للاستيراد",
  432. picker: "محدد عناصر الصفحة Pagetual",
  433. closePicker: "إغلاق محدد Pagetual",
  434. pickerPlaceholder: "محدد العناصر، اتركه فارغًا إذا كنت لا تعرف",
  435. pickerCheck: "تحقق من المحدد ونسخ",
  436. switchSelector: "انقر للتبديل بين العناصر",
  437. gotoEdit: "اذهب لتحرير القاعدة بالمحدد الحالي",
  438. manualMode: "تعطيل الدمج/الربط، واستخدام مفتاح الاتجاه الأيمن يدويًا للتمرير، واستخدام مفتاح السهم الأيسر للرجوع",
  439. clickMode: "تعطيل الدمج/الربط، عند التمرير إلى نهاية الصفحة، سيتم النقر تلقائيًا على الصفحة التالية",
  440. pageBarMenu: "انقر على مركز شريط الصفحة لفتح قائمة التحديد",
  441. nextSwitch: "تبديل الرابط التالي",
  442. arrowToScroll: "انقر على مفتاح السهم الأيمن للتمرير التالي ومفتاح السهم الأيسر للتمرير السابق",
  443. sideController: "عرض شريط التحكم في التصفح الترقيم في الشريط الجانبي",
  444. sideControllerScroll: "تبديل التمرير",
  445. sideControllerAlways: "عرض دائمًا",
  446. hideLoadingIcon: "إخفاء رمز التحميل",
  447. hideBarArrow: "إخفاء سهم شريط الصفحة",
  448. duplicate: "تم تثبيت Pagetual مكرر، تحقق من مدير النصوص البرمجية الخاص بك!",
  449. forceStateIframe: "تضمين الصفحة بالكامل كإطار",
  450. forceStateDynamic: "تحميل المحتوى الديناميكي عبر الإطار",
  451. forceStateDisable: "تعطيل تحويل الصفحات على هذا الموقع",
  452. autoScrollRate: "سرعة التمرير (1~1000)",
  453. disableAutoScroll: "إيقاف التمرير التلقائي",
  454. enableAutoScroll: "تمكين التمرير التلقائي",
  455. toggleAutoScroll: "تبديل التمرير التلقائي",
  456. ruleRequest: "طلب قاعدة",
  457. page: "صفحة ",
  458. prevPage: "الصفحة السابقة",
  459. nextPage: "الصفحة التالية",
  460. errorRulesMustBeArray: "يجب أن تكون القواعد مصفوفة!",
  461. errorJson: "خطأ في JSON، تحقق مرة أخرى!",
  462. editSuccess: "تم التحرير بنجاح",
  463. errorWrongUrl: "عنوان URL خاطئ، تحقق مرة أخرى!",
  464. errorAlreadyExists: "موجود بالفعل!",
  465. settingsSaved: "تم حفظ الإعدادات، قم بالتحديث لعرض",
  466. iframe: "إطار",
  467. dynamic: "ديناميكي",
  468. reloadPage: "اكتمل التحرير، إعادة تحميل الصفحة الآن؟",
  469. copied: "تم النسخ",
  470. noValidContent: "لم يتم الكشف عن محتوى صالح، قد يكون الإجراء Captcha مطلوبًا، انقر لعرض",
  471. outOfDate: "النص البرمجي قديم، قم بالتحديث إلى الإصدار الأحدث في الوقت المناسب!",
  472. hideBarTips: "إخفاء شريط التحكم في التصفح الترقيم ، والتبديل لوضع كامل الصفحة",
  473. setConfigPage: "تعيين الصفحة الحالية كصفحة الإعداد الافتراضية",
  474. wedata2github: "تغيير عنوان الويب داتا إلى العنوان البديل المرآة, في مستودع جيت هاب",
  475. addOtherProp: "إضافة خاصية قاعدة",
  476. addNextSelector: "إضافة محتوى المحدد كـ nextLink",
  477. addPageSelector: "إضافة محتوى المحدد كـ pageElement",
  478. propName: "أدخل اسم خاصية القاعدة",
  479. propValue: "أدخل قيمة خاصية القاعدة",
  480. customFirst: "تجاهل ذاكرة التخزين المؤقت للقواعد المخصصة المحلية",
  481. rulesExample: "مثال على القواعد",
  482. lastPage: "تم الوصول إلى الصفحة الأخيرة",
  483. lastPageTips: "عرض تلميحات عند الوصول إلى الصفحة الأخيرة"
  484. }
  485. },
  486. {
  487. name: "简体中文",
  488. match: ["zh-CN", "zh-SG"],
  489. lang: {
  490. enableDebug: "调试模式,输出信息至控制台",
  491. updateNotification: "规则更新后提示",
  492. disable: "暂时禁用",
  493. disableSite: "站点禁用开关",
  494. disableSiteTips: "已在此站禁用",
  495. enableSiteTips: "已在此站启用",
  496. enable: "启用自动翻页",
  497. toTop: "回到顶部",
  498. toBottom: "前往页尾",
  499. current: "当前页",
  500. forceIframe: "强制拼接",
  501. cancelForceIframe: "取消强制拼接",
  502. configure: "打开配置页面",
  503. firstUpdate: "点击此处初始化规则",
  504. update: "更新在线规则",
  505. click2update: "点击立即更新规则",
  506. loadNow: "立即翻页",
  507. loadConfirm: "要翻几页?(0为不间断)",
  508. noNext: "没有找到下一页,请新建规则",
  509. passSec: "更新于 #t# 秒前",
  510. passMin: "更新于 #t# 分钟前",
  511. passHour: "更新于 #t# 小时前",
  512. passDay: "更新于 #t# 天前",
  513. cantDel: "无法删除内置规则",
  514. confirmDel: "是否确认要删除此规则?",
  515. updateSucc: "更新成功",
  516. beginUpdate: "正在更新,请耐心等待,不要关闭页面",
  517. customUrls: "导入 Pagetual 或 AutoPagerize 规则 url,一行一条",
  518. customRules: "输入【东方永页机】格式的自定义规则 <a href='#t#'>✍️贡献规则</a>",
  519. save: "保存设置",
  520. loadingText: "少女祈祷中...",
  521. opacity: "不透明值",
  522. opacityPlaceholder: "0: 隐藏分隔条",
  523. hideBar: "隐藏分页隔条",
  524. hideBarButNoStop: "隐藏但不停止",
  525. dbClick2Stop: "空白处双击暂停翻页",
  526. sortTitle: "排序在下次更新规则后生效",
  527. autoRun: "自动启用,否则为白名单模式",
  528. autoLoadNum: "自动加载指定页数",
  529. turnRate: "距离页尾【X】倍页面高度时就开始翻页",
  530. inputPageNum: "输入页码跳转",
  531. enableHistory: "翻页后写入历史记录",
  532. enableHistoryAfterInsert: "拼接后立即写入历史记录,否则浏览完毕后再行写入",
  533. contentVisibility: "自动切换 contentVisibility,提升渲染性能",
  534. initRun: "打开页面后立即尝试翻页,否则滚动至页尾再翻页",
  535. preload: "翻页前预读下一页,加速浏览",
  536. click2ImportRule: "点击下方任意一条添加规则库,并静待更新成功,请预先打开链接确认能正常访问再行导入:",
  537. forceAllBody: "是否拼接整个页面?",
  538. openInNewTab: "使拼接页面的内容在新页面打开",
  539. importSucc: "导入成功",
  540. import: "导入",
  541. editCurrent: "编辑此站规则",
  542. editBlacklist: "编辑黑名单网址,一行一条,支持? *通配符与正则",
  543. upBtnImg: "回到页首图标",
  544. downBtnImg: "前往页尾图标",
  545. sideControllerIcon: "侧边栏图标",
  546. loadingTextTitle: "加载中文字",
  547. dbClick2StopCtrl: "Ctrl",
  548. dbClick2StopAlt: "Alt",
  549. dbClick2StopShift: "Shift",
  550. dbClick2StopMeta: "Meta",
  551. dbClick2StopKey: "快捷键",
  552. pageElementCss: "页面主体框架的样式",
  553. customCss: "自定义 css",
  554. firstAlert: "你还未导入规则库,请选择合适的规则库导入哦",
  555. picker: "东方永页机主体元素抓取器",
  556. closePicker: "关闭东方永页机抓取器",
  557. pickerPlaceholder: "元素选择器,没想法建议留空",
  558. pickerCheck: "检查你编辑的选择器并复制",
  559. switchSelector: "点击切换元素",
  560. gotoEdit: "使用当前的选择器前往编辑规则",
  561. manualMode: "禁用拼接,手动用右方向键翻页,可使用左方向键返回",
  562. clickMode: "禁用拼接,滚动至页尾时自动点击下一页",
  563. pageBarMenu: "点击分隔条中间弹出菜单",
  564. nextSwitch: "切换其他页码",
  565. arrowToScroll: "左方向键滚动至上一页,右方向键滚动至下一页",
  566. sideController: "在侧边显示翻页控制栏",
  567. sideControllerScroll: "滚动开关",
  568. sideControllerAlways: "始终显示",
  569. hideLoadingIcon: "隐藏加载动画",
  570. hideBarArrow: "隐藏分隔条定位箭头",
  571. duplicate: "检测到永页机重复安装,请删除其他脚本管理器中的永页机!",
  572. forceStateIframe: "以 iframe 嵌入整页",
  573. forceStateDynamic: "通过 iframe 加载动态内容后取出",
  574. forceStateDisable: "在此站禁用",
  575. autoScrollRate: "滚动速度(1~1000)",
  576. disableAutoScroll: "停止自动滚动",
  577. enableAutoScroll: "开启自动滚动",
  578. toggleAutoScroll: "自动滚动开关",
  579. ruleRequest: "适配请求",
  580. page: "Page ",
  581. prevPage: "上一页",
  582. nextPage: "下一页",
  583. errorRulesMustBeArray: "规则必须为数组形式!",
  584. errorJson: "JSON 格式有错,请重新检查!",
  585. editSuccess: "编辑成功",
  586. errorWrongUrl: "URL 错误, 请重新检查!",
  587. errorAlreadyExists: "已经存在!",
  588. settingsSaved: "设置已保存,刷新后生效",
  589. iframe: "强制拼接",
  590. dynamic: "动态加载",
  591. reloadPage: "编辑完成,是否立即刷新页面?",
  592. copied: "已复制",
  593. noValidContent: "没有检测到有效内容,可能需要人机校验,点击查看",
  594. outOfDate: "脚本已过时,请及时更新到最新版本!",
  595. hideBarTips: "隐藏分页隔条,沉浸式体验",
  596. setConfigPage: "将当前页面设为默认配置页",
  597. wedata2github: "将 wedata 地址更改为 github 仓库内的镜像地址",
  598. addOtherProp: "添加规则属性",
  599. addNextSelector: "添加选择器内容为 nextLink",
  600. addPageSelector: "添加选择器内容为 pageElement",
  601. propName: "输入规则属性名",
  602. propValue: "输入规则属性值",
  603. customFirst: "为本地自定义规则忽略缓存",
  604. rulesExample: "自定义规则详解",
  605. lastPage: "已到达最后一页",
  606. lastPageTips: "到达最后一页时进行提示"
  607. }
  608. },
  609. {
  610. name: "正體中文",
  611. match: ["zh", "zh-TW", "zh-HK"],
  612. lang: {
  613. enableDebug: "調試模式,輸出信息至控制台",
  614. updateNotification: "規則更新后提示",
  615. disable: "暫時禁用",
  616. disableSite: "站點禁用開關",
  617. disableSiteTips: "已在此站禁用",
  618. enableSiteTips: "已在此站啟用",
  619. enable: "啟用自動翻頁",
  620. toTop: "回到頂部",
  621. toBottom: "前往頁尾",
  622. current: "當前頁",
  623. forceIframe: "強制拼接",
  624. cancelForceIframe: "取消强制拼接",
  625. configure: "打開配置頁面",
  626. firstUpdate: "點擊此處初始化規則",
  627. update: "更新在綫規則",
  628. click2update: "點擊立即更新規則",
  629. loadNow: "立即翻頁",
  630. loadConfirm: "要翻几頁?(0為不間斷)",
  631. noNext: "沒有找到下一頁,請新建規則",
  632. passSec: "更新于 #t# 秒前",
  633. passMin: "更新于 #t# 分鐘前",
  634. passHour: "更新于 #t# 小時前",
  635. passDay: "更新于 #t# 天前",
  636. cantDel: "無法刪除内置規則",
  637. confirmDel: "是否確認要刪除此規則?",
  638. updateSucc: "更新成功",
  639. beginUpdate: "正在更新,請稍候",
  640. customUrls: "導入 Pagetual 或 AutoPagerize 規則 url,一行一條",
  641. customRules: "輸入【東方永頁機】格式的自定義規則 <a href='#t#'>✍️貢獻規則</a>",
  642. save: "存儲設置",
  643. loadingText: "少女祈禱中...",
  644. opacity: "不透明值",
  645. opacityPlaceholder: "0: 隱藏分隔條",
  646. hideBar: "隱藏分頁隔條",
  647. hideBarButNoStop: "隱藏但不停止",
  648. dbClick2Stop: "空白處雙擊暫停翻頁",
  649. sortTitle: "排序在下次更新規則後生效",
  650. autoRun: "自動啓用,否則為白名單模式",
  651. autoLoadNum: "自動加載指定頁數",
  652. turnRate: "距離頁尾【X】倍頁面高度時就開始翻頁",
  653. inputPageNum: "輸入頁碼跳轉",
  654. enableHistory: "翻頁后寫入歷史記錄",
  655. enableHistoryAfterInsert: "拼接後立即寫入歷史記錄,否則瀏覽完畢後再行寫入",
  656. contentVisibility: "自動切換 contentVisibility,提升渲染性能",
  657. initRun: "打開頁面后立即嘗試翻頁,否則滾動至頁尾再翻頁",
  658. preload: "翻頁前預讀下一頁,加速瀏覽",
  659. click2ImportRule: "點擊下方添加特殊規則庫,并靜待更新成功:",
  660. forceAllBody: "是否拼接整個頁面?",
  661. openInNewTab: "使拼接頁面的内容在新頁面打開",
  662. importSucc: "導入成功",
  663. import: "導入",
  664. editCurrent: "編輯此站規則",
  665. editBlacklist: "編輯黑名單網址,一行一條,支持? *通配符與正則",
  666. upBtnImg: "回到頁首圖標",
  667. downBtnImg: "前往頁尾圖標",
  668. sideControllerIcon: "側邊欄圖標",
  669. loadingTextTitle: "加載中文字",
  670. dbClick2StopCtrl: "Ctrl",
  671. dbClick2StopAlt: "Alt",
  672. dbClick2StopShift: "Shift",
  673. dbClick2StopMeta: "Meta",
  674. dbClick2StopKey: "快捷鍵",
  675. pageElementCss: "頁面主體框架的樣式",
  676. customCss: "自定義 css",
  677. firstAlert: "你還未導入規則庫,請選擇合適的規則庫導入哦",
  678. picker: "東方永頁機主體元素抓取器",
  679. closePicker: "關閉東方永頁機抓取器",
  680. pickerPlaceholder: "元素選擇器,沒想法建議留空",
  681. pickerCheck: "檢查你編輯的選擇器並複製",
  682. switchSelector: "點擊切換元素",
  683. gotoEdit: "使用當前的選擇器前往編輯規則",
  684. manualMode: "禁用拼接,手動用右方向鍵翻頁,左方向鍵返回",
  685. clickMode: "禁用拼接,滾動至頁尾時自動點擊下一頁",
  686. pageBarMenu: "點擊分隔條中間彈出菜單",
  687. nextSwitch: "切換其他頁碼",
  688. arrowToScroll: "左方向鍵滾動至上一頁,右方向鍵滾動至下一頁",
  689. sideController: "在側邊顯示翻頁控制欄",
  690. sideControllerScroll: "滾燈開關",
  691. sideControllerAlways: "始終顯示",
  692. hideLoadingIcon: "隱藏加載動畫",
  693. hideBarArrow: "隱藏分隔條定位箭頭",
  694. duplicate: "檢測到永頁機重複安裝,請刪除其他腳本管理器中的永頁機!",
  695. forceStateIframe: "以 iframe 嵌入整頁",
  696. forceStateDynamic: "通過 iframe 加載動態內容後取出",
  697. forceStateDisable: "在此站禁用",
  698. autoScrollRate: "滾動速度(1~1000)",
  699. disableAutoScroll: "停止自動滾動",
  700. enableAutoScroll: "開啟自動滾動",
  701. toggleAutoScroll: "自動滾動開關",
  702. ruleRequest: "適配請求",
  703. page: "Page ",
  704. prevPage: "上一頁",
  705. nextPage: "下一頁",
  706. errorRulesMustBeArray: "規則必須為陣列形式!",
  707. errorJson: "JSON 格式有錯,請重新檢查!",
  708. editSuccess: "編輯成功",
  709. errorWrongUrl: "URL 錯誤, 請重新檢查!",
  710. errorAlreadyExists: "已經存在!",
  711. settingsSaved: "設置已保存,刷新後生效",
  712. iframe: "強制拼接",
  713. dynamic: "動態加載",
  714. reloadPage: "編輯完成,是否立即刷新頁面?",
  715. copied: "已復制",
  716. noValidContent: "沒有檢測到有效内容,可能需要人機校驗,點擊查看",
  717. outOfDate: "脚本已過時,請及時更新到最新版本!",
  718. hideBarTips: "隱藏分頁隔條,沉浸式體驗",
  719. setConfigPage: "將當前頁面設為默認配置頁",
  720. wedata2github: "將 wedata 地址更改為 github 倉庫內的鏡像地址",
  721. addOtherProp: "添加規則屬性",
  722. addNextSelector: "添加選擇器內容為 nextLink",
  723. addPageSelector: "添加選擇器內容為 pageElement",
  724. propName: "輸入規則屬性名",
  725. propValue: "輸入規則屬性值",
  726. customFirst: "為本地自定義規則忽略緩存",
  727. rulesExample: "自定義規則詳解",
  728. lastPage: "已到達最後一頁",
  729. lastPageTips: "到達最後一頁時進行提示"
  730. }
  731. },
  732. {
  733. name: "日本語",
  734. match: ["ja"],
  735. lang: {
  736. enableDebug: "デバッグモード",
  737. updateNotification: "ルール更新後の通知",
  738. disable: "一時的に無効",
  739. disableSite: "無効状態の切り替え",
  740. disableSiteTips: "このサイトで既に無効になっています",
  741. enableSiteTips: "このサイトで既に有効になっています",
  742. enable: "ページめくりを有効にする",
  743. toTop: "トップに戻る",
  744. toBottom: "ページの下部に移動",
  745. current: "現在のページ",
  746. forceIframe: "強制ステッチ",
  747. cancelForceIframe: "強制ステッチをキャンセル",
  748. configure: "設定ページを開く",
  749. firstUpdate: "ここをクリックしてルールを初期化します",
  750. update: "更新ルール",
  751. click2update: "今すぐルールを更新してください",
  752. loadNow: "今すぐページをめくる",
  753. loadConfirm: "数ページめくりたいですか?(0は途切れない)",
  754. noNext: "次のページが見つかりません、新しいルールを作成してください",
  755. passSec: "#t#秒前に更新",
  756. passMin: "#t#分前に更新",
  757. passHour: "#t#時間前に更新",
  758. passDay: "#t#日前に更新",
  759. cantDel: "組み込みルールを削除できません",
  760. confirmDel: "このルールを削除してもよろしいですか?",
  761. updateSucc: "更新に成功しました",
  762. beginUpdate: "更新中、お待ちください",
  763. customUrls: "インポートルールのURL、1行に1つ",
  764. customRules: "【東方永頁機】の形式でカスタムルールを入力してください <a href='#t#'>✍️寄稿ルール</a>",
  765. save: "設定を保存",
  766. loadingText: "少女祈祷中...",
  767. opacity: "不透明値",
  768. opacityPlaceholder: "0: 隠す",
  769. hideBar: "ページ区切り文字を非表示にします",
  770. hideBarButNoStop: "非表示にするが停止しない",
  771. dbClick2Stop: "空白部分をダブルクリックしてページめくりを一時停止します",
  772. sortTitle: "並べ替えは、次のルールの更新後に有効になります",
  773. autoRun: "自動的に有効",
  774. autoLoadNum: "指定したページ数を自動的に読み込みます",
  775. turnRate: "ページの端からページの高さの【X】倍になったらページをめくる",
  776. inputPageNum: "ジャンプするページ番号を入力",
  777. enableHistory: "ページめくり後の履歴を書く",
  778. enableHistoryAfterInsert: "スプライシングの直後に履歴レコードを書き込みます。それ以外の場合は、閲覧後に書き込みます",
  779. contentVisibility: "contentVisibility を自動的に切り替えてレンダリング パフォーマンスを向上させる",
  780. initRun: "Webページを開いた直後にページをめくる",
  781. preload: "事前に次のページを読む",
  782. click2ImportRule: "以下をクリックして、ルールベースを追加します:",
  783. forceAllBody: "フルページ埋め込み?",
  784. openInNewTab: "スプライスされたページのコンテンツを新しいページで開きます",
  785. importSucc: "インポート完了",
  786. import: "インポート",
  787. editCurrent: "現在のルールの編集",
  788. editBlacklist: "ブラックリストのURLを編集し、1行ずつ、サポート? *ワイルドカード",
  789. upBtnImg: "トップアイコンに戻る",
  790. downBtnImg: "フッターアイコンに移動",
  791. sideControllerIcon: "サイドバー アイコン",
  792. loadingTextTitle: "テキストをロード",
  793. dbClick2StopCtrl: "Ctrlキー",
  794. dbClick2StopAlt: "Altキー",
  795. dbClick2StopShift: "Shiftキー",
  796. dbClick2StopMeta: "Metaキー",
  797. dbClick2StopKey: "Shortcutキー",
  798. pageElementCss: "ページ本文フレームの STYLE",
  799. customCss: "カスタム css",
  800. firstAlert: "ルールベースをインポートしていないため、インポートする適切なルールベースを選択してください",
  801. picker: "Pagetualページ要素ピッカー",
  802. closePicker: "Pagetualピッカーを閉じる",
  803. pickerPlaceholder: "わからない場合は空のままにしてください",
  804. pickerCheck: "セレクターをチェックしてコピー",
  805. switchSelector: "クリックして要素を切り替えます",
  806. gotoEdit: "現在のセレクターでルールを編集する",
  807. manualMode: "スプライシングを無効にします。手動で右の矢印キーを使用してページをめくります",
  808. clickMode: "スティッチングを無効にします。ページの最後までスクロールすると、次のページが自動的にクリックされます",
  809. pageBarMenu: "ページバーの中央をクリックしてメニューをポップアップ表示",
  810. nextSwitch: "次のページに切り替え",
  811. arrowToScroll: "左矢印キーで前へ、右矢印キーで次へ",
  812. sideController: "サイドバーにページング コントロール バーを表示する",
  813. sideControllerScroll: "スクロール スイッチ",
  814. sideControllerAlways: "常に表示",
  815. hideLoadingIcon: "読み込み中のアニメーションを隠す",
  816. hideBarArrow: "分割線の位置矢印を隠す",
  817. duplicate: "Pagetual の重複インストールが検出されました。他のスクリプト マネージャで永続的なページ マシンを削除してください!",
  818. forceStateIframe: "iframe にページ全体を埋め込む",
  819. forceStateDynamic: "iframe 経由で動的コンテンツを読み込む",
  820. forceStateDisable: "このステーションでのページめくりを無効にする",
  821. autoScrollRate: "スクロール速度 (1~1000)",
  822. disableAutoScroll: "自動スクロールを停止します",
  823. EnableAutoScroll: "自動スクロールを有効にする",
  824. toggleAutoScroll: "自動スクロールの切り替え",
  825. ruleRequest: "ルール要求",
  826. page: "Page ",
  827. prevPage: "Prev page",
  828. nextPage: "Next page",
  829. errorRulesMustBeArray: "Rules must be a Array!",
  830. errorJson: "JSON error, check again!",
  831. editSuccess: "Edit successfully",
  832. errorWrongUrl: "Wrong url, check again!",
  833. errorAlreadyExists: "Already exists!",
  834. settingsSaved: "The settings are saved, refresh to view",
  835. iframe: "Iframe",
  836. dynamic: "Dynamic",
  837. reloadPage: "Edit completed, reload page now?",
  838. copied: "Copied",
  839. noValidContent: "有効なコンテンツが検出されませんでした。クリックして表示",
  840. outOfDate: "スクリプトが古くなっています。最新バージョンに更新してください。",
  841. hideBarTips: "ページネーション バーを非表示にします。没入型エクスペリエンス",
  842. setConfigPage: "現在のページをデフォルト設定ページとして設定",
  843. wedata2github: "wedata アドレスを github ウェアハウスのミラー アドレスに変更",
  844. addOtherProp: "ルールプロパティを追加",
  845. addNextSelector: "セレクターのコンテンツを nextLink として追加",
  846. addPageSelector: "セレクタ コンテンツを pageElement として追加",
  847. propName: "ルールのプロパティ名を入力してください",
  848. propValue: "ルールのプロパティ値を入力してください",
  849. customFirst: "ローカルカスタムルールのキャッシュを無視する",
  850. rulesExample: "カスタムルールの詳しい説明",
  851. lastPage: "最後のページに到達しました",
  852. lastPageTips: "最後のページに到達した時にヒントを表示する"
  853. }
  854. },
  855. {
  856. name: "Русский",
  857. match: ["ru", "ru-RU"],
  858. lang: {
  859. enableDebug: "Включить отладку",
  860. updateNotification: "Уведомление после обновления правила",
  861. disable: "Выключить",
  862. disableSite: "Включить/выключить на сайте",
  863. disableSiteTips: "Выключено для этого сайта",
  864. enableSiteTips: "Включено для этого сайта",
  865. enable: "Включить",
  866. toTop: "Наверх",
  867. toBottom: "Вниз",
  868. current: "Текущая страница",
  869. forceIframe: "Подгрузить ещё страницу",
  870. cancelForceIframe: "Отменить подгрузку",
  871. configure: "Настройки",
  872. firstUpdate: "Нажмите здесь, чтобы инициализировать правила",
  873. update: "Обновить правила",
  874. click2update: "Нажмите, чтобы обновить правила",
  875. loadNow: "Загрузить следующую страницу",
  876. loadConfirm: "Сколько страниц вы хотите загрузить? (0 означает бесконечность)",
  877. noNext: "Ссылка на следующую страницу не найдена. Пожалуйста, создайте новое правило",
  878. passSec: "Обновлено #t# секунд назад",
  879. passMin: "Обновлено #t# минут назад",
  880. passHour: "Обновлено #t# часов назад",
  881. passDay: "Обновлено #t# дней назад",
  882. cantDel: "Нельзя удалить правила по умолчанию",
  883. confirmDel: "Вы уверены, что хотите удалить эту ссылку?",
  884. updateSucc: "Правила обновлены",
  885. beginUpdate: "Обновление. Пожалуйста, немного подождите",
  886. customUrls: "Ссылки с правилами для импорта. Одна ссылка на строку",
  887. customRules: "Введите пользовательские правила в формате Pagetual. <a href='#t#'>✍️Улучшить встроенные правила</a>",
  888. save: "Сохранить настройки",
  889. loadingText: "Следующая страница подгружается…",
  890. opacity: "Прозрачность",
  891. opacityPlaceholder: "0 - скрыть",
  892. hideBar: "Скрыть разделитель страниц",
  893. hideBarButNoStop: "Скрыть, но не останавливать",
  894. dbClick2Stop: "Двойной клик на странице для выключения",
  895. sortTitle: "Правило сортировки применится после следующего обновления правил",
  896. autoRun: "Автозапуск (режим черного списка)",
  897. autoLoadNum: "Количество страниц для предзагрузки",
  898. turnRate: "Подгрузить страницу, когда она будет в 【X】 раз больше высоты страницы от конца страницы",
  899. inputPageNum: "Введите номер страницы для перехода",
  900. enableHistory: "Записать историю после переключения страниц",
  901. enableHistoryAfterInsert: "Записать запись истории сразу после вставки, иначе записать после просмотра",
  902. contentVisibility: "Автоматически переключать contentVisibility для повышения производительности рендеринга",
  903. initRun: "Подгружать страницы сразу после открытия",
  904. preload: "Предзагрузка следующей страницы",
  905. click2ImportRule: "Нажмите, чтобы импортировать базовые правила: ",
  906. forceAllBody: "Присоединить страницу целиком?",
  907. openInNewTab: "Открыть дополнительные ссылки в новой вкладке",
  908. importSucc: "Импорт завершен",
  909. import: "Импорт",
  910. editCurrent: "Изменить правило для текущего сайта",
  911. editBlacklist: "Изменить черный список. Одна ссылка на строку. Поддерживаются метасимволы: ? и *",
  912. upBtnImg: "Иконка перехода к началу",
  913. downBtnImg: "Иконка перехода к концу",
  914. sideControllerIcon: "Значок боковой панели",
  915. loadingTextTitle: "Текст во время загрузки",
  916. dbClick2StopCtrl: "Ctrl",
  917. dbClick2StopAlt: "Alt",
  918. dbClick2StopShift: "Shift",
  919. dbClick2StopMeta: "Meta",
  920. dbClick2StopKey: "Клавиша",
  921. pageElementCss: "Пользовательский стиль для основных элементов страницы",
  922. customCss: "Полный пользовательский CSS",
  923. firstAlert: "Вы не импортировали базовое правило. Пожалуйста, выберите соответствующее правило для импорта",
  924. picker: "Pagetual: выбор элемента страницы",
  925. closePicker: "Закрыть окно Pagetual",
  926. pickerPlaceholder: "Если не знаете, что тут писать — оставьте поле пустым",
  927. pickerCheck: "Проверить и скопировать селектор",
  928. switchSelector: "Нажмите для выбора элемента",
  929. gotoEdit: "Перейти к редактированию правила с текущим селектором",
  930. manualMode: "Отключить автоматическую загрузку страниц. Загружать вручную с помощью стрелки вправо (или вызова события 'pagetual.next')",
  931. clickMode: "Отключить \"сшивание\" страниц. При прокрутке до конца автоматически переходить на следующую страницу",
  932. pageBarMenu: "Открывать меню кликом на середину панели страниц",
  933. nextSwitch: "Переключить ссылку на следующую страницу",
  934. arrowToScroll: "Листать страницы клавишами со стрелками влево и вправо",
  935. sideController: "Показать справа панель перемещения по вкладке",
  936. sideControllerScroll: "Переключатель прокрутки",
  937. sideControllerAlways: "Всегда показывать",
  938. hideLoadingIcon: "Скрыть анимацию загрузки",
  939. hideBarArrow: "Скрыть кнопки перемещения на разделителе",
  940. duplicate: "Похоже, Pagetual установлен несколько раз. Пожалуйста, удалите Pagetual из других менеджеров скриптов!",
  941. forceStateIframe: "Вставить полную страницу как iframe",
  942. forceStateDynamic: "Загружать динамический контент через iframe",
  943. forceStateDisable: "Отключить перелистывание страниц на этой станции",
  944. autoScrollRate: "Скорость прокрутки (1~1000)",
  945. disableAutoScroll: "Остановить автоматическую прокрутку",
  946. enableAutoScroll: "Включить автопрокрутку",
  947. toggleAutoScroll: "Переключить автопрокрутку",
  948. ruleRequest: "Запрос правил",
  949. page: "Страница ",
  950. prevPage: "Предыдущая страница",
  951. nextPage: "Следующая страница",
  952. errorRulesMustBeArray: "Правила должны быть массивом!",
  953. errorJson: "Ошибка разбора JSON. Пожалуйста, исправьте его",
  954. editSuccess: "Редактирование успешно",
  955. errorWrongUrl: "Ссылка некорректна. Пожалуйста, исправьте её",
  956. errorAlreadyExists: "Уже существует!",
  957. settingsSaved: "Настройки сохранены. Обновите страницы",
  958. iframe: "iframe",
  959. dynamic: "Динамически",
  960. reloadPage: "Редактирование завершено. Обновить страницу?",
  961. copied: "Скопировано",
  962. noValidContent: "Действительный контент не обнаружен, нажмите для просмотра",
  963. outOfDate: "Скрипт устарел, своевременно обновляйте до последней версии!",
  964. hideBarTips: "Скрыть панель разбиения на страницы, иммерсивный опыт",
  965. setConfigPage: "Установить текущую страницу в качестве страницы конфигурации по умолчанию",
  966. wedata2github: "Изменить адрес wedata на зеркальный адрес на складе github",
  967. addOtherProp: "Добавить свойство правила",
  968. addNextSelector: "Добавить содержимое селектора как nextLink",
  969. addPageSelector: "Добавить содержимое селектора как pageElement",
  970. propName: "Введите имя свойства правила",
  971. propValue: "Введите значение свойства правила",
  972. customFirst: "Игнорировать кеш для локальных пользовательских правил",
  973. rulesExample: "Подробное объяснение настраиваемых правил",
  974. lastPage: "Достигнута последняя страница",
  975. lastPageTips: "Показывать подсказки при достижении последней страницы"
  976. }
  977. }
  978. ];
  979. var langList = {};
  980. langData.forEach(lang => {
  981. langList[lang.match[0]] = lang.name;
  982. });
  983. var i18nData = langData[0].lang;
  984. function setLang(la) {
  985. for (let i = 0; i < langData.length; i++) {
  986. let lang = langData[i];
  987. if (lang && lang.match.indexOf(la) !== -1) {
  988. i18nData = lang.lang;
  989. break;
  990. }
  991. }
  992. }
  993. setLang(lang);
  994. var enableDebug = true;
  995. var _GM_xmlhttpRequest, _GM_registerMenuCommand, _GM_notification, _GM_addStyle, _GM_openInTab, _GM_info, _GM_setClipboard;
  996. function i18n(name, param) {
  997. return i18nData[name] ? i18nData[name].replace("#t#", param) : name;
  998. }
  999.  
  1000. function debug(str, title) {
  1001. if (enableDebug) {
  1002. console.log(
  1003. `%cPagetual v.${_GM_info.script.version}】 ${title ? title : 'debug'}:`,
  1004. 'color: yellow;font-size: large;font-weight: bold;background-color: darkblue;',
  1005. str
  1006. );
  1007. }
  1008. }
  1009.  
  1010. if (typeof GM_xmlhttpRequest !== 'undefined') {
  1011. _GM_xmlhttpRequest = GM_xmlhttpRequest;
  1012. } else if (typeof GM !== 'undefined' && typeof GM.xmlHttpRequest !== 'undefined') {
  1013. _GM_xmlhttpRequest = GM.xmlHttpRequest;
  1014. } else {
  1015. _GM_xmlhttpRequest = (f) => {fetch(f.url, {method: f.method || 'GET', body: f.data, headers: f.headers}).then(response => response.text()).then(data => {f.onload && f.onload({response: data})}).catch(f.onerror && f.onerror())};
  1016. }
  1017. if (typeof GM_registerMenuCommand !== 'undefined') {
  1018. _GM_registerMenuCommand = GM_registerMenuCommand;
  1019. } else if (typeof GM !== 'undefined' && typeof GM.registerMenuCommand !== 'undefined') {
  1020. _GM_registerMenuCommand = GM.registerMenuCommand;
  1021. } else {
  1022. _GM_registerMenuCommand = (s, f) => {debug(s); debug(f);};
  1023. }
  1024. if (typeof GM_info !== 'undefined') {
  1025. _GM_info = GM_info;
  1026. } else if (typeof GM !== 'undefined' && typeof GM.info !== 'undefined') {
  1027. _GM_info = GM.info;
  1028. } else {
  1029. _GM_info = {script: {}};
  1030. }
  1031. if (typeof GM_notification !== 'undefined') {
  1032. _GM_notification = GM_notification;
  1033. } else if (typeof GM !== 'undefined' && typeof GM.notification !== 'undefined') {
  1034. _GM_notification = GM.notification;
  1035. } else {
  1036. _GM_notification = (s) => {showTips(String(s.text || s));};
  1037. }
  1038. if (typeof GM_openInTab !== 'undefined') {
  1039. _GM_openInTab = GM_openInTab;
  1040. } else if (typeof GM !== 'undefined' && typeof GM.openInTab !== 'undefined') {
  1041. _GM_openInTab = GM.openInTab;
  1042. } else {
  1043. _GM_openInTab = (s,t) => {window.open(s); debug(t);};
  1044. }
  1045. if (typeof GM_addStyle !== 'undefined') {
  1046. _GM_addStyle = GM_addStyle;
  1047. } else if (typeof GM !== 'undefined' && typeof GM.addStyle !== 'undefined') {
  1048. _GM_addStyle = GM.addStyle;
  1049. } else {
  1050. _GM_addStyle = cssStr => {
  1051. let styleEle = document.createElement("style");
  1052. styleEle.innerHTML = cssStr;
  1053. document.head.appendChild(styleEle);
  1054. return styleEle;
  1055. };
  1056. }
  1057. if (typeof GM_setClipboard !== 'undefined') {
  1058. _GM_setClipboard = GM_setClipboard;
  1059. } else if (typeof GM !== 'undefined' && typeof GM.setClipboard !== 'undefined') {
  1060. _GM_setClipboard = GM.setClipboard;
  1061. } else {
  1062. _GM_setClipboard = (s, i) => {debug(s); debug(i);};
  1063. }
  1064. const _unsafeWindow = (typeof unsafeWindow === 'undefined') ? window : unsafeWindow;//兼容 ios userscripts 的寫法
  1065. const storage = {
  1066. supportGM: typeof GM_getValue === 'function' && typeof GM_getValue('a', 'b') !== 'undefined',
  1067. supportGMPromise: typeof GM !== 'undefined' && typeof GM.getValue === 'function' && typeof GM.getValue('a', 'b') !== 'undefined' && typeof GM.getValue('a', 'b').then === 'function',
  1068. supportCrossSave: function() {
  1069. return this.supportGM || this.supportGMPromise;
  1070. },
  1071. mxAppStorage: (function() {
  1072. try {
  1073. return window.external.mxGetRuntime().storage;
  1074. } catch(e) {
  1075. }
  1076. })(),
  1077. operaUJSStorage: (function() {
  1078. try {
  1079. return window.opera.scriptStorage;
  1080. } catch(e) {
  1081. }
  1082. })(),
  1083. setItem: function(key, value) {
  1084. if (this.supportGMPromise) {
  1085. GM.setValue(key, value);
  1086. if (value === "" && typeof GM !== 'undefined' && typeof GM.deleteValue !== 'undefined') {
  1087. GM.deleteValue(key);
  1088. }
  1089. } else if (this.supportGM) {
  1090. GM_setValue(key, value);
  1091. if (value === "" && typeof GM_deleteValue !== 'undefined') {
  1092. GM_deleteValue(key);
  1093. }
  1094. } else if (this.operaUJSStorage) {
  1095. this.operaUJSStorage.setItem(key, value);
  1096. } else if (this.mxAppStorage) {
  1097. this.mxAppStorage.setConfig(key, value);
  1098. } else if (window.localStorage) {
  1099. window.localStorage.setItem(key, value);
  1100. }
  1101. },
  1102. getItem: function(key, cb) {
  1103. var value;
  1104. if (this.supportGMPromise) {
  1105. value = GM.getValue(key).then(v => {cb(v);});
  1106. return;
  1107. } else if (this.supportGM) {
  1108. value = GM_getValue(key);
  1109. } else if (this.operaUJSStorage) {
  1110. value = this.operaUJSStorage.getItem(key);
  1111. } else if (this.mxAppStorage) {
  1112. value = this.mxAppStorage.getConfig(key);
  1113. } else if (window.localStorage) {
  1114. value = window.localStorage.getItem(key);
  1115. }
  1116. cb(value);
  1117. }
  1118. };
  1119. async function getData(key) {
  1120. return new Promise((resolve) => {
  1121. storage.getItem(key, value => {
  1122. resolve(value);
  1123. });
  1124. });
  1125. }
  1126. async function getListData(list, key) {
  1127. return new Promise((resolve) => {
  1128. storage.getItem(list, listData => {
  1129. let value;
  1130. if (listData) {
  1131. for(var i = 0; i < listData.length; i++) {
  1132. let data = listData[i];
  1133. if (data.k === key) {
  1134. value = data.v;
  1135. break;
  1136. }
  1137. }
  1138. }
  1139. resolve(value);
  1140. });
  1141. });
  1142. }
  1143. function setListData(list, key, value, length) {
  1144. storage.getItem(list, listData => {
  1145. if (!listData) {
  1146. listData = [];
  1147. }
  1148. listData = listData.filter(data => data && data.k !== key);
  1149. if (value !== "") {
  1150. listData.unshift({k: key, v: value});
  1151. if (listData.length > (length || 100)) {
  1152. listData.pop();
  1153. }
  1154. }
  1155. storage.setItem(list, listData);
  1156. });
  1157. }
  1158. const isMobile = ('ontouchstart' in document.documentElement);
  1159. const configPage = [`https://pagetual.hoothin.com/${lang === 'zh-CN' ? 'cn/' : ''}rule.html`,
  1160. "https://github.com/hoothin/UserScripts/tree/master/Pagetual",
  1161. "https://hoothin.github.io/UserScripts/Pagetual/"];
  1162. const firstRunPage = "https://pagetual.hoothin.com/firstRun";
  1163. const guidePage = /^https?:\/\/.*pagetual.*rule\.html/i;
  1164. const ruleImportUrlReg = /greasyfork\.org\/.*scripts\/438684(\-[^\/]*)?(\/discussions|\/?$|\/feedback)|github\.com\/hoothin\/UserScripts\/(tree\/master\/Pagetual|issues)/i;
  1165. const allOfBody = "body>*";
  1166. const mainSel = ["article,.article","[role=main],main,.main,#main","#results"];
  1167. const nextTextReg1 = new RegExp("\u005e\u7ffb\u003f\u005b\u4e0b\u540e\u5f8c\u6b21\u005d\u005b\u4e00\u30fc\u0031\u005d\u003f\u005b\u9875\u9801\u5f20\u5f35\u005d\u007c\u005e\u006e\u0065\u0078\u0074\u005b\u005c\u0073\u005f\u002d\u005d\u003f\u0070\u0061\u0067\u0065\u005c\u0073\u002a\u005b\u203a\u003e\u2192\u00bb\u005d\u003f\u0024\u007c\u6b21\u306e\u30da\u30fc\u30b8\u007c\u005e\u6b21\u3078\u003f\u0024\u007c\u0412\u043f\u0435\u0440\u0435\u0434", "i");
  1168. const nextTextReg2 = new RegExp("\u005e\u0028\u005b\u4e0b\u540e\u5f8c\u6b21\u005d\u005b\u4e00\u30fc\u0031\u005d\u003f\u005b\u7ae0\u8bdd\u8a71\u8282\u7bc0\u5e45\u005d\u007c\u006e\u0065\u0078\u0074\u002e\u003f\u0063\u0068\u0061\u0070\u0074\u0065\u0072\u007c\u00bb\u007c\u003e\u003e\u0029\u0028\u005b\u003a\uff1a\u005c\u002d\u005f\u2014\u005c\u0073\u005c\u002e\u3002\u003e\u0023\u00b7\u005c\u005b\u3010\u3001\uff08\u005c\u0028\u002f\u002c\uff0c\uff1b\u003b\u2192\u005d\u007c\u0024\u0029", "i");
  1169. const lazyImgAttr = ["data-lazy-src", "data-lazy", "data-isrc", "data-url", "data-orig-file", "zoomfile", "file", "original", "load-src", "imgsrc", "real_src", "src2", "origin-src", "data-lazyload", "data-lazyload-src", "data-lazy-load-src", "data-ks-lazyload", "data-ks-lazyload-custom", "data-src", "data-defer-src", "data-actualsrc", "data-cover", "data-original", "data-thumb", "data-imageurl", "data-placeholder", "lazysrc"];
  1170. var rulesData = {uninited: true, firstRun: true, sideController: !isMobile}, ruleUrls, updateDate, clickedSth = false, loadNowNum = 5, autoScrollRate = 50;
  1171. var isPause = false, manualPause = false, isHideBar = false, isLoading = false, curPage = 1, forceState = 0, autoScroll = 0, autoScrollInterval, bottomGap = 1000, autoLoadNum = -1, nextIndex = 0, stopScroll = false, clickMode = false, openInNewTab = 0, charset = "UTF-8", charsetValid = true, urlWillChange = false;
  1172. var tryTimes = 0, showedLastPageTips = false, rate = 1, author = '';
  1173.  
  1174. function getBody(doc) {
  1175. return doc.body || doc.querySelector('body') || doc;
  1176. }
  1177.  
  1178. function getElementByXpath(xpath, doc, contextNode) {
  1179. if (doc && doc.ownerDocument) doc = doc.ownerDocument;
  1180. doc = (doc && doc.evaluate) ? doc : document;
  1181. contextNode = contextNode || doc;
  1182. try {
  1183. let result = doc.evaluate(xpath, contextNode, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  1184. return result.singleNodeValue && result.singleNodeValue.nodeType === 1 && result.singleNodeValue;
  1185. } catch (err) {
  1186. debug(`Invalid xpath: ${xpath}`);
  1187. }
  1188. return null;
  1189. }
  1190.  
  1191. function getAllElementsByXpath(xpath, contextNode, doc) {
  1192. if (doc && doc.ownerDocument) doc = doc.ownerDocument;
  1193. doc = (doc && doc.evaluate) ? doc : document;
  1194. contextNode = contextNode || doc;
  1195. var result = [];
  1196. try {
  1197. var query = doc.evaluate(xpath, contextNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  1198. for (var i = 0; i < query.snapshotLength; i++) {
  1199. var node = query.snapshotItem(i);
  1200. if (node.nodeType === 1) {
  1201. result.push(node);
  1202. }
  1203. }
  1204. } catch (err) {
  1205. debug(`Invalid xpath: ${xpath}`);
  1206. }
  1207. return result;
  1208. }
  1209.  
  1210. function isXPath(xpath) {
  1211. if (!xpath) {
  1212. return false;
  1213. }
  1214. return /^\(*(descendant::|\.\/|\/|id\()/.test(xpath);
  1215. }
  1216.  
  1217. function getAllElements(sel, doc, contextNode) {
  1218. try {
  1219. if (!isXPath(sel)) {
  1220. return doc.querySelectorAll(sel);
  1221. }
  1222. } catch(e) {
  1223. debug(e, 'Error selector');
  1224. }
  1225. return getAllElementsByXpath(sel, contextNode, doc);
  1226. }
  1227.  
  1228. function getElement(sel, doc, contextNode, bySort) {
  1229. try {
  1230. if (!isXPath(sel)) {
  1231. if (!bySort) {
  1232. return doc.querySelector(sel);
  1233. } else {
  1234. let selArr = sel.split(",");
  1235. try {
  1236. for (let i = 0; i < selArr.length; i++) {
  1237. let ele = doc.querySelector(selArr[i].trim());
  1238. if (ele) {
  1239. return ele;
  1240. }
  1241. }
  1242. } catch(e) {
  1243. return doc.querySelector(sel);
  1244. }
  1245. return null;
  1246. }
  1247. }
  1248. } catch(e) {
  1249. debug(e, 'Error selector');
  1250. }
  1251. return getElementByXpath(sel, doc, contextNode);
  1252. }
  1253.  
  1254. function compareNodeName(node, names) {
  1255. if (!node || !node.nodeName || !node.nodeName.toLowerCase) {
  1256. return false;
  1257. }
  1258. let nodeName = node.nodeName.toLowerCase();
  1259. for (let i = 0; i < names.length; i++) {
  1260. if (names[i] === nodeName) {
  1261. return true;
  1262. }
  1263. }
  1264. return false;
  1265. }
  1266.  
  1267. function geneSelector(ele, addID, exact) {
  1268. let selector = ele.nodeName.toLowerCase();
  1269. //Google id class都是隨機。百度更過分,style script順序都是隨機的
  1270. if (selector !== "html" && selector !== "body") {
  1271. let hasId = false;
  1272. if (addID && ele.id && /^[a-z_][\w\-_]*$/i.test(ele.id)) {
  1273. if (ele.ownerDocument && ele.ownerDocument.querySelectorAll("#" + ele.id).length === 1) {
  1274. hasId = true;
  1275. selector = '#' + ele.id;
  1276. }
  1277. }
  1278. if (!hasId) {
  1279. let className = "";
  1280. if (ele.className) {
  1281. let classList = ele.classList;
  1282. for (let i = 0; i < classList.length; i++) {
  1283. let c = classList[i];
  1284. if (c !== 'scrolling' && /^[a-z_][\w\-_]*$/.test(c) && !/\d{4,}/.test(c)) {
  1285. className += '.' + c;
  1286. }
  1287. }
  1288. selector += className;
  1289. }
  1290. let parent = ele.parentElement;
  1291. if (parent) {
  1292. if (exact) {
  1293. let i, nth = 0, all = 0;
  1294. for (i = 0; i < parent.children.length; i++) {
  1295. if (parent.children[i].nodeName === ele.nodeName) {
  1296. all++;
  1297. if (parent.children[i] === ele) {
  1298. nth = all;
  1299. }
  1300. if (nth > 0 && all > 1) {
  1301. break;
  1302. }
  1303. }
  1304. }
  1305. selector += (all === 1 ? "" : `:nth-of-type(${nth})`);
  1306. } else if (!className && !hasId && parent.children.length > 1 && !compareNodeName(parent, ["html"])) {
  1307. let prevE = ele.previousElementSibling;
  1308. if (prevE && prevE.className) {
  1309. let classList = prevE.classList;
  1310. for (let i = 0; i < classList.length; i++) {
  1311. let c = classList[i];
  1312. if (c !== 'scrolling' && /^[a-z_][\w\-_]*$/.test(c) && !/\d{4,}/.test(c)) {
  1313. className += '.' + c;
  1314. }
  1315. }
  1316. if (className) {
  1317. selector = prevE.nodeName.toLowerCase() + className + "+" + selector;
  1318. }
  1319. }
  1320. if (!className) {
  1321. let i, nth = 0, all = 0;
  1322. for (i = 0; i < parent.children.length; i++) {
  1323. if (parent.children[i].nodeName === ele.nodeName) {
  1324. all++;
  1325. if (parent.children[i] === ele) {
  1326. nth = all;
  1327. }
  1328. if (nth > 0 && all > 1) {
  1329. break;
  1330. }
  1331. }
  1332. }
  1333. selector += (all === 1 ? "" : `:nth-of-type(${nth})`);
  1334. }
  1335. }
  1336. selector = geneSelector(parent, addID, exact) + ' > ' + selector;
  1337. }
  1338. }
  1339. }
  1340. return selector;
  1341. }
  1342.  
  1343. function createXPathFromElement(elm) {
  1344. let allNodes = document.getElementsByTagName('*'), segs;
  1345. for (segs = []; elm && elm.nodeType === 1; elm = elm.parentNode) {
  1346. if (compareNodeName(elm, ["body", "html"])) {
  1347. segs.unshift(elm.localName.toLowerCase());
  1348. continue;
  1349. }
  1350. if (elm.hasAttribute && elm.hasAttribute('id')) {
  1351. var uniqueIdCount = 0;
  1352. for (var n = 0; n < allNodes.length; n++) {
  1353. if (allNodes[n].hasAttribute('id') && allNodes[n].id === elm.id) {
  1354. uniqueIdCount++;
  1355. }
  1356. if (uniqueIdCount > 1) {
  1357. break;
  1358. }
  1359. }
  1360. if ( uniqueIdCount === 1) {
  1361. segs.unshift('id("' + elm.getAttribute('id') + '")');
  1362. return segs.join('/');
  1363. } else {
  1364. segs.unshift(elm.localName.toLowerCase() + '[@id="' + elm.getAttribute('id') + '"]');
  1365. }
  1366. } else if (elm.hasAttribute && elm.hasAttribute('class')) {
  1367. segs.unshift(elm.localName.toLowerCase() + '[@class="' + elm.getAttribute('class') + '"]');
  1368. } else {
  1369. let i, sib;
  1370. for (i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling) {
  1371. if (sib.localName === elm.localName) {
  1372. i++;
  1373. }
  1374. }
  1375. segs.unshift(elm.localName.toLowerCase() + '[' + i + ']');
  1376. }
  1377. }
  1378. return segs.length ? '/' + segs.join('/') : null;
  1379. }
  1380.  
  1381. const escapeHTMLPolicy = (_unsafeWindow.trustedTypes && _unsafeWindow.trustedTypes.createPolicy) ? _unsafeWindow.trustedTypes.createPolicy('pagetual_default', {
  1382. createHTML: (string, sink) => string
  1383. }) : null;
  1384.  
  1385. function createHTML(html) {
  1386. return escapeHTMLPolicy ? escapeHTMLPolicy.createHTML(html) : html;
  1387. }
  1388.  
  1389. const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
  1390.  
  1391. async function sleep(time) {
  1392. await new Promise((resolve) => {
  1393. setTimeout(() => {
  1394. resolve();
  1395. }, time);
  1396. });
  1397. }
  1398.  
  1399. class RuleParser {
  1400. constructor() {
  1401. this.hpRules = [];
  1402. this.smartRules = [];
  1403. this.customRules = [];
  1404. this.rules = [];
  1405. this.pageDoc = document;
  1406. this.nextLinkHref = null;
  1407. this.nextTitle = "";
  1408. this.oldUrl = "";
  1409. this.curUrl = location.href;
  1410. this.curSiteRule = {};
  1411. }
  1412.  
  1413. async initSavedRules(callback) {
  1414. var self = this;
  1415. let smartRules = await getData("smartRules");
  1416. if (smartRules) self.smartRules = smartRules;
  1417. let hpRules = await getData("hpRules");
  1418. if (hpRules) self.hpRules = hpRules;
  1419. let customRules = await getData("customRules");
  1420. if (customRules) self.customRules = customRules;
  1421. if (_unsafeWindow.pagetualRules && _unsafeWindow.pagetualRules.length) {
  1422. _unsafeWindow.pagetualRules.forEach(rule => {
  1423. rule.isScript = true;
  1424. });
  1425. self.customRules = _unsafeWindow.pagetualRules.concat(self.customRules);
  1426. }
  1427. let rules = await getData("rules");
  1428. if (rules) self.rules = rules;
  1429. callback();
  1430. }
  1431.  
  1432. saveCurSiteRule() {
  1433. /*if(!this.curSiteRule || !this.curSiteRule.url || this.curSiteRule.smart || this.curSiteRule.url.length<13)return;
  1434. this.hpRules=this.hpRules.filter(item=>{return item&&item.url!=this.curSiteRule.url});
  1435. this.hpRules.unshift(this.curSiteRule);
  1436. if(this.hpRules.length>30){
  1437. this.hpRules.pop();
  1438. }
  1439. storage.setItem("hpRules", this.hpRules);*/
  1440. }
  1441.  
  1442. requestJSON(url, callback) {
  1443. _GM_xmlhttpRequest({
  1444. url: url,
  1445. method: 'GET',
  1446. timeout: 1000000,
  1447. headers: {
  1448. 'accept': 'application/json,text/html',
  1449. 'Referer': url,
  1450. },
  1451. onload: function(res) {
  1452. let json = null;
  1453. try {
  1454. json = JSON.parse(res.response || res.responseText);
  1455. } catch(e) {
  1456. debug(e, 'Error json');
  1457. }
  1458. callback(json);
  1459. },
  1460. onerror: function(e) {
  1461. callback(null, e);
  1462. },
  1463. ontimeout: function(e) {
  1464. callback(null, e);
  1465. }
  1466. });
  1467. }
  1468.  
  1469. formatRule(item, from) {
  1470. if (item.data && item.data.url) {
  1471. let result = {
  1472. name: item.name,
  1473. from: from,
  1474. action: item.data.forceIframe === "true" ? 1 : undefined,
  1475. url: item.data.url,
  1476. pageElement: item.data.pageElement,
  1477. nextLink: item.data.nextLink,
  1478. insert: item.data.insertBefore||undefined,
  1479. updatedAt: item.updated_at
  1480. };
  1481. let _css = (item.data.Stylus || '') + (item.data.CSS || '');
  1482. if (_css) result.css = _css;
  1483. if (item.data.bookmarklet) result.pageAction = item.data.bookmarklet;
  1484. return result;
  1485. } else {
  1486. item.from = from;
  1487. return item;
  1488. }
  1489. return null;
  1490. }
  1491.  
  1492. addRuleByUrl(url, from, callback) {
  1493. if (url.indexOf("?") === -1) {
  1494. url = url + "?" + Date.now();
  1495. } else {
  1496. url = url + "&" + Date.now();
  1497. }
  1498. this.requestJSON(url, (json,err) => {
  1499. if (!json) {
  1500. debug(err, "Failed to update " + url + " rules!");
  1501. }
  1502. this.addRules(json, from);
  1503. callback(json, err);
  1504. });
  1505. }
  1506.  
  1507. addRules(rules, from) {
  1508. if (rules && rules.length > 0) {
  1509. let first = -1;
  1510. this.rules = this.rules.filter((item, i) => {
  1511. if (item.from === from) {
  1512. if (first === -1) first = i;
  1513. return false;
  1514. } else return true;
  1515. });
  1516. if (first === -1) first = 0;
  1517. rules.forEach(item => {
  1518. let rule = this.formatRule(item, from);
  1519. if (rule) {
  1520. this.rules.splice(first, 0, rule)
  1521. }
  1522. });
  1523. }
  1524. }
  1525.  
  1526. ruleMatchPre(r) {
  1527. if (r.include) {
  1528. let include;
  1529. if (Array && Array.isArray && Array.isArray(r.include)) {
  1530. include = r.include.every((sel, i) => {
  1531. let ele = getElement(sel, document);
  1532. return !!ele;
  1533. });
  1534. } else include = getElement(r.include, document);
  1535. if (!include) return false;
  1536. }
  1537. if (r.exclude) {
  1538. let exclude;
  1539. if (Array && Array.isArray && Array.isArray(r.exclude)) {
  1540. exclude = !r.exclude.every((sel, i) => {
  1541. let ele = getElement(sel, document);
  1542. return !ele;
  1543. });
  1544. } else exclude = getElement(r.exclude, document);
  1545. if (exclude) return false;
  1546. }
  1547. return true;
  1548. }
  1549.  
  1550. ruleMatchReady(r) {
  1551. let findIndex = 0;
  1552. if (r.nextLink && r.nextLink !== 0) {
  1553. let nextLinkSel = r.nextLink, nextLink;
  1554. if (Array && Array.isArray && Array.isArray(nextLinkSel)) {
  1555. nextLink = !nextLinkSel.every((sel, i) => {
  1556. let ele = getElement(sel, document);
  1557. if (ele) findIndex = i;
  1558. return !ele;
  1559. });
  1560. } else nextLink = getElement(nextLinkSel, document);
  1561. if (!nextLink) return false;
  1562. }
  1563. if (r.pageElement) {
  1564. let pageElementSel = r.pageElement, pageElement;
  1565. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  1566. pageElementSel = pageElementSel[findIndex];
  1567. }
  1568. pageElement = getElement(pageElementSel, document);
  1569. if (!pageElement) return false;
  1570. }
  1571. if (r.insert) {
  1572. let insertSel = r.insert, insert;
  1573. if (Array && Array.isArray && Array.isArray(insertSel)) {
  1574. insertSel = insertSel[findIndex];
  1575. }
  1576. insert = getElement(insertSel, document);
  1577. if (!insert) return false;
  1578. }
  1579. //if (findIndex !== 0) nextIndex = findIndex;
  1580. return true;
  1581. }
  1582.  
  1583. ruleMatch(r) {
  1584. return this.ruleMatchPre(r) && this.ruleMatchReady(r);
  1585. }
  1586.  
  1587. scrollToShow(sel, doc) {
  1588. let exclude = getElement(sel, doc);
  1589. if (exclude) {
  1590. var actualTop = exclude.offsetTop;
  1591. var current = exclude.offsetParent;
  1592. while (current !== null) {
  1593. actualTop += current.offsetTop;
  1594. current = current.offsetParent;
  1595. }
  1596. getBody(doc).scrollTop = 0;
  1597. doc.documentElement.scrollTop = 0;
  1598. let maxHeight = Math.max(getBody(doc).scrollHeight, doc.documentElement.scrollHeight);
  1599. getBody(doc).scrollTop = actualTop - 10;
  1600. doc.documentElement.scrollTop = actualTop - 10;
  1601. setTimeout(() => {
  1602. while (actualTop < maxHeight) {
  1603. actualTop += 200;
  1604. getBody(doc).scrollTop = actualTop;
  1605. doc.documentElement.scrollTop = actualTop;
  1606. }
  1607. }, 0);
  1608. return false;
  1609. }
  1610. return true;
  1611. }
  1612.  
  1613. waitElement(doc, selArr) {
  1614. if (!selArr) selArr = this.curSiteRule.waitElement;
  1615. if (!Array.isArray(selArr)) {
  1616. selArr = [selArr];
  1617. }
  1618. let includeSel = selArr[0].trim(), excludeSel;
  1619. if (selArr.length === 2) {
  1620. excludeSel = selArr[1].trim().replace(/^!/, '');
  1621. } else if (includeSel.indexOf('!') === 0) {
  1622. excludeSel = includeSel.replace(/^!/, '');
  1623. includeSel = '';
  1624. }
  1625. if (includeSel) {
  1626. let include = getElement(includeSel, doc);
  1627. if (!include) {
  1628. if (doc !== document) {
  1629. getBody(doc).scrollTop = 9999999;
  1630. doc.documentElement.scrollTop = 9999999;
  1631. }
  1632. return false;
  1633. }
  1634. }
  1635. if (doc === document) return true;
  1636. if (excludeSel) {
  1637. if (!this.scrollToShow(excludeSel, doc)) {
  1638. if (!loadingDiv.offsetParent && this.insert.parentNode) {
  1639. this.insertElement(loadingDiv);
  1640. }
  1641. return false;
  1642. }
  1643. }
  1644. return true;
  1645. }
  1646.  
  1647. runPageBar(pageBar) {
  1648. if (this.curSiteRule.pageBar && this.curSiteRule.pageBar !== 0) {
  1649. try {
  1650. ((typeof this.curSiteRule.pageBar === 'function') ? this.curSiteRule.pageBar : Function("pageBar",'"use strict";' + this.curSiteRule.pageBar))(pageBar);
  1651. } catch(e) {
  1652. debug(e);
  1653. }
  1654. }
  1655. }
  1656.  
  1657. runWait(cb) {
  1658. let checkEval = null, waitTime = 0;
  1659. if (this.curSiteRule.waitElement) {
  1660. checkEval = async doc => {
  1661. return await this.waitElement(doc);
  1662. };
  1663. } else if(this.curSiteRule.wait) {
  1664. if (isNaN(this.curSiteRule.wait)) {
  1665. try {
  1666. checkEval = (typeof this.curSiteRule.wait === 'function') ? this.curSiteRule.wait : new AsyncFunction("doc", '"use strict";' + this.curSiteRule.wait);
  1667. } catch(e) {
  1668. debug(e);
  1669. }
  1670. } else {
  1671. waitTime = this.curSiteRule.wait;
  1672. }
  1673. }
  1674. cb(checkEval, waitTime);
  1675. }
  1676.  
  1677. findNoNext() {
  1678. if (!this.curSiteRule || !this.curSiteRule.smart || this.curSiteRule.nextLink === 0 || this.possibleRule) return;
  1679. let self = this;
  1680. self.curSiteRule.nextLink = 0;
  1681. self.smartRules = self.smartRules.filter(item => {return item && item.url !== self.curSiteRule.url;});
  1682. self.smartRules.unshift(self.curSiteRule);
  1683. storage.setItem("smartRules", self.smartRules);
  1684. }
  1685.  
  1686. async getRule(callback) {
  1687. var href = location.href.slice(0, 500);
  1688. if(noRuleTest) {
  1689. this.curSiteRule = {};
  1690. this.curSiteRule.url = href;
  1691. this.curSiteRule.smart = true;
  1692. callback();
  1693. return;
  1694. }
  1695. if (_unsafeWindow.pagetualRule) {
  1696. this.curSiteRule = _unsafeWindow.pagetualRule;
  1697. if (!this.curSiteRule.url) this.curSiteRule.url = ".";
  1698. this.curSiteRule.isScript = true;
  1699. }
  1700. if (this.curSiteRule && this.curSiteRule.url && !this.curSiteRule.smart) {
  1701. let urlReg = new RegExp(this.curSiteRule.url, "i");
  1702. if (urlReg.test(href) && this.ruleMatch(this.curSiteRule)) {
  1703. return callback();
  1704. }
  1705. }
  1706. if (this.possibleRule) {
  1707. let urlReg = new RegExp(this.possibleRule.url, "i");
  1708. if (urlReg.test(href) && this.ruleMatch(this.possibleRule)) {
  1709. this.curSiteRule = this.possibleRule;
  1710. debug(this.curSiteRule, 'Match');
  1711. return callback();
  1712. }
  1713. }
  1714. this.curSiteRule = {};
  1715. var self = this;
  1716.  
  1717. function setRule(r) {
  1718. if (self.preSiteRule) {
  1719. href = location.href.slice(0, 500);
  1720. let urlReg = new RegExp(self.preSiteRule.url, "i");
  1721. if (urlReg.test(href) && self.ruleMatch(self.preSiteRule)) {
  1722. self.curSiteRule = self.preSiteRule;
  1723. return callback();
  1724. }
  1725. }
  1726. if (r.from === 2) {
  1727. delete r.autoLoadNum;
  1728. delete r.history;
  1729. delete r.sideController;
  1730. if (r.pageBar === 0) delete r.pageBar;
  1731. }
  1732. if (!r.smart) {
  1733. self.insert = null;
  1734. self.curSiteRule = r;
  1735. self.preSiteRule = r;
  1736. if (r.enable !== 0) debug(r, 'Match');
  1737. } else if (!self.curSiteRule || !self.curSiteRule.smart) self.curSiteRule = r;
  1738. callback();
  1739. }
  1740.  
  1741. function checkRule(r) {
  1742. if (r.from === 1 && r.url.length <= 13) return false;
  1743. let urlReg = new RegExp(r.url, "i");
  1744. if (urlReg.test(href)) {
  1745. if (!self.ruleMatchPre(r)) return false;
  1746. if (r.url.length > 15 && r.from !== 1) {
  1747. self.possibleRule = r;
  1748. }
  1749. if (r.waitElement) {
  1750. let waitTime = 500;
  1751. let checkReady = () => {
  1752. setTimeout(() => {
  1753. if (!self.waitElement(document, r.waitElement) || !self.ruleMatchReady(r)) {
  1754. checkReady();
  1755. } else {
  1756. setRule(r);
  1757. }
  1758. }, parseInt(waitTime));
  1759. };
  1760. checkReady();
  1761. debug(r, 'Wait for');
  1762. return true;
  1763. } else if (r.wait) {
  1764. let waitTime = 500, checkEval, maxCheckTimes = 50;
  1765. if (isNaN(r.wait)) {
  1766. try {
  1767. checkEval = (typeof r.wait === 'function') ? r.wait : AsyncFunction("doc",'"use strict";' + r.wait);
  1768. } catch(e) {
  1769. debug(e, 'Error when checkeval');
  1770. }
  1771. } else {
  1772. waitTime = r.wait;
  1773. }
  1774. let checkReady = () => {
  1775. if (maxCheckTimes-- <= 0) {
  1776. debug("Wait for rule ready but failed");
  1777. setRule(r);
  1778. return;
  1779. }
  1780. setTimeout(async() => {
  1781. if (!self.ruleMatchReady(r) || (checkEval && !await checkEval(document))) {
  1782. checkReady();
  1783. } else {
  1784. setRule(r);
  1785. }
  1786. }, parseInt(waitTime));
  1787. };
  1788. checkReady();
  1789. debug(r, 'Wait for');
  1790. return true;
  1791. }
  1792. if (r.pinUrl) {
  1793. setRule(r);
  1794. return true;
  1795. }
  1796. if (!self.ruleMatchReady(r)) {
  1797. return false;
  1798. }
  1799. setRule(r);
  1800. return true;
  1801. }
  1802. return false;
  1803. }
  1804.  
  1805. function checkHpRules() {
  1806. for (let i in self.hpRules) {
  1807. let rule = self.hpRules[i];
  1808. if (!rule || !rule.url || rule.smart) continue;
  1809. if (checkRule(rule)) return true;
  1810. }
  1811. return false;
  1812. }
  1813.  
  1814. function checkCustomRules() {
  1815. for (let i in self.customRules) {
  1816. let rule = self.customRules[i];
  1817. if (!rule || !rule.url) continue;
  1818. if (checkRule(rule)) return true;
  1819. }
  1820. return false;
  1821. }
  1822.  
  1823. if (rulesData.customFirst) {
  1824. if (checkCustomRules()) return;
  1825. await sleep(1);
  1826. if (checkHpRules()) return;
  1827. } else {
  1828. if (checkHpRules()) return;
  1829. await sleep(1);
  1830. if (checkCustomRules()) return;
  1831. }
  1832. await sleep(1);
  1833.  
  1834. for (let i in this.smartRules) {
  1835. let rule = this.smartRules[i];
  1836. if (!rule || !rule.url || !rule.smart) continue;
  1837. if (href == rule.url) {
  1838. setRule(rule);
  1839. return;
  1840. }
  1841. }
  1842. let r = 0;
  1843. async function searchByTime() {
  1844. while (document.hidden) {
  1845. await sleep(1000);
  1846. }
  1847. setTimeout(() => {
  1848. let end = r + 20;
  1849. end = end > self.rules.length ? self.rules.length : end;
  1850. for (; r < end; r++) {
  1851. let rule = self.rules[r];
  1852. if (checkRule(rule)) return;
  1853. }
  1854. if (end >= self.rules.length) {
  1855. setRule({url: href, smart: true});
  1856. return;
  1857. } else {
  1858. searchByTime();
  1859. }
  1860. }, 1);
  1861. }
  1862. searchByTime();
  1863. }
  1864.  
  1865. addToHpRules(instead) {
  1866. try {
  1867. if (this.curSiteRule.isScript) return;
  1868. if (!this.hpRules) this.hpRules = [];
  1869. let url = this.curSiteRule && this.curSiteRule.url, self = this;
  1870. let href = location.href.slice(0, 500);
  1871. let matchedRules = this.hpRules.filter(rule => rule != self.curSiteRule && new RegExp(rule.url, "i").test(href) && self.ruleMatch(rule));
  1872. if (url) matchedRules.unshift(this.curSiteRule);
  1873. matchedRules.sort((a, b) => {
  1874. if ((a.include || a.exclude) && (!b.include && !b.exclude)) {
  1875. return -1;
  1876. } else if ((b.include || b.exclude) && (!a.include && !a.exclude)) {
  1877. return 1;
  1878. } else {
  1879. if ((a.nextLink || a.pageElement) && (!b.nextLink && !b.pageElement)) {
  1880. return -1;
  1881. } else if ((b.nextLink || b.pageElement) && (!a.nextLink && !a.pageElement)) {
  1882. return 1;
  1883. } else {
  1884. if (a.url.length > b.url.length) {
  1885. return -1;
  1886. } else if (a.url.length < b.url.length) {
  1887. return 1;
  1888. } else {
  1889. return 0;
  1890. }
  1891. }
  1892. }
  1893. });
  1894. this.hpRules = this.hpRules.filter(item => {
  1895. return item && !matchedRules.find(rule => item.url == rule.url && JSON.stringify(item) == JSON.stringify(rule));
  1896. });
  1897. if (instead) {
  1898. if (url) {
  1899. this.hpRules.unshift(this.curSiteRule);
  1900. matchedRules = [];
  1901. }
  1902. } else {
  1903. this.hpRules = matchedRules.concat(this.hpRules);
  1904. }
  1905. if (matchedRules && matchedRules.length) this.curSiteRule = matchedRules[0];
  1906. if (this.hpRules.length > 30) {
  1907. this.hpRules.pop();
  1908. }
  1909. if (!rulesData.sort) rulesData.sort = [1];
  1910. this.hpRules.sort((a, b) => {
  1911. let aSort = -1, bSort = -1;
  1912. for (let s = 0; s < rulesData.sort.length; s++) {
  1913. if (a.from == rulesData.sort[s]) aSort = s;
  1914. if (b.from == rulesData.sort[s]) bSort = s;
  1915. if (aSort > -1 && bSort > -1) break;
  1916. }
  1917. return aSort - bSort;
  1918. });
  1919. storage.setItem("hpRules", this.hpRules);
  1920. } catch (e) {
  1921. debug(e);
  1922. }
  1923. }
  1924.  
  1925. replaceElement(doc) {
  1926. if (!doc || doc === document) return;
  1927. let replaceElementSel = this.curSiteRule.replaceElement;
  1928. if (replaceElementSel) {
  1929. if (!Array.isArray(replaceElementSel)) {
  1930. replaceElementSel = [replaceElementSel];
  1931. }
  1932. replaceElementSel.forEach(sel => {
  1933. let pageEles = getAllElements(sel, document);
  1934. let replaceEles = getAllElements(sel, doc);
  1935. for (let i = 0; i < pageEles.length; i++) {
  1936. let replaceEle = replaceEles[i];
  1937. let pageEle = pageEles[i];
  1938. if (replaceEle) {
  1939. pageEle.parentNode.replaceChild(replaceEle.cloneNode(true), pageEle);
  1940. } else break;
  1941. }
  1942. });
  1943. }
  1944. }
  1945.  
  1946. refreshByClick() {
  1947. let refreshByClickSel = this.curSiteRule.refreshByClick;
  1948. if (refreshByClickSel) {
  1949. let self = this;
  1950. if (!this.refreshByClickHandler) {
  1951. this.refreshByClickHandler = e => {
  1952. if (!self.refreshing) {
  1953. self.refreshing = true;
  1954. setTimeout(() => {
  1955. self.refreshing = false;
  1956. let checkEles = getAllElements(refreshByClickSel, document);
  1957. for (let i = 0; i < checkEles.length; i++) {
  1958. let curEle = checkEles[i];
  1959. if (curEle === e.target || curEle.contains(e.target)) {
  1960. ruleParser.urlChanged();
  1961. isPause = true;
  1962. if (!ruleParser.nextLinkHref) isLoading = false;
  1963. break;
  1964. }
  1965. }
  1966. }, 300);
  1967. }
  1968. }
  1969. }
  1970. document.removeEventListener("click", this.refreshByClickHandler);
  1971. document.addEventListener("click", this.refreshByClickHandler);
  1972. }
  1973. }
  1974.  
  1975. getValidSize(ele, win) {
  1976. if (!win) return {h: 0, w: 0};
  1977. let eleStyle = win.getComputedStyle(ele);
  1978. if (!ele.offsetParent && (eleStyle.position !== "fixed" || eleStyle.opacity === 0)) {
  1979. return {h: 0, w: 0};
  1980. }
  1981. if (ele.children && ele.children.length === 1 && (ele.offsetWidth === 0 || ele.offsetHeight === 0)) {
  1982. ele = ele.children[0];
  1983. }
  1984. let h = ele.scrollHeight, w;
  1985. if (eleStyle.overflow === "hidden") {
  1986. h = ele.offsetHeight;
  1987. w = ele.offsetWidth;
  1988. } else w = parseInt(ele.offsetWidth || ele.scrollWidth);
  1989. if (h === 0 && ele.parentNode && ele.parentNode.children.length === 1) {
  1990. h = ele.parentNode.scrollHeight;
  1991. }
  1992. while (h === 0 && ele.children && ele.children.length === 1) {
  1993. ele = ele.children[0];
  1994. h = ele.scrollHeight;
  1995. }
  1996. if (h === 0 && ele.children && ele.children.length) {
  1997. let maxChildSize = {h: 0}, self = this;
  1998. [].forEach.call(ele.children, el => {
  1999. let childSize = self.getValidSize(el, win);
  2000. if (childSize.h > maxChildSize.h) maxChildSize = childSize;
  2001. });
  2002. if (maxChildSize.h !== 0) return maxChildSize;
  2003. }
  2004. const maxNum = 2147483647;
  2005. let moreChild = ele.children[0], minOffsetTop = maxNum;
  2006. while (moreChild) {
  2007. if ((moreChild.offsetParent === ele || moreChild.offsetParent === ele.offsetParent)) {
  2008. let curOffsetTop = moreChild.offsetParent === ele.offsetParent ? moreChild.offsetTop - ele.offsetTop : moreChild.offsetTop;
  2009. if (curOffsetTop < minOffsetTop) {
  2010. minOffsetTop = curOffsetTop;
  2011. }
  2012. }
  2013. moreChild = moreChild.nextElementSibling;
  2014. }
  2015. if (h && minOffsetTop !== maxNum && minOffsetTop > 0) {
  2016. h -= minOffsetTop;
  2017. }
  2018. return {h: h, w: w};
  2019. }
  2020.  
  2021. checkTargetChildren(ele, curWin, articleNum, curHeight) {
  2022. let pf = false;
  2023. if (ele.parentNode) {
  2024. let paStyle = curWin.getComputedStyle(ele.parentNode);
  2025. let paDisplay = paStyle.display;
  2026. let paOverflow = paStyle.overflow;
  2027. pf = (paDisplay.indexOf('flex') !== -1 && paStyle.flexDirection.indexOf("row") === 0 && paStyle.flexWrap !== "wrap") || compareNodeName(ele.parentNode, ["ul"]) || paDisplay.indexOf('grid') !== -1 || paOverflow === "hidden";
  2028. }
  2029. let curStyle = curWin.getComputedStyle(ele);
  2030. if (ele.children.length > 1) {
  2031. if (articleNum > 1) {
  2032. return ">article";
  2033. } else {
  2034. let hasText = false;
  2035. for (let i in ele.childNodes) {
  2036. let child = ele.childNodes[i];
  2037. if (child.nodeType === 3 && child.nodeValue.trim() !== '') {
  2038. hasText = true;
  2039. break;
  2040. }
  2041. }
  2042. let gridArea = curStyle.gridArea;
  2043. if (gridArea && gridArea !== "auto" && gridArea !== "auto / auto / auto / auto") {
  2044. return ">*";
  2045. } else {
  2046. let middleChild = ele.children[parseInt(ele.children.length / 2)];
  2047. if ((curStyle.display === 'flex' && curStyle.flexDirection.indexOf("row") === 0 && curStyle.flexWrap !== "wrap") || (curStyle.float === "none" && curStyle.display !== "table-cell" && (rulesData.opacity !== 0 || hasText) && !pf)) {
  2048. return "";
  2049. } else if ((middleChild.style && middleChild.style.position === "absolute" && middleChild.style.left && middleChild.style.top) || compareNodeName(ele, ["ul"]) || curHeight === 0) {
  2050. return "";
  2051. } else {
  2052. return ">*";
  2053. }
  2054. }
  2055. }
  2056. } else if (pf || curStyle.position === "absolute") {
  2057. return ">*";
  2058. }
  2059. return "";
  2060. }
  2061.  
  2062. getPageElement(doc, curWin, dontFind) {
  2063. if (doc === document && this.docElementValid()) {
  2064. return this.docPageElement;
  2065. }
  2066. let pageElement = null;
  2067. let self = this;
  2068. let body = getBody(doc);
  2069. if (this.curSiteRule.pageElement) {
  2070. let pageElementSel = this.curSiteRule.pageElement;
  2071. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  2072. pageElementSel = pageElementSel[nextIndex < pageElementSel.length ? nextIndex : 0];
  2073. }
  2074. pageElement = getAllElements(pageElementSel, doc);
  2075. if (this.curSiteRule.smart && (!pageElement || pageElement.length === 0)) {
  2076. const childSelMatch = />\s*\*$/;
  2077. const targetChild = childSelMatch.test(pageElementSel);
  2078. if (targetChild) pageElementSel = pageElementSel.replace(childSelMatch, "");
  2079. let pageElementSelSplit = pageElementSel.split(">");
  2080. while(pageElementSelSplit && pageElementSelSplit.length > 5) {
  2081. pageElementSelSplit.shift();
  2082. let tempSel = pageElementSelSplit.join(">");
  2083. pageElement = getAllElements(tempSel, doc);
  2084. if (pageElement && pageElement.length === 1) {
  2085. if (targetChild) {
  2086. pageElement = pageElement.children;
  2087. }
  2088. this.curSiteRule.pageElement = tempSel + (targetChild ? ">*" : "");
  2089. break;
  2090. }
  2091. }
  2092. if (!pageElement || pageElement.length === 0) {
  2093. pageElementSel = pageElementSel.replace(/:nth-of-type\(\d+\)/g, "");
  2094. pageElement = getAllElements(pageElementSel, doc);
  2095. if (pageElement && pageElement.length === 1) {
  2096. if (targetChild) {
  2097. pageElement = pageElement.children;
  2098. }
  2099. this.curSiteRule.pageElement = pageElementSel + (targetChild ? ">*" : "");
  2100. }
  2101. }
  2102. }
  2103. if (this.curSiteRule.smart && pageElement && pageElement.length && curWin && curWin !== _unsafeWindow) {
  2104. if (pageElement.length === 1 && !pageElement[0].src && pageElement[0].innerHTML.trim() === "") {
  2105. pageElement = null;
  2106. } else {
  2107. let parent = pageElement[0].parentNode;
  2108. let loading = parent.querySelector('[class*=loading]');
  2109. if (loading && loading.offsetParent && loading.offsetHeight > parent.offsetHeight>>2) {
  2110. pageElement = null;
  2111. }
  2112. }
  2113. }
  2114. }
  2115. if (pageElement && pageElement.length === 1 && pageElement[0].style.display === 'none') {
  2116. pageElement = [body];
  2117. }
  2118. if (this.curSiteRule.smart && pageElement && pageElement.length > 0 && compareNodeName(pageElement[0], ["tr"])) {
  2119. let mainTr = this.insert.parentNode.querySelectorAll('tr'), mainTdNum = 0, newTdNum = 0;
  2120. mainTr = mainTr[mainTr.length - 1];
  2121. [].forEach.call(mainTr.children, el => {
  2122. if (compareNodeName(el, ["td", "th"])) {
  2123. mainTdNum += el.colSpan || 1;
  2124. }
  2125. });
  2126. [].forEach.call(pageElement[0].children, el => {
  2127. if (compareNodeName(el, ["td", "th"])) {
  2128. newTdNum += el.colSpan || 1;
  2129. }
  2130. });
  2131. if (mainTdNum !== newTdNum) {
  2132. this.curSiteRule.pageElement = this.curSiteRule.pageElement.replace(/> *table.*/, ">table");
  2133. this.getInsert(true);
  2134. return this.getPageElement(doc, curWin, dontFind);
  2135. }
  2136. }
  2137. if ((this.curSiteRule.smart || !this.curSiteRule.pageElement) && (!pageElement || pageElement.length == 0) && curWin && !dontFind) {
  2138. if (!body) return null;
  2139. let bodyHeight = parseInt(body.offsetHeight || body.scrollHeight);
  2140. let curHeight = bodyHeight, curWidth = 0;
  2141. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  2142. let windowWidth = window.innerWidth || document.documentElement.clientWidth;
  2143. let needCheckNext = (doc == document && this.initNext), nextLeftPos = 0;
  2144. if (needCheckNext && this.initNext.getBoundingClientRect) {
  2145. nextLeftPos = this.initNext.getBoundingClientRect().left;
  2146. }
  2147. function checkElement(ele) {
  2148. if (compareNodeName(ele, ["pre", "code"])) {
  2149. self.curSiteRule.pageElement = geneSelector(ele.parentNode);
  2150. debug(self.curSiteRule.pageElement, 'Page element');
  2151. return [ele.parentNode];
  2152. }
  2153. if (ele.children && ele.children.length === 1) {
  2154. let hasText = false;
  2155. for (let i in ele.childNodes) {
  2156. let child = ele.childNodes[i];
  2157. if (child.nodeType === 3 && child.nodeValue.trim() !== '') {
  2158. hasText = true;
  2159. break;
  2160. }
  2161. }
  2162. if (!hasText) {
  2163. ele = ele.children[0];
  2164. let validSize = self.getValidSize(ele, curWin);
  2165. curHeight = validSize.h;
  2166. curWidth = validSize.w;
  2167. }
  2168. }
  2169. if (compareNodeName(ele, ["picture"]) || !ele.innerText || ele.innerText.trim() === '') {
  2170. self.curSiteRule.pageElement = geneSelector(ele.parentNode) + ">" + ele.nodeName.toLowerCase();
  2171. debug(self.curSiteRule.pageElement, 'Page element');
  2172. let eles = [];
  2173. for (let i = 0; i < ele.parentNode.children.length; i++) {
  2174. let curNode = ele.parentNode.children[i];
  2175. if (curNode.nodeName === ele.nodeName && curNode.id === ele.id && curNode.className === ele.className) {
  2176. eles.push(curNode);
  2177. }
  2178. }
  2179. return eles;
  2180. }
  2181. if (compareNodeName(ele, ["form"]) && ele.parentNode !== getBody(document)) {
  2182. self.curSiteRule.pageElement = geneSelector(ele) + ">*";
  2183. debug(self.curSiteRule.pageElement, 'Page element');
  2184. return ele.children;
  2185. }
  2186. if (ele.children.length === 0 && !self.curSiteRule.pageElement) {
  2187. if (compareNodeName(ele.parentNode, ["p"])) ele = ele.parentNode;
  2188. self.curSiteRule.pageElement = geneSelector(ele.parentNode) + ">" + ele.nodeName.toLowerCase();
  2189. debug(self.curSiteRule.pageElement, 'Page element');
  2190. return getAllElements(self.curSiteRule.pageElement, doc);
  2191. }
  2192. let i, minHeight = curHeight * 0.52, curMaxEle = null, curMaxArea = 0, minWidth = Math.min(curWidth * 0.38, 500);
  2193. let isHori, preOffsetTop = -1;
  2194. let articleNum = 0;
  2195. for (i = 0; i < ele.children.length; i++) {
  2196. let curNode = ele.children[i];
  2197. if (ele !== body && /^H\d$/i.test(curNode.nodeName) && curNode.offsetParent) {
  2198. curMaxEle = null;
  2199. break;
  2200. }
  2201. if (compareNodeName(curNode, ["canvas", "nav"])) continue;
  2202. let curStyle = curWin.getComputedStyle(curNode);
  2203. if (!curNode.offsetParent && (curStyle.position !== "fixed" || curStyle.opacity === 0)) {
  2204. continue;
  2205. }
  2206. if (!compareNodeName(curNode, ["img"]) && curNode.querySelector('img') === null && /^\s*$/.test(curNode.innerText)) continue;
  2207. if (needCheckNext && !curNode.contains(self.initNext) && getElementTop(curNode) > windowHeight) {
  2208. continue;
  2209. }
  2210. if (compareNodeName(curNode, ["article"])) articleNum++;
  2211. let validSize = self.getValidSize(curNode, curWin);
  2212. let h = validSize.h;
  2213. let w = validSize.w;
  2214. if (isNaN(h) || isNaN(w) || !h || !w) continue;
  2215. isHori = Math.abs(preOffsetTop - curNode.offsetTop) <= 20 ? true : (preOffsetTop === -1 && curNode.nextElementSibling && curNode.nextElementSibling.offsetTop === curNode.offsetTop);
  2216. if (isHori && h <= 50) continue;
  2217. /*if (isHori && nextLeftPos && curMaxEle && curWidth > 500 && curHeight > 500) {
  2218. let curRect = curNode.getBoundingClientRect();
  2219. if (curRect.left > windowWidth>>2 && curRect.left <= nextLeftPos && curRect.right > nextLeftPos) {
  2220. continue;
  2221. }
  2222. }*/
  2223. let a = h * w, moreChild = curNode.children[0];
  2224. while (moreChild) {
  2225. let validSize = self.getValidSize(moreChild, curWin);
  2226. let ch = validSize.h;
  2227. let cw = validSize.w;
  2228. if (h < ch) {
  2229. h = ch;
  2230. }
  2231. if (moreChild.innerText !== "" && ch && cw) {
  2232. a += ch * cw;
  2233. }
  2234. moreChild = moreChild.nextElementSibling;
  2235. }
  2236. let isMax = false;
  2237. if (isHori) {
  2238. if (curMaxEle) {
  2239. if (w > curWidth && (windowWidth>>1) > curWidth) {
  2240. isMax = true;
  2241. } else if (w + 300 > curWidth && a > curMaxArea) {
  2242. isMax = true;
  2243. }
  2244. }
  2245. } else {
  2246. if (curMaxEle && curMaxEle.offsetParent === curNode.offsetParent && curMaxEle.offsetTop === curNode.offsetTop) {
  2247. if (curMaxArea * 2 > a) continue;
  2248. }
  2249. isMax = curMaxArea < a;
  2250. }
  2251. if (curMaxEle === null || isMax) {
  2252. if (isHori) {
  2253. if (w < minWidth) {
  2254. continue;
  2255. }
  2256. }
  2257. if (h < minHeight) {
  2258. if (!needCheckNext || h < (windowHeight>>1)) {
  2259. continue;
  2260. }
  2261. if (!ele.contains(self.initNext)) {
  2262. continue;
  2263. } else if (!curNode.contains(self.initNext) && h < curHeight >> 1) {
  2264. continue;
  2265. }
  2266. }
  2267. curHeight = h;
  2268. curMaxArea = a;
  2269. curWidth = w;
  2270. curMaxEle = curNode;
  2271. preOffsetTop = curNode.offsetTop;
  2272. }
  2273. }
  2274. let curHeightPercent = curHeight / bodyHeight;
  2275. if (curMaxEle && curHeightPercent <= 0.18) {
  2276. let article;
  2277. for (let i = 0; i < mainSel.length; i++) {
  2278. article = doc.querySelectorAll(mainSel[i]);
  2279. if (article && article.length === 1) break;
  2280. }
  2281. if (article && article.length === 1) {
  2282. article = article[0];
  2283. let childrenEnd = self.checkTargetChildren(article, curWin, articleNum, curHeight);
  2284. self.curSiteRule.pageElement = article.nodeName.toLowerCase() + (article.id ? "#" + article.id : "") + (article.className ? "." + article.className.replace(/ /g, ".") : "") + childrenEnd;
  2285. debug(self.curSiteRule.pageElement, 'Page element');
  2286. return childrenEnd ? article.children : [article];
  2287. }
  2288. curMaxEle = null;
  2289. }
  2290. if (curMaxEle && (!compareNodeName(curMaxEle, ["ul"]) || curHeightPercent > 0.8)) {
  2291. let sameClassNum = 0, hasDifferent = false;
  2292. if (curMaxEle.className) {
  2293. for(i = 0; i < ele.children.length; i++) {
  2294. let curNode = ele.children[i];
  2295. if (curMaxEle !== curNode && curNode.style.display !== 'none' && curMaxEle.className === curNode.className && curMaxEle.nodeName === curNode.nodeName){
  2296. sameClassNum++;
  2297. } else if (curMaxEle.className !== curNode.className) {
  2298. hasDifferent = true;
  2299. }
  2300. }
  2301. }
  2302. if (sameClassNum < 2 || (sameClassNum < 5 && hasDifferent)) {
  2303. return checkElement(curMaxEle);
  2304. }
  2305. }
  2306. if (ele.nodeName === "APP-ROOT") {
  2307. isPause = true;
  2308. debug(ele, "Angular root");
  2309. return null;
  2310. }
  2311. while (compareNodeName(ele, ["p", "br", "td"])) {
  2312. ele = ele.parentNode;
  2313. }
  2314. if (compareNodeName(ele, ["tbody"])) {
  2315. self.curSiteRule.pageElement = geneSelector(ele) + ">*";
  2316. if (ele.children.length > 0 && ele.children[0].querySelector("th")) {
  2317. self.curSiteRule.pageElement += ":not(:first-child)";
  2318. }
  2319. debug(self.curSiteRule.pageElement, 'Page element');
  2320. return ele.children;
  2321. }
  2322. let imgs = ele.querySelectorAll('img');
  2323. if (imgs.length === 1) {
  2324. let img = imgs[0];
  2325. if (img.offsetWidth > ele.offsetWidth / 3 * 2 && img.offsetHeight > ele.offsetHeight / 2) {
  2326. ele = img;
  2327. }
  2328. }
  2329. let childrenEnd = self.checkTargetChildren(ele, curWin, articleNum, curHeight);
  2330. if (childrenEnd) {
  2331. self.curSiteRule.pageElement = geneSelector(ele) + childrenEnd;
  2332. ele = ele.children;
  2333. } else {
  2334. if (ele.scrollHeight === 0 && ele.parentNode.children.length === 1) {
  2335. ele = ele.parentNode;
  2336. }
  2337. self.curSiteRule.pageElement = geneSelector(ele);
  2338. ele = [ele];
  2339. }
  2340. debug(self.curSiteRule.pageElement, 'Page element');
  2341. return ele;
  2342. }
  2343. pageElement = checkElement(body);
  2344. if (doc === document && pageElement && pageElement.length > 0 && self.initNext) {
  2345. let posEle = pageElement[pageElement.length - 1];
  2346. while (posEle && !posEle.offsetParent) {
  2347. posEle = posEle.previousElementSibling || posEle.parentNode;
  2348. }
  2349. if (posEle && posEle.scrollHeight === 0 && posEle.lastElementChild) posEle = posEle.lastElementChild;
  2350. let lastBottom = forceState !== 2 && forceState !== 3 && posEle && getElementBottom(posEle);
  2351. if (lastBottom && getElementTop(self.initNext) - lastBottom > 1000) {
  2352. debug("Stop as too long between next & page element, try to enable Force-Join mode.");
  2353. isPause = true;
  2354. pageElement = [];
  2355. sideController.remove();
  2356. } else {
  2357. if (pageElement.length === 1 && compareNodeName(pageElement[0], ["img"])) {
  2358. self.curSiteRule.pageBar = 0;
  2359. }
  2360. }
  2361. }
  2362. //if(pageElement)this.saveCurSiteRule();
  2363. }
  2364.  
  2365. if (doc !== document) {
  2366. this.setPageElementCss(pageElement);
  2367. this.lazyImgAction(pageElement, doc);
  2368. this.filterEles(doc, pageElement);
  2369. } else if (!this.docPageElement) {
  2370. this.setPageElementCss(pageElement, true);
  2371. this.docPageElement = pageElement;
  2372. this.filterEles(doc, pageElement);
  2373. if (this.nextLinkHref) {
  2374. this.openInNewTab(pageElement);
  2375. }
  2376. }
  2377. return pageElement;
  2378. }
  2379.  
  2380. showAddedElements() {
  2381. if (!this.addedElementsIsHide) return;
  2382. if (this.addedElePool && this.addedElePool.length) {
  2383. this.addedElePool.forEach(ele => {
  2384. ele.classList && ele.classList.remove("pagetual-hide");
  2385. });
  2386. }
  2387. this.addedElementsIsHide = false;
  2388. }
  2389.  
  2390. hideAddedElements() {
  2391. if (this.addedElePool && this.addedElePool.length) {
  2392. this.addedElePool.forEach(ele => {
  2393. ele.classList && ele.classList.add("pagetual-hide");
  2394. });
  2395. }
  2396. this.addedElementsIsHide = true;
  2397. }
  2398.  
  2399. toggleAddedElements() {
  2400. if (this.addedElementsIsHide) {
  2401. this.showAddedElements();
  2402. } else {
  2403. this.hideAddedElements();
  2404. }
  2405. }
  2406.  
  2407. changeVisibility() {
  2408. let contentVisibility = this.curSiteRule.contentVisibility || rulesData.contentVisibility;
  2409. if (!contentVisibility) return;
  2410. if (!this.changingVisibility) {
  2411. clearTimeout(this.changeVisibilityTimer);
  2412. this.changeVisibilityTimer = setTimeout(() => {
  2413. this.changingVisibility = true;
  2414. this.changeVisibility();
  2415. }, 300);
  2416. return;
  2417. }
  2418. this.changingVisibility = false;
  2419. if (!this.visibilityItems || !this.visibilityItems.length || this.visibleIndex < 0) return;
  2420. let tempIndex = this.visibleIndex, findVisible = false, lastVisible = 0;
  2421. let viewPortHeight = window.innerHeight || document.documentElement.clientHeight || getBody(document).clientHeight;
  2422. let checkItem = this.visibilityItems[tempIndex];
  2423. while(checkItem) {
  2424. if (checkItem.offsetParent) {
  2425. if (!checkItem.style.containIntrinsicSize) return;
  2426. let clientRect = checkItem.getBoundingClientRect();
  2427. let top = clientRect && clientRect.top;
  2428. let bottom = clientRect && clientRect.bottom;
  2429. if (bottom > 0 && top < viewPortHeight) {
  2430. if (!findVisible) {
  2431. findVisible = true;
  2432. lastVisible = tempIndex;
  2433. }
  2434. checkItem.style.contentVisibility = "visible";
  2435. } else {
  2436. if (top < viewPortHeight && checkItem.style.contentVisibility === "auto") {
  2437. break;
  2438. } else checkItem.style.contentVisibility = "auto";
  2439. }
  2440. }
  2441. if (tempIndex === 0) break;
  2442. tempIndex--;
  2443. checkItem = this.visibilityItems[tempIndex];
  2444. }
  2445. tempIndex = this.visibleIndex + 1;
  2446. if (findVisible) {
  2447. this.visibleIndex = lastVisible;
  2448. }
  2449. checkItem = this.visibilityItems[tempIndex];
  2450. while(checkItem) {
  2451. if (checkItem.offsetParent) {
  2452. if (!checkItem.style.containIntrinsicSize) return;
  2453. let clientRect = checkItem.getBoundingClientRect();
  2454. let top = clientRect && clientRect.top;
  2455. let bottom = clientRect && clientRect.bottom;
  2456. if (bottom > 0 && top < viewPortHeight) {
  2457. findVisible = true;
  2458. lastVisible = tempIndex;
  2459. checkItem.style.contentVisibility = "visible";
  2460. } else {
  2461. if (findVisible && checkItem.style.contentVisibility === "auto") {
  2462. break;
  2463. } else checkItem.style.contentVisibility = "auto";
  2464. }
  2465. }
  2466. if (tempIndex === this.visibilityItems.length - 1) break;
  2467. tempIndex++;
  2468. checkItem = this.visibilityItems[tempIndex];
  2469. }
  2470. if (findVisible) {
  2471. this.visibleIndex = lastVisible;
  2472. }
  2473. }
  2474.  
  2475. setPageElementCss(pageElement, init) {
  2476. let self = this;
  2477. if (pageElement && pageElement.length > 0) {
  2478. let pageElementCss = this.curSiteRule.pageElementCss || rulesData.pageElementCss;
  2479. if (!pageElementCss && init && !this.nextLinkHref) return;
  2480. let contentVisibility = this.curSiteRule.contentVisibility || rulesData.contentVisibility;
  2481. if (!contentVisibility && !pageElementCss) return;
  2482. [].forEach.call(pageElement, (ele, i) => {
  2483. if (!compareNodeName(ele, ["link", "meta", "style", "script"])) {
  2484. if (pageElementCss) {
  2485. if (pageElementCss !== '0' && !ele.dataset.pagetualPageElement) {
  2486. ele.style.cssText = (ele.style.cssText || '') + pageElementCss;
  2487. ele.dataset.pagetualPageElement = 1;
  2488. }
  2489. }
  2490. if (contentVisibility) {
  2491. ele.style.containIntrinsicSize = `auto ${ele.offsetHeight || self.preVisibleHeight || 100}px`;
  2492. if (ele.style.containIntrinsicSize) {
  2493. if (ele.offsetHeight) self.preVisibleHeight = ele.offsetHeight;
  2494. if (init) {
  2495. ele.style.contentVisibility = "visible";
  2496. self.visibilityItems.push(ele);
  2497. self.visibleIndex++;
  2498. } else {
  2499. ele.style.contentVisibility = emuIframe ? "visible" : "auto";
  2500. }
  2501. }
  2502. }
  2503. }
  2504. });
  2505. }
  2506. }
  2507.  
  2508. clearAddedElements() {
  2509. if (this.addedElePool && this.addedElePool.length) {
  2510. this.addedElePool.forEach(ele => {
  2511. if (ele.parentNode) ele.parentNode.removeChild(ele);
  2512. });
  2513. }
  2514. this.addedElePool = [];
  2515. sideController.remove();
  2516. }
  2517.  
  2518. linkHasHref(link) {
  2519. return link.href && link.href.replace && !this.hrefIsJs(link.href);
  2520. }
  2521.  
  2522. hrefIsJs(href) {
  2523. return /^(javascript|#|$)/.test(href.trim().replace("#p{", "").replace(location.href, ""));
  2524. }
  2525.  
  2526. async querySelectorList(source, list, defaultView) {
  2527. for (let i = 0; i < list.length; i++) {
  2528. await sleep(1);
  2529. let sel = list[i];
  2530. let result = getAllElements(sel, source);
  2531. if (result.length > 0) {
  2532. if (defaultView) {
  2533. for (let i = result.length - 1; i >= 0; i--) {
  2534. let ele = result[i];
  2535. if (isVisible(ele, defaultView)) return ele;
  2536. }
  2537. }
  2538. return result[result.length - 1];
  2539. }
  2540. }
  2541. return null;
  2542. }
  2543.  
  2544. verifyElement(ele) {
  2545. let verifyHandler = e => {
  2546. if (e.nodeType == 9) return true;
  2547. if (e.style.display === "none" || e.getAttribute("aria-disabled") === "true") {
  2548. return false;
  2549. }
  2550. if (e.className) {
  2551. if (/slick|slide|gallery|disabled\s*$/i.test(e.className)) {
  2552. return false;
  2553. } else if (e.classList) {
  2554. if (e.classList.contains('disabled') || e.classList.contains('active')) {
  2555. return false;
  2556. }
  2557. }
  2558. }
  2559. let ariaLabel = e.getAttribute("aria-label");
  2560. if (ariaLabel && /slick|slide|gallery/i.test(ariaLabel)) return false;
  2561. return true;
  2562. };
  2563. if (!ele) return false;
  2564. let i = 0;
  2565. while (ele && i++ < 6) {
  2566. if (!verifyHandler(ele)) return false;
  2567. ele = ele.parentNode;
  2568. }
  2569. return true;
  2570. }
  2571.  
  2572. async getPage(doc, exist) {
  2573. if (document.documentElement.className.indexOf && document.documentElement.className.indexOf('discourse') !== -1) return {};
  2574. let body = getBody(doc);
  2575. let canSave = false;//發現頁碼選擇器在其他頁對不上,還是別保存了
  2576. let url = this.curUrl.slice(0, 250).replace("index.php?", "?");
  2577. let _url = url.replace(/\.s?html?$/i, "").toLowerCase();
  2578. let pageNum = 1, preStr = "", afterStr = "";
  2579. let pageTwoReg = /^[\/\?&]?[_-]?(p|page)?=?\/?2(\/[^\/]*$|\?|&|$)/i;
  2580. let pageMatch1 = url.match(/(.*[\?&]p(?:age)?=)(\d+)($|[#&].*)/i);
  2581. let doubtTextReg = /^\s*(»|>>)\s*$/;
  2582. if (pageMatch1) {
  2583. preStr = pageMatch1[1];
  2584. pageNum = parseInt(pageMatch1[2]);
  2585. afterStr = pageMatch1[3];
  2586. } else {
  2587. let pageMatch2 = url.match(/(.*[a-z\/\-_](?:p|page)?\/?)(\d+)(\.s?html?$|\/?$)/i);
  2588. if (pageMatch2) {
  2589. preStr = pageMatch2[1];
  2590. pageNum = parseInt(pageMatch2[2]);
  2591. afterStr = pageMatch2[3];
  2592. if (/^\/?$/.test(afterStr) && !/(p(age)?|_|\-|\/)$/.test(preStr)) {
  2593. preStr = "";
  2594. afterStr = "";
  2595. }
  2596. }
  2597. }
  2598. if (pageNum > 999) {
  2599. pageNum = 1;
  2600. preStr = "";
  2601. afterStr = "";
  2602. }
  2603. let curPage = doc, i, cur, jsNext;
  2604. let next1, next2, next3, next4, nextJs1, nextJs2;
  2605. let selectorList = [
  2606. ".page-next>a",
  2607. "a.next_page",
  2608. "#next_page",
  2609. ".curPage+a",
  2610. ".nextPage",
  2611. ".pagination-next>a",
  2612. "a[data-pagination=next]",
  2613. ".pageButtonsCurrent+a",
  2614. "a[class*=nextpage]",
  2615. "li.page-current+li>a",
  2616. "[class^=pag] a[rel=next]",
  2617. "[class^=Pag] [aria-label=next]",
  2618. "[aria-label='Next Page']",
  2619. "[aria-label='Next page']",
  2620. "[aria-label='next page']",
  2621. ".pagination-nav__item--next>a",
  2622. "a.pageright",
  2623. ".page-numbers.current+a",
  2624. "a.page-numbers.next",
  2625. "body [class*=pagination] li.active+span+li>a",
  2626. "body [class*=pagination] li.active+li>a",
  2627. "body [class^=pag] .current+a",
  2628. ".page_current+a",
  2629. "input[value='next']",
  2630. "input[value='Next page']",
  2631. "input[value='下一页']",
  2632. "input[value='下一頁']",
  2633. "a#pb_next",
  2634. "a#rightFix",
  2635. "a#btnPreGn",
  2636. "a.page-next",
  2637. "a.pages-next",
  2638. "a.page.right",
  2639. ".paging>.active+.item",
  2640. "a#next",
  2641. ".next>a",
  2642. ".next>button",
  2643. "a[alt=next]",
  2644. ".pg_area>em+a",
  2645. "button.next:not([disabled])",
  2646. ".btn_next:not([disabled])",
  2647. ".btn-next:not([disabled])",
  2648. "a#linkNext",
  2649. "body a[class*=page__next]",
  2650. "body [class*=pager]>a.next",
  2651. "body [class*=pagination-next]>a",
  2652. "body [class*=pagination-next]>button",
  2653. "body [class*=page--current]+li>a",
  2654. "body [class*=Pages]>.curr+a",
  2655. "body [class*=pagination] [class*=next]",
  2656. ".page>em+a",
  2657. "[name*=nextPage]",
  2658. '//button[contains(@class, "Page")][text()="Next"]',
  2659. '//button[contains(@class, "page")][text()="next"]'
  2660. ];
  2661. let next = await this.querySelectorList(body, selectorList, doc.defaultView);
  2662. if (!next) {
  2663. await sleep(1);
  2664. let nexts = body.querySelectorAll("a.next");
  2665. const prevReg = /^\s*([上前首尾]|previous)/i;
  2666. for (i = 0; i < nexts.length; i++) {
  2667. let n = nexts[i];
  2668. if (this.verifyElement(n) && this.linkHasHref(n) && !prevReg.test(n.innerText.trim())) {
  2669. next = n;
  2670. break;
  2671. }
  2672. }
  2673. }
  2674. if (next) {
  2675. let innerText = next.innerText;
  2676. let isJs = !this.linkHasHref(next);
  2677. if (innerText && nextTextReg2.test(innerText.trim())) {
  2678. if (isJs) {
  2679. if (this.verifyElement(next)) {
  2680. nextJs2 = next;
  2681. }
  2682. } else {
  2683. next2 = next;
  2684. }
  2685. next = null;
  2686. } else {
  2687. if (isJs) {
  2688. if (this.verifyElement(next)) {
  2689. jsNext = next;
  2690. }
  2691. next = null;
  2692. }
  2693. }
  2694. }
  2695. if (!next) {
  2696. await sleep(1);
  2697. next = body.querySelector("a.curr+a") ||
  2698. body.querySelector("div.wp-pagenavi>span.current+a,div.page-nav>span.current+a,div.article-paging>span+a") ||
  2699. body.querySelector(".number>ul>li.active+li>a");
  2700. }
  2701. if (!next) {
  2702. await sleep(1);
  2703. let pageDiv = body.querySelector(".pages>ul,.page_no>ul");
  2704. if (pageDiv) {
  2705. cur = pageDiv.querySelector("li>b,li>strong");
  2706. if (cur) next = cur.parentNode.nextElementSibling;
  2707. if (next) next = next.querySelector("a");
  2708. }
  2709. }
  2710. if (!next) {
  2711. await sleep(1);
  2712. next = body.querySelector(".pages>a[href='javascript:;']+a");
  2713. if (next && (next.href === "javascript:;" || next.getAttribute("href") === "#")) next = null;
  2714. }
  2715. if (!next) {
  2716. await sleep(1);
  2717. let pageDiv = body.querySelector(".pagination");
  2718. if (pageDiv) {
  2719. cur = pageDiv.querySelector("[class*=current],.page-selected");
  2720. if (cur) next = cur.parentNode.nextElementSibling;
  2721. if (next) next = next.querySelector("a");
  2722. }
  2723. }
  2724. if (!next) {
  2725. await sleep(1);
  2726. let pageDivs = body.querySelectorAll("[class*=pagination],[class*=Pagination]");
  2727. if (pageDivs && pageDivs.length) {
  2728. for (let i = pageDivs.length - 1; i >= 0; i--) {
  2729. let p = pageDivs[i];
  2730. if (/(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)/i.test(p.title || p.value || '')) {
  2731. next = p.querySelector("a,button,[type='button']") || p;
  2732. break;
  2733. } else if (/^(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)$/i.test((p.innerText || '').trim())) {
  2734. next = p.querySelector("a,button,[type='button']") || p;
  2735. break;
  2736. }
  2737. }
  2738. if (next && !this.linkHasHref(next)) {
  2739. if (!jsNext) jsNext = next;
  2740. next = null;
  2741. }
  2742. }
  2743. }
  2744. if (!next) {
  2745. let isApp = !!body.querySelector("main#app");
  2746. let aTags = body.querySelectorAll("a,button,[type='button'],.btn-action");
  2747. for (i = aTags.length - 1; i >= 0; i--) {
  2748. if (next1) break;
  2749. if (i % 100 === 0) {
  2750. await sleep(1);
  2751. }
  2752. let aTag = aTags[i];
  2753. let title = aTag.title || "";
  2754. let value = aTag.value || "";
  2755. let innerText = aTag.innerText || "";
  2756. if (innerText === "" || (title !== "" && title.length < innerText.length)) {
  2757. innerText = title;
  2758. }
  2759. if (innerText === "" || (value !== "" && value.length < innerText.length)) {
  2760. innerText = value;
  2761. }
  2762. if (innerText !== "") {
  2763. if (innerText === "§") continue;
  2764. innerText = innerText.trim();
  2765. if (innerText.length > 80) continue;
  2766. }
  2767. if (!this.verifyElement(aTag)) continue;
  2768. if (aTag.dataset && aTag.dataset.preview) continue;
  2769. let availableHref = aTag.href && aTag.href.length < 250 && !/^(javascript:|#)/.test(aTag.href);
  2770. if (availableHref && /next\-?(page)?$|\/video\/|\/vod\/play\//i.test(aTag.href)) continue;
  2771. if (compareNodeName(aTag.parentNode, ["blockquote"])) continue;
  2772. if (aTag.previousElementSibling && /\b(play|volume)\b/.test(aTag.previousElementSibling.className)) continue;
  2773. if (aTag.nextElementSibling && /\b(play|volume)\b/.test(aTag.nextElementSibling.className)) continue;
  2774. let isJs = !this.linkHasHref(aTag);
  2775. if (exist && isJs && !aTag.offsetParent) continue;
  2776. if (innerText) {
  2777. innerText = innerText.split(/\n/)[0].replace(/ /g, '');
  2778. if (isJs && /^(»|>>|>|›|→|❯)$/.test(innerText)) continue;
  2779. if (innerText && innerText.length <= 25) {
  2780. if (!next1) {
  2781. if (nextTextReg1.test(innerText)) {
  2782. if (isJs) {
  2783. if (!nextJs1) nextJs1 = aTag;
  2784. } else {
  2785. next1 = aTag;
  2786. }
  2787. }
  2788. }
  2789. if (!next4) {
  2790. if (!next2) {
  2791. if (nextTextReg2.test(innerText) || /nextpage|pager\-older/i.test(aTag.className) || /^(»|>>)$/.test(innerText)) {
  2792. if (isJs) {
  2793. if (!nextJs2) nextJs2 = aTag;
  2794. } else {
  2795. next2 = aTag;
  2796. }
  2797. }
  2798. }
  2799. if (!isApp && !next3 && !isJs) {
  2800. if (/^(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)$/i.test(aTag.textContent) && aTag.parentNode.hasAttribute && !aTag.parentNode.hasAttribute("jsaction")) {
  2801. next3 = aTag;
  2802. }
  2803. }
  2804. }
  2805. }
  2806. }
  2807. if (isJs) continue;
  2808. if (!next4) {
  2809. let prevEle = aTag.previousElementSibling;
  2810. if (prevEle && compareNodeName(prevEle, ["b", "span", "strong"])) {
  2811. if (/^\d+$/.test(aTag.innerText.trim()) && /^\d+$/.test(prevEle.innerText.trim()) && parseInt(aTag.innerText) === parseInt(prevEle.innerText) + 1) {
  2812. next4 = aTag;
  2813. }
  2814. }
  2815. }
  2816. if (urlWillChange) continue;
  2817. if (!next4 && availableHref) {
  2818. let aHref = aTag.href.indexOf("http") === 0 ? aTag.href : this.canonicalUri(aTag.href);
  2819. if (aHref.indexOf(location.hostname) === -1) continue;
  2820. let _aHref = aHref.replace("?&", "?").replace("index.php?", "?");
  2821. if (preStr || afterStr) {
  2822. let _aHrefTrim = _aHref;
  2823. if (preStr) _aHrefTrim = _aHrefTrim.replace(preStr, "");
  2824. if (afterStr) _aHrefTrim = _aHrefTrim.replace(afterStr, "");
  2825. if (_aHrefTrim == pageNum + 1) {
  2826. next4 = aTag;
  2827. }
  2828. } else if (this.curUrl !== aHref) {
  2829. _aHref = _aHref.replace(/\.s?html?$/i, "").toLowerCase();
  2830. if (_aHref.indexOf(_url) !== -1) {
  2831. let pageTwoMatch = _aHref.replace(_url, "").match(pageTwoReg);
  2832. if (pageTwoMatch) {
  2833. afterStr = pageTwoMatch[2];
  2834. next4 = aTag;
  2835. }
  2836. }
  2837. }
  2838. if (next4 && !/page/.test(next4.href)) {
  2839. let curHref = next4.getAttribute("href");
  2840. let curPageReg = new RegExp("(.*)" + (pageNum + 1) + afterStr.replace(/([\.\?])/g, '\\$1'));
  2841. let otherPageHref = curHref.replace(curPageReg, `$1${pageNum}${afterStr}`);
  2842. let otherPageEle = body.querySelector(`a[href='${otherPageHref}']`);
  2843. if (!otherPageEle) {
  2844. otherPageHref = curHref.replace(curPageReg, `$1${pageNum + 2}${afterStr}`);
  2845. otherPageEle = body.querySelector(`a[href='${otherPageHref}']`);
  2846. }
  2847. if (otherPageEle) {
  2848. let parent = otherPageEle.parentNode;
  2849. if (parent && parent.parentNode) {
  2850. parent = parent.parentNode;
  2851. if (parent.parentNode) {
  2852. parent = parent.parentNode;
  2853. }
  2854. }
  2855. if (parent && parent.contains(next4) && !/^\d+$/.test(next4.innerText.trim())) {
  2856. next4 = null;
  2857. }
  2858. }
  2859. }
  2860. }
  2861. }
  2862. if (next2 && doubtTextReg.test(next2.innerText)) {
  2863. next2 = this.verifyNext(next2, doc, false);
  2864. }
  2865. if (nextJs2 && doubtTextReg.test(nextJs2.innerText)) {
  2866. nextJs2 = this.verifyNext(nextJs2, doc, true);
  2867. }
  2868. if (next3) {
  2869. next3 = this.verifyNext(next3, doc, false);
  2870. }
  2871. }
  2872. if (!next) next = next1 || next4 || next3 || next2;
  2873. if (!next && location.pathname + location.search !== "/") {
  2874. next = jsNext || nextJs1 || nextJs2;
  2875. if (next && next.parentNode.className && next.parentNode.className.indexOf && next.parentNode.className.indexOf('tab') !== -1) next = null;
  2876. }
  2877. if (next && next.classList && (next.classList.contains("results-more") || next.classList.contains("no"))) next = null;
  2878. if (next && next.hasAttribute && next.hasAttribute("disabled")) next = null;
  2879. if (next && next.parentNode.href && compareNodeName(next.parentNode, ["a"])) next = next.parentNode;
  2880. return {next:next, canSave:canSave};
  2881. }
  2882.  
  2883. verifyNext(next, doc, isJs) {
  2884. if (!next) return null;
  2885. if (!isJs) {
  2886. let href = next.getAttribute("href");
  2887. if (href && !/\d/.test(next.getAttribute("href"))) {
  2888. return null;
  2889. }
  2890. }
  2891. if (next.previousElementSibling && compareNodeName(next.previousElementSibling, ["br"])) return null;
  2892. let eles = [];
  2893. if (next.innerText && next.innerText.indexOf("\n") === -1) {
  2894. eles = getAllElements(`//${next.nodeName}[text()='${next.innerText}']`, doc);
  2895. }
  2896. if (eles.length >= 2 && eles[0].href !== eles[1].href) {
  2897. next = null;
  2898. } else if (doc === document) {
  2899. let left = getElementLeft(next);
  2900. if (left < 20 || (document.documentElement.scrollWidth > 500 && left < 250)) {
  2901. next = null;
  2902. } else {
  2903. let top = getElementTop(next);
  2904. if (top < 20 || (left < window.innerWidth / 3 && top < window.innerHeight / 3)) {
  2905. next = null;
  2906. } else {
  2907. let bottom = top + next.offsetHeight || 0;
  2908. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  2909. if (scrollH - bottom < 10) next = null;
  2910. }
  2911. }
  2912. }
  2913. return next;
  2914. }
  2915.  
  2916. canonicalUri(src) {
  2917. if (!src) {
  2918. return "";
  2919. }
  2920. if (src.charAt(0) === "#") return this.curUrl + src;
  2921. if (src.charAt(0) === "?") return this.curUrl.replace(/^([^\?#]+).*/, "$1" + src);
  2922. let origin = location.protocol + '//' + location.host;
  2923. let url = this.basePath || origin;
  2924. url = url.replace(/(\?|#).*/, "");
  2925. if (/https?:\/\/[^\/]+$/.test(url)) url = url + '/';
  2926. if (url.indexOf("http") !== 0) url = origin + url;
  2927. var root_page = /^[^\?#]*\//.exec(url)[0],
  2928. root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  2929. absolute_regex = /^\w+\:\/\//;
  2930. this.updateUrl = false;
  2931. while (src.indexOf("../") === 0) {
  2932. src = src.substr(3);
  2933. root_page = root_page.replace(/\/[^\/]+\/$/, "/");
  2934. this.updateUrl = true;
  2935. }
  2936. src = src.replace(/\.\//, "");
  2937. if (/^\/\/\/?/.test(src)) {
  2938. src = location.protocol + src;
  2939. }
  2940. return (absolute_regex.test(src) ? src : ((src.charAt(0) === "/" ? root_domain : root_page) + src));
  2941. }
  2942.  
  2943. getLinkByPage(url, pageNum) {
  2944. if (!url) return null;
  2945. if (this.curSiteRule.pageNum) {
  2946. let result = this.curSiteRule.pageNum;
  2947. let strMatch = result.match(/\{.*?}/);
  2948. if (!strMatch) return null;
  2949. let urlReg = new RegExp("(" + result.replace(strMatch[0], ")\\d+(") + ")", "i");
  2950. let code = strMatch[0].replace(/^{/, "").replace(/}$/, "").replace(/\$p/g, pageNum);
  2951. if (code === pageNum) {
  2952. result = url.replace(urlReg, "$1" + code + "$2");
  2953. } else {
  2954. try {
  2955. code = Function('"use strict";return ' + code)();
  2956. if (code && code % 1 == 0) {
  2957. result = url.replace(urlReg, "$1" + code + "$2");
  2958. } else return null;
  2959. } catch(e) {
  2960. debug(e);
  2961. }
  2962. }
  2963. if (result != url) {
  2964. return result;
  2965. }
  2966. }
  2967. return url.replace(/([&\/\?](p=|page[=\/_-]?))\d+/i, "$1" + pageNum).replace(/([_-])\d+\./i, "$1" + pageNum + ".");
  2968. }
  2969.  
  2970. getPageNumFromUrl(url, defaultPage) {
  2971. if (!url) return defaultPage;
  2972. if (this.curSiteRule.pageNum) {
  2973. let result = this.curSiteRule.pageNum;
  2974. let strMatch = result.match(/\{.*?}/);
  2975. if (!strMatch) return defaultPage;
  2976. let urlReg = new RegExp(".*" + result.replace(strMatch[0], "(\\d+)") + ".*", "i");
  2977. let curShowNum = url.replace(urlReg, "$1");
  2978. if (curShowNum !== url) {
  2979. let code = strMatch[0].replace(/^{/, "").replace(/}$/, "");
  2980. if (code === "$p") {
  2981. return curShowNum;
  2982. } else {
  2983. try {
  2984. let page1 = parseInt(Function('"use strict";return ' + code.replace("$p", "0"))());
  2985. let page2 = parseInt(Function('"use strict";return ' + code.replace("$p", "1"))());
  2986. let numGap = page2 - page1;
  2987. let _page = (parseInt(curShowNum) - page1) / numGap;
  2988. if (_page && _page % 1 === 0) return _page;
  2989. else {
  2990. this.curSiteRule.pageNum = null;
  2991. return defaultPage;
  2992. }
  2993. } catch(e) {
  2994. debug(e);
  2995. }
  2996. }
  2997. } else {
  2998. return defaultPage;
  2999. }
  3000. }
  3001. let pageNum = url.replace(/.*[&\/\?](p=|page[=\/_-]?)(\d+).*/i, "$2");
  3002. return pageNum === url ? defaultPage : (pageNum.length > 4 ? defaultPage : pageNum);
  3003. }
  3004.  
  3005. async getNextLink(doc, exist) {
  3006. let nextLink = null, page, href;
  3007. let getNextLinkByForm = (form, submitBtn, n) => {
  3008. let params = [];
  3009. let formData = new FormData(form);
  3010. if (submitBtn && submitBtn.getAttribute) {
  3011. let btnValue, btnName;
  3012. btnName = submitBtn.getAttribute("name");
  3013. btnValue = submitBtn.getAttribute("value");
  3014. if (btnName && btnValue) params = [btnName + "=" + encodeURIComponent(btnValue)];
  3015. }
  3016. for (let [key, value] of formData) {
  3017. if (n && /^(p|page)$/i.test(key)) {
  3018. params.push(key + '=' + n);
  3019. } else {
  3020. params.push(key + '=' + encodeURIComponent(value));
  3021. }
  3022. }
  3023. params = params.join('&');
  3024. return form.action + (form.action.indexOf('?') === -1 ? '?' : '&') + params + (form.method === 'post' ? '#p{' + params + '}' : '');
  3025. };
  3026. if (this.curSiteRule.pageElementByJs) {
  3027. this.nextLinkHref = "#";
  3028. return true;
  3029. } else if (this.curSiteRule.nextLinkByJs) {
  3030. try {
  3031. let over = _url => {};
  3032. let targetUrl = await ((typeof this.curSiteRule.nextLinkByJs === 'function') ? this.curSiteRule.nextLinkByJs : new AsyncFunction("doc", '"use strict";' + this.curSiteRule.nextLinkByJs))(doc);
  3033. if (targetUrl) nextLink = {href: targetUrl};
  3034. } catch(e) {
  3035. debug(e);
  3036. }
  3037. } else if (this.curSiteRule.nextLinkByUrl) {
  3038. let targetUrl = this.curUrl.replace(new RegExp(this.curSiteRule.nextLinkByUrl[0], "i"), this.curSiteRule.nextLinkByUrl[1]);
  3039. if (targetUrl !== this.curUrl) {
  3040. let includeSel = this.curSiteRule.nextLinkByUrl[2];
  3041. let excludeSel = this.curSiteRule.nextLinkByUrl[3];
  3042. if (includeSel) {
  3043. includeSel = includeSel.trim();
  3044. if (!getElement(includeSel, doc)) {
  3045. this.nextLinkHref=false;
  3046. return null;
  3047. }
  3048. }
  3049. if (excludeSel) {
  3050. excludeSel = excludeSel.trim();
  3051. if (getElement(excludeSel, doc)) {
  3052. this.nextLinkHref=false;
  3053. return null;
  3054. }
  3055. }
  3056. let reps = targetUrl.match(/{.*?}/g);
  3057. if (reps) {
  3058. reps.forEach(rep => {
  3059. let code = rep.replace("{", "").replace("}", "").replace(/\(\)/g, "0");
  3060. let result = code.match(/^(\d*)\+1$/);
  3061. if (result) {
  3062. result = parseInt(result[1] || 1) + 1;
  3063. } else {
  3064. try {
  3065. result = Function('"use strict";return ' + code)();
  3066. } catch(e) {
  3067. debug(e);
  3068. }
  3069. }
  3070. targetUrl = targetUrl.replace(rep, result);
  3071. });
  3072. }
  3073. }
  3074. nextLink = {href: targetUrl};
  3075. } else if (typeof this.curSiteRule.nextLink !== 'undefined') {
  3076. let nextLinkSel = this.curSiteRule.nextLink;
  3077. if (nextLinkSel != 0) {
  3078. if (Array && Array.isArray && Array.isArray(nextLinkSel)) {
  3079. nextLink = getElement(nextLinkSel[nextIndex], doc, null, true);
  3080. if (!nextLink && curPage === 1 && nextIndex !== 0) {
  3081. nextIndex = 0;
  3082. nextLink = getElement(nextLinkSel[nextIndex], doc, null, true);
  3083. }
  3084. } else nextLink = getElement(nextLinkSel, doc, null, true);
  3085. }
  3086. if (nextLink && (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2)) {
  3087. let form = doc.querySelector('#search-form');
  3088. if (!nextLink.href && nextLink.hasAttribute && nextLink.hasAttribute("onclick") && form) {
  3089. if (/^\d+$/.test(nextLink.innerText)) {
  3090. nextLink.href = getNextLinkByForm(form, nextLink, nextLink.innerText);
  3091. }
  3092. } else if (compareNodeName(nextLink, ["input"]) || nextLink.type === "submit") {
  3093. form = nextLink.parentNode;
  3094. while (form) {
  3095. if (compareNodeName(form, ["form"])) break;
  3096. else form = form.parentNode;
  3097. }
  3098. if (form) {
  3099. nextLink.href = getNextLinkByForm(form, nextLink);
  3100. }
  3101. }
  3102. if (nextLink.href && this.curSiteRule.action != 0) {
  3103. nextLink.href = nextLink.href.replace(/#p{.*/, "");
  3104. }
  3105. }
  3106. } else {
  3107. page = await this.getPage(doc, exist);
  3108. nextLink = page.next;
  3109. if (nextLink) {
  3110. if (compareNodeName(nextLink, ["input"]) || nextLink.type === "submit") {
  3111. if (!/next/i.test(nextLink.getAttribute("onclick"))) {
  3112. let form = nextLink.parentNode;
  3113. while (form) {
  3114. if (compareNodeName(form, ["form"])) break;
  3115. else form = form.parentNode;
  3116. }
  3117. if (form) {
  3118. nextLink.href = getNextLinkByForm(form, nextLink);
  3119. }
  3120. }
  3121. }
  3122. let parent = nextLink;
  3123. while (parent && !compareNodeName(parent, ["body"])) {
  3124. if (parent.hasAttribute && parent.hasAttribute("disabled")) {
  3125. this.nextLinkHref = false;
  3126. return null;
  3127. }
  3128. if (parent.className && parent.classList) {
  3129. if (parent.classList.contains("noClick") || parent.classList.contains("no-pages") || parent.classList.contains("disabled")) {
  3130. this.nextLinkHref = false;
  3131. return null;
  3132. }
  3133. }
  3134. if (parent.style && parent.style.display === "none") {
  3135. this.nextLinkHref = false;
  3136. return null;
  3137. }
  3138. parent = parent.parentNode;
  3139. }
  3140. if (doc === document) {
  3141. if (!this.linkHasHref(nextLink)) {
  3142. if ((clickedSth && this.curSiteRule.smart) || !isVisible(nextLink, _unsafeWindow)) {
  3143. this.nextLinkHref = false;
  3144. return null;
  3145. }
  3146. let video = document.querySelector("video,iframe[id*=play],[id*=play]>iframe,iframe[src*=player],iframe[src*=m3u8]");
  3147. if (video) {
  3148. if (video.offsetParent && video.name !== 'pagetual-iframe') {
  3149. let scrollWidth = video.scrollWidth || video.offsetWidth;
  3150. let scrollHeight = video.scrollHeight || video.offsetHeight;
  3151. if (compareNodeName(video, ["iframe"])) {
  3152. } else if (scrollWidth > 100 && scrollHeight > 100) {
  3153. let winWidth = window.innerWidth || document.documentElement.clientWidth;
  3154. let winHeight = window.innerHeight || document.documentElement.clientHeight;
  3155. if (scrollWidth > winWidth>>1 && scrollHeight > winHeight>>1) {
  3156. debug("Disable when large media found");
  3157. } else {
  3158. video = null;
  3159. }
  3160. } else {
  3161. video = null;
  3162. }
  3163. } else {
  3164. video = null;
  3165. }
  3166. }
  3167. if (video) {
  3168. isPause = true;
  3169. this.clearAddedElements();
  3170. this.nextLinkHref = false;
  3171. return null;
  3172. }
  3173. }
  3174.  
  3175. let nextLinkCs = _unsafeWindow.getComputedStyle(nextLink);
  3176. if (nextLinkCs.cursor === "not-allowed") {
  3177. this.nextLinkHref = false;
  3178. return null;
  3179. }
  3180. this.initNext = nextLink;
  3181. }
  3182. let form = doc.querySelector('#search-form');
  3183. if (!nextLink.href && nextLink.hasAttribute("onclick") && form) {
  3184. if (form && /^\d+$/.test(nextLink.innerText)) {
  3185. href = getNextLinkByForm(form, nextLink, nextLink.innerText);
  3186. }
  3187. }
  3188. }
  3189. }
  3190. if (nextLink) {
  3191. if (!this.checkStopSign(nextLink, doc)) {
  3192. if (curPage > 1) {
  3193. if (rulesData.lastPageTips) {
  3194. showTips(i18n("lastPage"), "", 800);
  3195. }
  3196. _unsafeWindow.postMessage({
  3197. action: "lastPage",
  3198. command: 'pagetual'
  3199. }, '*');
  3200. }
  3201. return null;
  3202. }
  3203. if (this.curSiteRule.action == 3) {
  3204. if (doc == document) debug(nextLink, 'Next link');
  3205. this.nextLinkHref = '#';
  3206. } else {
  3207. let needUrl = (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2);
  3208. if (!href) href = nextLink.href;
  3209. if (href && nextLink.getAttribute) {
  3210. let _href = nextLink.getAttribute("href");
  3211. if (_href) {
  3212. if (_href.charAt(0) === "#" || _href === "?"){
  3213. href = "#";
  3214. } else {
  3215. href = _href;
  3216. }
  3217. } else if (_href === "") {
  3218. href = _href;
  3219. }
  3220. }
  3221.  
  3222. if (needUrl && (href === "" || href === null)) {
  3223. this.nextLinkHref = false;
  3224. } else if (needUrl && /^(javascript:|#)/.test(href)) {
  3225. this.nextLinkHref = false;
  3226. } else {
  3227. this.nextLinkHref = (href && !/^(javascript:|#)/.test(href)) ? this.canonicalUri(href) : "#";
  3228. let tempUrl = this.nextLinkHref;
  3229. 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 + "#"))) {
  3230. this.nextLinkHref = false;
  3231. } else if (doc === document) {
  3232. debug(nextLink, 'Next link');
  3233. }
  3234. }
  3235. }
  3236. } else {
  3237. this.nextLinkHref = false;
  3238. }
  3239. this.nextLinkEle = nextLink;
  3240. this.preload();
  3241. return nextLink;
  3242. }
  3243.  
  3244. compareUrl(url1, url2) {
  3245. if (url1 === url2) return true;
  3246. if (!url1 || !url2) return false;
  3247. let url1Arr = url1.split("?");
  3248. let url2Arr = url2.split("?");
  3249. if (url1Arr[0] != url2Arr[0]) return false;
  3250. if (!url1Arr[1] || !url2Arr[1]) return false;
  3251. url1Arr = url1Arr[1].split("&").sort().join("&");
  3252. url2Arr = url2Arr[1].split("&").sort().join("&");
  3253. return url1Arr === url2Arr;
  3254. }
  3255.  
  3256. filterEles(doc, eles) {
  3257. let filter = this.curSiteRule.filter;
  3258. if (!filter || !eles || eles.length === 0) return;
  3259. if (eles.length === 1) {
  3260. eles = eles[0].children;
  3261. if (eles.length === 1) {
  3262. eles = eles[0].children;
  3263. }
  3264. }
  3265. if (typeof filter === "string") {
  3266. if (/^\d+$/.test(filter)) {
  3267. filter = {count: parseInt(filter)};
  3268. } else filter = {words: filter};
  3269. }
  3270. [].forEach.call(eles, ele => {
  3271. if (!ele.parentNode) return;
  3272. let canKeep = (() => {
  3273. let innerText = (ele.innerText && ele.innerText.trim()) || "";
  3274. if (filter.count) {
  3275. if (innerText.length < filter.count) return false;
  3276. }
  3277. if (filter.words) {
  3278. let wordsRegExp = new RegExp(filter.words, "i");
  3279. if (innerText && wordsRegExp.test(innerText)) return false;
  3280. }
  3281. if (filter.link) {
  3282. let linkRegExp = new RegExp(filter.link, "i");
  3283. if (compareNodeName(ele, ["a"]) && linkRegExp.test(ele.href)) return false;
  3284. let aChildren = ele.querySelectorAll("a");
  3285. for (let i = 0; i < aChildren.length; i++) {
  3286. let child = aChildren[i];
  3287. if (linkRegExp.test(child.href)) return false;
  3288. }
  3289. }
  3290. if (filter.selector) {
  3291. if (getElement(filter.selector, doc, ele)) return false;
  3292. }
  3293. return true;
  3294. })();
  3295. if (!canKeep) {
  3296. ele.parentNode.removeChild(ele);
  3297. }
  3298. });
  3299. }
  3300.  
  3301. checkStopSign(nextLink, doc) {
  3302. if (this.curSiteRule.stopSign) {
  3303. let typeArray = Array && Array.isArray && Array.isArray(this.curSiteRule.stopSign);
  3304. let typeObject = !typeArray && (this.curSiteRule.stopSign.include || this.curSiteRule.stopSign.exclude || this.curSiteRule.stopSign.pageNum);
  3305. if (typeArray || typeObject) {
  3306. let includeSel, excludeSel, curSign, maxSign;
  3307. if (typeArray) {
  3308. includeSel = this.curSiteRule.stopSign[0];
  3309. excludeSel = this.curSiteRule.stopSign[1];
  3310. curSign = this.curSiteRule.stopSign[2];
  3311. maxSign = this.curSiteRule.stopSign[3];
  3312. if (Array && Array.isArray && Array.isArray(includeSel) && !curSign) {
  3313. curSign = includeSel;
  3314. includeSel = false;
  3315. }
  3316. if (excludeSel && Array && Array.isArray && Array.isArray(excludeSel) && !maxSign) {
  3317. maxSign = excludeSel;
  3318. excludeSel = false;
  3319. }
  3320. } else {
  3321. includeSel = this.curSiteRule.stopSign.include;
  3322. excludeSel = this.curSiteRule.stopSign.exclude;
  3323. curSign = this.curSiteRule.stopSign.pageNum;
  3324. }
  3325. if (includeSel) {
  3326. includeSel = includeSel.trim();
  3327. if (!getElement(includeSel, doc)) {
  3328. isPause = true;
  3329. this.nextLinkHref = false;
  3330. return false;
  3331. }
  3332. }
  3333. if (excludeSel) {
  3334. excludeSel = excludeSel.trim();
  3335. if (getElement(excludeSel, doc)) {
  3336. isPause = true;
  3337. this.nextLinkHref = false;
  3338. return false;
  3339. }
  3340. }
  3341. if (curSign) {
  3342. if (!maxSign) maxSign = curSign.slice(2);
  3343. let currentEle = getElement(curSign[0], doc);
  3344. let maxEle = getElement(maxSign[0], doc);
  3345. if (currentEle && maxEle) {
  3346. let currentSignNum, maxSignNum;
  3347. if (/\(.*\)/.test(curSign[1])) {
  3348. currentSignNum = currentEle.innerText.match(new RegExp(curSign[1]));
  3349. if (currentSignNum) currentSignNum = currentSignNum[1];
  3350. } else if (currentEle.getAttribute) {
  3351. currentSignNum = currentEle.getAttribute(curSign[1]);
  3352. }
  3353. if (/\(.*\)/.test(maxSign[1])) {
  3354. maxSignNum = maxEle.innerText.match(new RegExp(maxSign[1]));
  3355. if (maxSignNum) maxSignNum = maxSignNum[1];
  3356. } else if (maxEle.getAttribute) {
  3357. maxSignNum = maxEle.getAttribute(maxSign[1]);
  3358. }
  3359. if (currentSignNum && maxSignNum && currentSignNum == maxSignNum) {
  3360. isPause = true;
  3361. this.nextLinkHref = false;
  3362. return false;
  3363. }
  3364. }
  3365. }
  3366. } else {
  3367. try {
  3368. let stopSign = ((typeof this.curSiteRule.stopSign === 'function') ? this.curSiteRule.stopSign : Function("doc", "nextLink", '"use strict";' + this.curSiteRule.stopSign))(doc, nextLink);
  3369. if (stopSign) {
  3370. isPause = true;
  3371. this.nextLinkHref = false;
  3372. return false;
  3373. }
  3374. } catch(e) {
  3375. debug(e);
  3376. }
  3377. }
  3378. }
  3379. return true;
  3380. }
  3381.  
  3382. preloadImageHandler() {
  3383. if (this.preloadingImage || !this.unCheckedImgs.length) return;
  3384. this.preloadingImage = true;
  3385. setTimeout(() => {
  3386. this.preloadingImage = false;
  3387. this.preloadImageHandler();
  3388. }, 10);
  3389. let iSrc = this.unCheckedImgs.shift();
  3390. let img = document.createElement('img');
  3391. img.src = iSrc;
  3392. this.preloadDiv.appendChild(img);
  3393. }
  3394.  
  3395. preload() {
  3396. if (!rulesData.preload) return;
  3397. if (this.curSiteRule.preload === 0) return;
  3398. if (!this.nextLinkHref || this.nextLinkHref == "#") return;
  3399. if (this.readyStateUnComplete) return;
  3400. if (document.readyState !== 'complete') {
  3401. this.readyStateUnComplete = true;
  3402. let self = this;
  3403. window.addEventListener("load", e => {
  3404. self.readyStateUnComplete = false;
  3405. self.preload();
  3406. });
  3407. return;
  3408. }
  3409. let self = this, url = this.nextLinkHref;
  3410. let postParams = url.match(/#p{(.*)}$/);
  3411. if (postParams) {
  3412. postParams = postParams[1];
  3413. url = url.replace(/#p{.*/, "");
  3414. }
  3415. _GM_xmlhttpRequest({
  3416. url: url,
  3417. method: postParams ? 'POST' : 'GET',
  3418. data: postParams,
  3419. overrideMimeType: 'text/html;charset=' + charset,
  3420. headers: {
  3421. 'Referer': location.href,
  3422. 'User-Agent': navigator.userAgent,
  3423. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + charset,
  3424. },
  3425. timeout: 10000,
  3426. onload: function(res) {
  3427. var doc = null;
  3428. try {
  3429. doc = document.implementation.createHTMLDocument('');
  3430. doc.documentElement.innerHTML = createHTML(res.response);
  3431. var body = getBody(doc);
  3432. if (!self.preloadDiv) {
  3433. self.preloadDiv = document.createElement('div');
  3434. self.preloadDiv.id = "pagetual-preload";
  3435. self.preloadDiv.style.cssText = 'display:none!important;';
  3436. getBody(document).appendChild(self.preloadDiv);
  3437. self.checkedImgs = {};
  3438. self.unCheckedImgs = [];
  3439. }
  3440. let code = self.curSiteRule.preloadImages;
  3441. if (code) {
  3442. let imgSrcArr = new Function("doc", '"use strict";' + code)(doc);
  3443. if (imgSrcArr && imgSrcArr.length) {
  3444. imgSrcArr.forEach(imgSrc => {
  3445. if (imgSrc && !self.checkedImgs[imgSrc]) {
  3446. self.checkedImgs[imgSrc] = true;
  3447. self.unCheckedImgs.push(imgSrc);
  3448. }
  3449. });
  3450. }
  3451. self.preloadImageHandler();
  3452. } else if (code !== 0 && code !== false) {
  3453. if (body && body.firstChild) {
  3454. self.lazyImgAction(body.children, doc);
  3455. }
  3456. [].forEach.call(doc.images, i => {
  3457. let iSrc = i.src;
  3458. if (iSrc && !self.checkedImgs[iSrc]) {
  3459. self.checkedImgs[iSrc] = true;
  3460. self.unCheckedImgs.push(iSrc);
  3461. }
  3462. });
  3463. self.preloadImageHandler();
  3464. }
  3465. }
  3466. catch(e) {
  3467. debug(e);
  3468. return;
  3469. }
  3470. }
  3471. });
  3472. }
  3473.  
  3474. getInsert(refresh) {
  3475. if (refresh) {
  3476. this.insert = null;
  3477. }
  3478. if (this.insert && this.insert.parentNode && document.documentElement.contains(this.insert)) {
  3479. return this.insert;
  3480. }
  3481. if (this.curSiteRule.insert) {
  3482. let insertSel = this.curSiteRule.insert;
  3483. if (Array && Array.isArray && Array.isArray(insertSel)) {
  3484. insertSel = insertSel[nextIndex < insertSel.length ? nextIndex : 0];
  3485. }
  3486. this.insert = getElement(insertSel, document, null, true);
  3487. } else {
  3488. this.docPageElement = null;
  3489. let pageElement = this.getPageElement(document, _unsafeWindow);
  3490. if (this.curSiteRule.smart && this.nextLinkHref == "#" && this.curSiteRule.pageElement === 'body') {
  3491. debug("Stop as jsNext & whole body");
  3492. isPause = true;
  3493. return null;
  3494. }
  3495. if (pageElement && pageElement.length > 0) {
  3496. let pEIndex = pageElement.length - 1;
  3497. let pELast = pageElement[pEIndex];
  3498. while(pELast && compareNodeName(pELast, ["link", "meta", "style", "script"])) {
  3499. pEIndex--;
  3500. pELast = pageElement[pEIndex];
  3501. }
  3502. this.insert = pELast.nextSibling ? pELast.nextSibling : pELast.parentNode.appendChild(document.createTextNode(' '));
  3503. }
  3504. }
  3505. return this.insert;
  3506. }
  3507.  
  3508. pageInit(doc, eles) {
  3509. let code = this.curSiteRule.pageInit;
  3510. if (code) {
  3511. let initFunc = ((typeof code == 'function') ? code : Function("doc", "eles", '"use strict";' + code));
  3512. let checkInit = (resolve) => {
  3513. try {
  3514. if (initFunc(doc, eles) === false) {
  3515. setTimeout(() => {
  3516. checkInit(resolve);
  3517. }, 100);
  3518. } else {
  3519. resolve(true);
  3520. }
  3521. } catch(e) {
  3522. resolve(false);
  3523. debug(e);
  3524. }
  3525. };
  3526. return new Promise((resolve) => {
  3527. checkInit(function(e) {
  3528. resolve(e)
  3529. });
  3530. })
  3531. }
  3532. }
  3533.  
  3534. pageAction(doc, eles) {
  3535. let code = this.curSiteRule.pageAction;
  3536. if (code) {
  3537. try {
  3538. ((typeof code == 'function') ? code : Function("doc", "eles", '"use strict";' + code))(doc, eles);
  3539. } catch(e) {
  3540. debug(e);
  3541. }
  3542. }
  3543. this.openInNewTab(eles);
  3544. this.replaceElement(doc);
  3545. }
  3546.  
  3547. openInNewTab(eles) {
  3548. if (openInNewTab) {
  3549. [].forEach.call(eles, ele => {
  3550. if (compareNodeName(ele, ["a"]) && ele.href && !/^(mailto:|javascript:)|#/.test(ele.href)) {
  3551. ele.setAttribute('target', openInNewTab == 1 ? '_blank' : '_self');
  3552. } else {
  3553. [].forEach.call(ele.querySelectorAll('a[href]:not([href^="mailto:"]):not([href^="javascript:"]):not([href^="#"])'), a => {
  3554. if (openInNewTab == 1) {
  3555. a.setAttribute('target', '_blank');
  3556. if (a.getAttribute('onclick') == 'atarget(this)') {
  3557. a.removeAttribute('onclick');
  3558. }
  3559. } else a.setAttribute('target', '_self');
  3560. });
  3561. }
  3562. });
  3563. }
  3564. }
  3565.  
  3566. lazyImgAction(eles, doc) {
  3567. if (!eles || eles.length == 0) return;
  3568. let lazyImgSrc = this.curSiteRule.lazyImgSrc;
  3569. if (lazyImgSrc === 0 || lazyImgSrc === '0') return;
  3570. let imgLazyAttrs = [];
  3571. 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"];
  3572. let removeProps = [];
  3573. let setLazyImg = img => {
  3574. let realSrc;
  3575. imgLazyAttrs.forEach(attr => {
  3576. realSrc = img.getAttribute(lazyImgSrc[0]);
  3577. if (realSrc) {
  3578. removeProps.forEach(prop => {
  3579. img.removeAttribute(prop.trim());
  3580. });
  3581. img.src = realSrc;
  3582. return;
  3583. }
  3584. })
  3585. if (!realSrc) {
  3586. let lazyAttr = "";
  3587. if (img.getAttribute("_src") && !img.src) {
  3588. lazyAttr = "_src";
  3589. realSrc = img.getAttribute(lazyAttr);
  3590. } else {
  3591. for (let i in lazyImgAttr) {
  3592. lazyAttr = lazyImgAttr[i];
  3593. let attrValue = img.getAttribute(lazyAttr);
  3594. if (attrValue) {
  3595. realSrc = attrValue;
  3596. break;
  3597. }
  3598. }
  3599. }
  3600. if (!realSrc && img._lazyrias && img._lazyrias.srcset) {
  3601. realSrc = img._lazyrias.srcset[img._lazyrias.srcset.length - 1];
  3602. lazyAttr = "_lazyrias";
  3603. }
  3604. if (!realSrc && img.srcset) {
  3605. lazyAttr = "srcset";
  3606. var srcs = img.srcset.split(/[xw],/i), largeSize = 0;
  3607. srcs.forEach(srci => {
  3608. let srcInfo = srci.trim().split(" "), curSize = parseInt(srcInfo[1]);
  3609. if (srcInfo[1] && curSize > largeSize) {
  3610. largeSize = curSize;
  3611. realSrc = srcInfo[0];
  3612. }
  3613. });
  3614. }
  3615. if (realSrc) {
  3616. img.src = realSrc;
  3617. img.removeAttribute("srcset");
  3618. img.removeAttribute(lazyAttr);
  3619. if (img.classList && img.classList.contains && img.classList.contains("lazy")) {
  3620. img.classList.remove("lazy");
  3621. }
  3622. if (img.style.display == "none") {
  3623. img.style.display = "";
  3624. }
  3625. if (img.style.visibility == "hidden") {
  3626. img.style.visibility = "";
  3627. }
  3628. if (img.style.opacity == 0) {
  3629. img.style.opacity = "";
  3630. }
  3631. }
  3632. }
  3633. };
  3634. if (lazyImgSrc) {
  3635. if (!Array.isArray(lazyImgSrc)) {
  3636. lazyAttrs = lazyImgSrc.split(",");
  3637. } else {
  3638. lazyAttrs = lazyImgSrc[0].split(",");
  3639. removeProps = lazyImgSrc[1].split(",");
  3640. }
  3641. }
  3642. lazyAttrs.forEach(attr => {
  3643. let attrArr = attr.split("|");
  3644. if (attrArr.length !== 2) {
  3645. imgLazyAttrs.push(attr.trim());
  3646. } else {
  3647. let selector = attrArr[0].trim();
  3648. let lazyAttr = attrArr[1].trim();
  3649. if (selector == "img") {
  3650. imgLazyAttrs.push(lazyAttr);
  3651. } else {
  3652. selector += "[" + lazyAttr + "]";
  3653. [].forEach.call(doc.querySelectorAll(selector), ele => {
  3654. ele.style.setProperty("background-image", "url(" + ele.getAttribute(lazyAttr) + ")", "important");
  3655. removeProps.forEach(prop => {
  3656. ele.removeAttribute(prop.trim());
  3657. });
  3658. });
  3659. }
  3660. }
  3661. });
  3662. [].forEach.call(doc.querySelectorAll("img,picture>source"), img => {
  3663. setLazyImg(img);
  3664. });
  3665. }
  3666.  
  3667. canListenUrlChange() {
  3668. if (this.curSiteRule) {
  3669. if (this.curSiteRule.listenUrlChange === true) return true;
  3670. if (this.curSiteRule.listenUrlChange === false) return false;
  3671. if (this.docElementValid()) {
  3672. return false;
  3673. }
  3674. }
  3675. return true;
  3676. }
  3677.  
  3678. docElementValid() {
  3679. return (this.docPageElement && document.documentElement.contains(this.docPageElement[0]));
  3680. }
  3681.  
  3682. urlChanged() {
  3683. urlChanged = true;
  3684. this.clearAddedElements();
  3685. }
  3686.  
  3687. initPage(callback) {
  3688. let self = this;
  3689. if (self.initing) return;
  3690. self.initing = true;
  3691. setTimeout(() => {
  3692. self.initing = false;
  3693. }, 100);
  3694. curPage = 1;
  3695. urlChanged = false;
  3696. tryTimes = 0;
  3697. this.clearAddedElements();
  3698. this.insert = null;
  3699. this.visibilityItems = [];
  3700. this.visibleIndex = -1;
  3701. this.pageDoc = document;
  3702. this.nextLinkHref = null;
  3703. this.curUrl = location.href;
  3704. this.oldUrl = "";
  3705. this.initUrl = location.href;
  3706. this.historyUrl = "";
  3707. this.possibleCheck = 0;
  3708. let base = document.querySelector("base");
  3709. this.basePath = base ? base.href : location.href;
  3710. this.getRule(async () => {
  3711. if (self.curSiteRule.sideController === true || (self.curSiteRule.sideController !== false && rulesData.sideController)) {
  3712. isPause = manualPause;
  3713. }
  3714. if (typeof(self.curSiteRule.rate) !== "undefined") {
  3715. rate = self.curSiteRule.rate;
  3716. }
  3717. if (self.curSiteRule.enable == 0) {
  3718. debug("Stop as rule disable");
  3719. isPause = true;
  3720. _GM_registerMenuCommand(i18n("enable"), () => {
  3721. showTips(i18n("enableSiteTips"));
  3722. if(!self.customRules) {
  3723. self.customRules = [];
  3724. }
  3725. for (let i in self.customRules) {
  3726. if (self.customRules[i].url == self.curSiteRule.url) {
  3727. self.customRules.splice(i, 1);
  3728. break;
  3729. }
  3730. }
  3731. self.curSiteRule.enable = 1;
  3732. self.customRules.unshift(self.curSiteRule);
  3733. storage.setItem("customRules", self.customRules);
  3734. location.reload();
  3735. });
  3736. return;
  3737. }
  3738. if (rulesData.sideControllerAlways) {
  3739. sideController.setup();
  3740. }
  3741. //若是再亂匹配就不緩存wedata,或者只在找完本地規則之後再考慮wedata的緩存
  3742. if (self.curSiteRule.smart) {
  3743. delete self.curSiteRule.pageElement;
  3744. if (!self.possibleRule) {
  3745. self.smartRules = self.smartRules.filter(item => {return item && item.url != self.curSiteRule.url});
  3746. self.smartRules.unshift(self.curSiteRule);
  3747. if (self.smartRules.length > 100) {
  3748. self.smartRules.pop();
  3749. }
  3750. storage.setItem("smartRules", self.smartRules);
  3751. }
  3752. } else if (self.curSiteRule && self.curSiteRule.url.length > 13) {
  3753. self.addToHpRules();
  3754. }
  3755. let css = self.curSiteRule.css || rulesData.customCss;
  3756. if (css) {
  3757. let cssArr = css.split("inIframe:");
  3758. if (cssArr && cssArr.length) {
  3759. _GM_addStyle(cssArr[0]);
  3760. }
  3761. }
  3762. if (/sidesearch=(1|true)$/.test(self.curUrl)) {
  3763. openInNewTab = 0;
  3764. } else if (typeof self.curSiteRule.openInNewTab !== 'undefined') {
  3765. openInNewTab = self.curSiteRule.openInNewTab ? 1 : 2;
  3766. }
  3767. let autoClick = self.curSiteRule.autoClick;
  3768. if (autoClick) {
  3769. let autoClickBtn;
  3770. autoClickBtn = getElement(autoClick, document, null, true);
  3771. if (autoClickBtn) {
  3772. emuClick(autoClickBtn);
  3773. }
  3774. }
  3775. let code = self.curSiteRule.init;
  3776. if (code) {
  3777. try {
  3778. 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)});
  3779. } catch(e) {
  3780. debug(e);
  3781. }
  3782. }
  3783. await self.getNextLink(document, true);
  3784. if (self.curSiteRule.pageNum && self.nextLinkHref && self.nextLinkHref != "#") {
  3785. let num1st = self.getPageNumFromUrl(location.href, 1);
  3786. let num2nd = self.getPageNumFromUrl(self.nextLinkHref, 1);
  3787. if (num2nd != num1st + 1) {
  3788. self.curSiteRule.pageNum = null;
  3789. }
  3790. }
  3791. if (self.curSiteRule.smart && self.nextLinkHref == false && self.possibleRule) {
  3792. let urlReg = new RegExp(self.possibleRule.url, "i");
  3793. function checkPossible () {
  3794. if (self.possibleCheck++ < 3) {
  3795. setTimeout(() => {
  3796. if (self.curSiteRule.smart) {
  3797. var href = location.href.slice(0, 500);
  3798. if (urlReg.test(href) && self.ruleMatch(self.possibleRule)) {
  3799. self.initPage(() => {});
  3800. } else checkPossible();
  3801. }
  3802. }, 3000);
  3803. }
  3804. }
  3805. checkPossible();
  3806. }
  3807. self.refreshByClick();
  3808. if (emuIframe && emuIframe.parentNode) {
  3809. emuIframe.parentNode.removeChild(emuIframe);
  3810. emuIframe = null;
  3811. }
  3812.  
  3813. let pageElementCss = self.curSiteRule.pageElementCss || rulesData.pageElementCss;
  3814. if (pageElementCss && pageElementCss !== '0') {
  3815. self.getPageElement(document, _unsafeWindow);
  3816. }
  3817. callback();
  3818. let initRun = typeof self.curSiteRule.initRun == 'undefined' ? rulesData.initRun : self.curSiteRule.initRun;
  3819. if (self.nextLinkHref) {
  3820. sideController.setup();
  3821. if (initRun && initRun != false) {
  3822. setTimeout(() => {
  3823. nextPage();
  3824. }, 300);
  3825. }
  3826. }
  3827. });
  3828. }
  3829.  
  3830. async hookUrlSetEle(ele, doc) {
  3831. let self = this;
  3832. return new Promise((resolve) => {
  3833. let catchUrl = e => {
  3834. ele.dataset.url = self.catchedUrl;
  3835. ele.setAttribute('onclick', 'window.open(this.dataset.url)');
  3836. window.removeEventListener('pagetual_openUrl', catchUrl);
  3837. resolve();
  3838. };
  3839. window.addEventListener('pagetual_openUrl', catchUrl);
  3840. emuClick(ele, doc);
  3841. });
  3842. }
  3843.  
  3844. async hookUrl(doc) {
  3845. let sel = this.curSiteRule.hookUrl;
  3846. if (!sel) return;
  3847. let self = this;
  3848. if (!this.initHook) {
  3849. this.initHook = true;
  3850. Object.defineProperty(doc.defaultView, 'open', {
  3851. get: function () {
  3852. return (s) => {
  3853. self.catchedUrl = s;
  3854. var e = new CustomEvent('pagetual_openUrl');
  3855. window.dispatchEvent(e);
  3856. }
  3857. }
  3858. });
  3859. }
  3860. let eles = getAllElements(sel, doc);
  3861. for (let i = 0; i < eles.length; i++) {
  3862. await sleep(1);
  3863. let ele = eles[i];
  3864. if (!ele.dataset.url) {
  3865. await this.hookUrlSetEle(ele, doc);
  3866. }
  3867. }
  3868. }
  3869.  
  3870. beginLoading() {
  3871. isLoading = true;
  3872. if (targetY >= 0) {
  3873. window.scrollTo({ top: targetY, behavior: 'instant'});
  3874. targetY = -1;
  3875. }
  3876. let lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3877. ruleParser.insertElement(loadingDiv);
  3878. if (forceState == 2) {
  3879. getBody(document).appendChild(loadingDiv);
  3880. } else {
  3881. let parent = loadingDiv.parentNode;
  3882. if (compareNodeName(parent, ["tbody"])) {
  3883. parent = parent.parentNode;
  3884. }
  3885. if (compareNodeName(parent, ["table"])) {
  3886. parent.parentNode.appendChild(loadingDiv);
  3887. }
  3888. }
  3889. getBody(document).scrollTop = lastScrollTop;
  3890. document.documentElement.scrollTop = lastScrollTop;
  3891. }
  3892.  
  3893. insertElement(ele) {
  3894. if (!this.insert || !this.insert.parentNode) {
  3895. this.getInsert();
  3896. }
  3897. if (this.insert && this.insert.parentNode) {
  3898. let self = this;
  3899. if (ele.nodeName == "#document-fragment") {
  3900. [].forEach.call(ele.children, el => {
  3901. self.addedElePool.push(el);
  3902. });
  3903. } else {
  3904. this.addedElePool.push(ele);
  3905. }
  3906. if (this.curSiteRule.insertPos == 2 || this.curSiteRule.insertPos == "in") {
  3907. this.insert.appendChild(ele);
  3908. } else {
  3909. this.insert.parentNode.insertBefore(ele, this.insert);
  3910. }
  3911. }
  3912. }
  3913.  
  3914. noValidContent(url) {
  3915. if (!this.curSiteRule.nextLinkByUrl) showTips(i18n("noValidContent"), url);
  3916. }
  3917.  
  3918. async insertPage(doc, eles, url, callback, tried) {
  3919. this.oldUrl = this.curUrl;
  3920. let oldTitle = document.title;
  3921. try {
  3922. let oldTitle = this.pageDoc.title;
  3923. } catch (e) {}
  3924. this.pageDoc = doc;
  3925. this.curUrl = url;
  3926. isLoading = true;
  3927. let nextLink = await this.getNextLink(doc);
  3928. this.nextTitle = "";
  3929. if (this.curSiteRule.pageBarText) {
  3930. if (this.curSiteRule.pageBarText == 1 || this.curSiteRule.pageBarText == true) {
  3931. this.nextTitle = doc.title;
  3932. } else {
  3933. try {
  3934. this.nextTitle = ((typeof this.curSiteRule.pageBarText == 'function') ? this.curSiteRule.pageBarText : Function("doc",'"use strict";' + this.curSiteRule.pageBarText))(doc);
  3935. } catch(e) {
  3936. debug(e);
  3937. }
  3938. }
  3939. }
  3940. if (curPage == 1 && !tried && !nextLink && this.curSiteRule.smart && this.curSiteRule.pageElement && this.curSiteRule.action != 0) {
  3941. this.curSiteRule.action = 1;
  3942. this.curUrl = location.href;
  3943. isLoading = false;
  3944. return false;
  3945. }
  3946.  
  3947. if (targetY >= 0) {
  3948. window.scrollTo({ top: targetY, behavior: 'instant'});
  3949. targetY = -1;
  3950. }
  3951. let lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3952. this.getInsert();
  3953. await this.pageInit(doc, eles);
  3954. var self = this, newEles = [];
  3955. if (!eles || eles.length == 0 || !self.insert || !self.insert.parentNode) {
  3956. if (callback) callback(eles);
  3957. loadPageOver();
  3958. } else {
  3959. if (callback) callback(eles);
  3960. loadPageOver();
  3961. const collection = document.createDocumentFragment();
  3962. [].forEach.call(eles, ele => {
  3963. let newEle = ele.cloneNode(true);
  3964. let oldCanvass = ele.querySelectorAll("canvas");
  3965. let newCanvass = newEle.querySelectorAll("canvas");
  3966. if (self.updateUrl) {
  3967. [].forEach.call(newEle.querySelectorAll("img"), img => {
  3968. if (img.getAttribute("src")) img.src = self.canonicalUri(img.getAttribute("src"));
  3969. });
  3970. [].forEach.call(newEle.querySelectorAll("a"), a => {
  3971. if (a.getAttribute("href")) a.href = self.canonicalUri(a.getAttribute("href"));
  3972. });
  3973. }
  3974. for (let i = 0; i < oldCanvass.length; i++) {
  3975. let oldCanvas = oldCanvass[i];
  3976. let newCanvas = newCanvass[i];
  3977. newCanvas.getContext('2d').drawImage(oldCanvas, 0, 0);
  3978. }
  3979. if (!compareNodeName(newEle, ["style", "script"])) self.visibilityItems.push(newEle);
  3980. collection.appendChild(newEle)
  3981. newEles.push(newEle);
  3982. });
  3983. self.insertElement(collection);
  3984. }
  3985. getBody(document).scrollTop = lastScrollTop;
  3986. document.documentElement.scrollTop = lastScrollTop;
  3987. this.pageAction(doc, newEles);
  3988. let enableHistory = this.curSiteRule.history;
  3989. let enableHistoryAfterInsert = false;
  3990. if (enableHistory == 1) {
  3991. enableHistory = true;
  3992. } else if (enableHistory == 2) {
  3993. enableHistory = true;
  3994. enableHistoryAfterInsert = true;
  3995. } else if (enableHistory == 0) {
  3996. enableHistory = false;
  3997. } else {
  3998. enableHistory = rulesData.enableHistory;
  3999. enableHistoryAfterInsert = rulesData.enableHistoryAfterInsert;
  4000. }
  4001. if (enableHistory) {
  4002. this.historyUrl = enableHistoryAfterInsert ? this.curUrl : this.oldUrl;
  4003. if(this.historyUrl != location.href) {
  4004. let isJs = this.hrefIsJs(this.historyUrl);
  4005. if (!isJs) {
  4006. let historyTitle = enableHistoryAfterInsert ? doc.title : oldTitle;
  4007. _unsafeWindow.history.replaceState(undefined, historyTitle, this.historyUrl);
  4008. document.title = historyTitle;
  4009. }
  4010. }
  4011. }
  4012. isLoading = false;
  4013. _unsafeWindow.postMessage({
  4014. action: "insert",
  4015. command: 'pagetual'
  4016. }, '*');
  4017. return true;
  4018. }
  4019. }
  4020. var ruleParser = new RuleParser();
  4021.  
  4022. class SideController {
  4023. //static controller;
  4024. constructor() {
  4025. this.inited = false;
  4026. }
  4027.  
  4028. /*static getInstance() {
  4029. if (!SideController.controller) {
  4030. SideController.controller = new SideController();
  4031. }
  4032. return SideController.controller;
  4033. }*/
  4034.  
  4035. setup() {
  4036. if (ruleParser.curSiteRule.sideController === false) return;
  4037. if (!rulesData.sideController && !ruleParser.curSiteRule.sideController) return;
  4038. this.addToStage();
  4039. }
  4040.  
  4041. init() {
  4042. if (this.inited) return;
  4043. this.inited = true;
  4044. let self = this;
  4045. this.cssText = `
  4046. #pagetual-sideController {
  4047. position: fixed;
  4048. top: calc(50% - 83px);
  4049. left: calc(99% - 40px);
  4050. width: 40px;
  4051. border-radius: 20px;
  4052. box-shadow: rgb(0 0 0) 0px 0px 10px;
  4053. text-align: center;
  4054. background: #ffffffd0!important;
  4055. user-select: none;
  4056. z-index: 2147483646!important;
  4057. padding: 0!important;
  4058. opacity: 0.35;
  4059. transition: opacity .5s ease, background .5s, box-shadow .5s;
  4060. }
  4061. #pagetual-sideController * {
  4062. font-weight: bold;
  4063. font-family: arial;
  4064. font-style: normal;
  4065. font-size: 20px!important;
  4066. color: black!important;
  4067. line-height: normal;
  4068. float: none;
  4069. text-align: center;
  4070. }
  4071. #pagetual-sideController.stop {
  4072. -webkit-filter: invert(100%);
  4073. filter: invert(100%);
  4074. }
  4075. .pagetual-sideController-btn {
  4076. padding: 5px 0;
  4077. cursor: pointer;
  4078. transition: transform .15s ease-in-out, opacity .3s ease;
  4079. }
  4080. #pagetual-sideController .pagetual-sideController-btn:hover {
  4081. transform: scale(1.5);
  4082. color: red!important;
  4083. }
  4084. #pagetual-sideController #pagetual-sideController-move > svg {
  4085. transition: transform .3s ease;
  4086. }
  4087. #pagetual-sideController #pagetual-sideController-move > svg:hover {
  4088. transform: scale(1.2);
  4089. }
  4090. #pagetual-sideController.minSize #pagetual-sideController-move > svg {
  4091. background: white;
  4092. opacity: 0;
  4093. }
  4094. #pagetual-sideController #pagetual-sideController-move > img,
  4095. #pagetual-sideController #pagetual-sideController-move > span {
  4096. width: 35px;
  4097. height: 35px;
  4098. cursor: pointer;
  4099. }
  4100. #pagetual-sideController.minSize #pagetual-sideController-move > img,
  4101. #pagetual-sideController.minSize #pagetual-sideController-move > span {
  4102. border-radius: 50px;
  4103. text-shadow: rgb(255 255 255) 0px 0px 10px;
  4104. }
  4105. #pagetual-sideController #pagetual-sideController-pagenum {
  4106. font-size: 15px!important;
  4107. line-height: 30px;
  4108. text-align: center;
  4109. position: absolute;
  4110. right: calc(50% - 15px);
  4111. top: calc(50% - 15px);
  4112. border: 1px solid #00000099;
  4113. display: inline-block;
  4114. width: 30px;
  4115. height: 30px;
  4116. box-sizing: border-box;
  4117. border-radius: 50%;
  4118. background: white;
  4119. opacity: 0;
  4120. transition: opacity .5s ease;
  4121. pointer-events: none;
  4122. }
  4123. #pagetual-sideController.minSize #pagetual-sideController-pagenum {
  4124. opacity: 0.8;
  4125. }
  4126. #pagetual-sideController:hover {
  4127. opacity: 1;
  4128. }
  4129. #pagetual-sideController>.extra {
  4130. bottom: 170px;
  4131. left: 0px;
  4132. width: 40px;
  4133. position: absolute;
  4134. }
  4135. #pagetual-sideController>.extra>svg {
  4136. width: 40px;
  4137. height: 30px;
  4138. opacity: 0.1;
  4139. cursor: pointer;
  4140. margin: 0 0 5px 0;
  4141. transition: opacity .3s ease;
  4142. }
  4143. #pagetual-sideController.minSize>.extra>svg {
  4144. opacity: 0;
  4145. }
  4146. #pagetual-sideController>.extra>svg:hover {
  4147. opacity: 1;
  4148. }
  4149. #pagetual-sideController.minSize {
  4150. box-shadow: rgb(0 0 0 / 0%) 0px 0px 0px;
  4151. background: #00000000!important;
  4152. pointer-events: none;
  4153. }
  4154. #pagetual-sideController.minSize #pagetual-sideController-move {
  4155. pointer-events: all;
  4156. }
  4157. #pagetual-sideController.minSize .pagetual-sideController-btn {
  4158. opacity: 0;
  4159. }
  4160. `;
  4161. let frame = document.createElement("div");
  4162. frame.id = "pagetual-sideController";
  4163. frame.innerHTML = createHTML(`
  4164. <div class="extra">
  4165. <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>
  4166. <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>
  4167. </div>
  4168. <div id="pagetual-sideController-top" class="pagetual-sideController-btn">⊼</div>
  4169. <div>
  4170. <div id="pagetual-sideController-pre" class="pagetual-sideController-btn">∧</div>
  4171. <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>
  4172. <div id="pagetual-sideController-next" class="pagetual-sideController-btn">∨</div>
  4173. </div>
  4174. <div id="pagetual-sideController-bottom" class="pagetual-sideController-btn">⊻</div>
  4175. `);
  4176. frame.classList.add("stop");
  4177. let top = frame.querySelector("#pagetual-sideController-top");
  4178. let pre = frame.querySelector("#pagetual-sideController-pre");
  4179. let move = frame.querySelector("#pagetual-sideController-move");
  4180. let next = frame.querySelector("#pagetual-sideController-next");
  4181. let bottom = frame.querySelector("#pagetual-sideController-bottom");
  4182. let pagenum = frame.querySelector("#pagetual-sideController-pagenum");
  4183. let scroll = frame.querySelector("#scroll");
  4184. let loadNow = frame.querySelector("#loadNow");
  4185. if (rulesData.sideControllerScroll === false) {
  4186. scroll.style.display = "none";
  4187. }
  4188. if (rulesData.sideControllerLoadNow === false) {
  4189. loadNow.style.display = "none";
  4190. }
  4191. if (sideControllerIcon) move.innerHTML = sideControllerIcon;
  4192.  
  4193. frame.addEventListener("dblclick", e => {
  4194. e.preventDefault();
  4195. e.stopPropagation();
  4196. });
  4197.  
  4198. frame.addEventListener("mouseenter", e => {
  4199. clearTimeout(self.hideTimer);
  4200. frame.classList.remove("minSize");
  4201. });
  4202.  
  4203. frame.addEventListener("mouseleave", e => {
  4204. clearTimeout(self.hideTimer);
  4205. self.hideTimer = setTimeout(() => {
  4206. frame.classList.add("minSize");
  4207. }, 800);
  4208. });
  4209.  
  4210. document.body.addEventListener('touchstart', e => {
  4211. if (e.target === frame || frame.contains(e.target)) {
  4212. frame.classList.remove("minSize");
  4213. } else {
  4214. frame.classList.add("minSize");
  4215. }
  4216. });
  4217.  
  4218. scroll.addEventListener("click", e => {
  4219. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  4220. autoScroll = parseInt(autoScroll) || 0;
  4221. if (autoScroll < 0) autoScroll = 0;
  4222. if (autoScroll && autoScroll != autoScrollRate) {
  4223. autoScrollRate = autoScroll;
  4224. storage.setItem("autoScrollRate", autoScrollRate);
  4225. }
  4226. setListData("autoScroll", location.host + location.pathname, autoScroll);
  4227. startAutoScroll();
  4228. }, true);
  4229.  
  4230. loadNow.addEventListener("click", e => {
  4231. if (autoLoadNum != -1) {
  4232. autoLoadNum = -1;
  4233. return;
  4234. }
  4235. let loadNum = window.prompt(i18n("loadConfirm"), loadNowNum);
  4236. if (loadNum === "" || loadNum === null) return;
  4237. loadNum = Math.abs(parseInt(loadNum)) || 0;
  4238. if (loadNowNum != loadNum) {
  4239. loadNowNum = loadNum;
  4240. storage.setItem("loadNowNum", loadNowNum);
  4241. }
  4242. autoLoadNum = loadNum;
  4243. nextPage();
  4244. }, true);
  4245.  
  4246. pre.addEventListener("click", e => {
  4247. let prePageBar = getPageBar().preBar;
  4248. if (prePageBar) {
  4249. scrollToPageBar(prePageBar);
  4250. } else {
  4251. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  4252. targetY = scrollTop - (window.innerHeight || document.documentElement.clientHeight);
  4253. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4254. }
  4255. }, true);
  4256.  
  4257. next.addEventListener("click", e => {
  4258. let pageBarObj = getPageBar();
  4259. let nextPageBar = pageBarObj.nextBar;
  4260. if (nextPageBar) {
  4261. scrollToPageBar(nextPageBar);
  4262. } else {
  4263. if (pageBarObj.preBar) {
  4264. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  4265. targetY = scrollH || 9999999;
  4266. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4267. } else {
  4268. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  4269. targetY = scrollTop + (window.innerHeight || document.documentElement.clientHeight);
  4270. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4271. }
  4272. }
  4273. }, true);
  4274.  
  4275. top.addEventListener("click", e => {
  4276. getBody(document).scrollTop=0;
  4277. document.documentElement.scrollTop=0;
  4278. e.preventDefault();
  4279. e.stopPropagation();
  4280. }, true);
  4281.  
  4282. bottom.addEventListener("click", e => {
  4283. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  4284. changeStop(true, true);
  4285. }
  4286. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  4287. getBody(document).scrollTop = scrollH || 9999999;
  4288. document.documentElement.scrollTop = scrollH || 9999999;
  4289. e.preventDefault();
  4290. e.stopPropagation();
  4291. }, true);
  4292.  
  4293. let initX, initY, moving = false;
  4294. let removeTimer;
  4295. move.addEventListener("click", e => {
  4296. if (!moving) {
  4297. changeStop(!isPause, true);
  4298. }
  4299. }, true);
  4300. move.addEventListener("dblclick", e => {
  4301. clearTimeout(removeTimer);
  4302. document.removeEventListener("mousemove", mouseMoveHandler, true);
  4303. document.removeEventListener("mouseup", mouseUpHandler, true);
  4304. changeStop(!isPause, true);
  4305. if (isPause) {
  4306. ruleParser.hideAddedElements();
  4307. } else {
  4308. ruleParser.showAddedElements();
  4309. }
  4310. }, true);
  4311.  
  4312. move.oncontextmenu = e => {
  4313. e.preventDefault();
  4314. picker.start();
  4315. };
  4316.  
  4317. let clientX = e => {
  4318. if (e.type.indexOf('mouse') === 0) {
  4319. return e.clientX;
  4320. } else {
  4321. return e.changedTouches[0].clientX;
  4322. }
  4323. };
  4324.  
  4325. let clientY = e => {
  4326. if (e.type.indexOf('mouse') === 0) {
  4327. return e.clientY;
  4328. } else {
  4329. return e.changedTouches[0].clientY;
  4330. }
  4331. };
  4332.  
  4333. let mouseMoveHandler = e => {
  4334. if (moving) {
  4335. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  4336. let windowWidth = window.innerWidth || document.documentElement.clientWidth;
  4337. initX = (clientX(e) - 10 + 40) / windowWidth * 100;
  4338. initY = (clientY(e) - 83 + 83) / windowHeight * 100;
  4339. this.frame.style.top = `calc(${initY}% - 83px)`;
  4340. this.frame.style.left = `calc(${initX}% - 40px)`;
  4341. } else if (Math.abs(clientX(e) - initX) + Math.abs(clientY(e) - initY) > 20) {
  4342. moving = true;
  4343. clearTimeout(removeTimer);
  4344. }
  4345. };
  4346. let mouseUpHandler = e => {
  4347. clearTimeout(removeTimer);
  4348. document.removeEventListener("mousemove", mouseMoveHandler, true);
  4349. document.removeEventListener("mouseup", mouseUpHandler, true);
  4350. document.removeEventListener("touchmove", mouseMoveHandler, true);
  4351. document.removeEventListener("touchend", mouseUpHandler, true);
  4352. if (moving) {
  4353. rulesData.sideControllerPos = {x: parseInt(initX), y: parseInt(initY)};
  4354. storage.setItem("rulesData", rulesData);
  4355. }
  4356. };
  4357. let mouseDownHandler = e => {
  4358. initX = clientX(e);
  4359. initY = clientY(e);
  4360. moving = false;
  4361. clearTimeout(removeTimer);
  4362. removeTimer = setTimeout(() => {
  4363. if (e.type === "touchstart") {
  4364. picker.start();
  4365. } else {
  4366. self.remove();
  4367. }
  4368. }, 1500);
  4369. document.addEventListener("mousemove", mouseMoveHandler, true);
  4370. document.addEventListener("mouseup", mouseUpHandler, true);
  4371. document.addEventListener("touchmove", mouseMoveHandler, true);
  4372. document.addEventListener("touchend", mouseUpHandler, true);
  4373. e.stopPropagation();
  4374. e.preventDefault();
  4375. };
  4376.  
  4377. move.addEventListener("mousedown", mouseDownHandler, true);
  4378. move.addEventListener("touchstart", mouseDownHandler, { passive: false, capture: true });
  4379.  
  4380. this.frame = frame;
  4381. this.pagenum = pagenum;
  4382. if (rulesData.sideControllerPos) {
  4383. this.frame.style.top = `calc(${rulesData.sideControllerPos.y}% - 83px)`;
  4384. this.frame.style.left = `calc(${rulesData.sideControllerPos.x}% - 40px)`;
  4385. }
  4386. }
  4387.  
  4388. addToStage() {
  4389. this.init();
  4390. if (!this.styleEle || !this.styleEle.parentNode) {
  4391. this.styleEle = _GM_addStyle(this.cssText);
  4392. }
  4393. if (!isPause) {
  4394. this.frame.classList.remove("stop");
  4395. }
  4396. this.pagenum.innerHTML = createHTML(curPage);
  4397. this.frame.title = i18n("page") + curPage;
  4398. if (this.frame.parentNode) return;
  4399. getBody(document).appendChild(this.frame);
  4400. clearTimeout(this.hideTimer);
  4401. this.frame.classList.add("minSize");
  4402. }
  4403.  
  4404. remove() {
  4405. if (this.frame && this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  4406. }
  4407. }
  4408. const sideController = new SideController();
  4409.  
  4410. class NextSwitch {
  4411. //static nextSwitch;
  4412. constructor() {
  4413. this.inited = false;
  4414. }
  4415.  
  4416. /*static getInstance() {
  4417. if (!NextSwitch.nextSwitch) {
  4418. NextSwitch.nextSwitch = new NextSwitch();
  4419. }
  4420. return NextSwitch.nextSwitch;
  4421. }*/
  4422.  
  4423. init() {
  4424. if (this.inited) return;
  4425. this.inited = true;
  4426. let self = this;
  4427. this.cssText = `
  4428. #pagetual-nextSwitch {
  4429. position: fixed;
  4430. top: 10px;
  4431. left: calc(50% - 160px);
  4432. background: aliceblue;
  4433. padding: 10px;
  4434. border-radius: 5px;
  4435. text-align: center;
  4436. opacity: 0.95;
  4437. color: #161616;
  4438. z-index: 2147483647;
  4439. font-size: 16px;
  4440. box-shadow: rgb(0 0 0) 0px 0px 10px;
  4441. }
  4442. #pagetual-nextSwitch>.title {
  4443. margin: -5px 45px 10px 45px;
  4444. font-size: 20px;
  4445. font-weight: bold;
  4446. border-bottom: 1px solid black;
  4447. user-select: none;
  4448. color: orangered;
  4449. }
  4450. #pagetual-nextSwitch>.group {
  4451. display: flex;
  4452. flex-direction: column;
  4453. }
  4454. #pagetual-nextSwitch>.group>span {
  4455. color: #161616;
  4456. cursor: pointer;
  4457. margin: 3px;
  4458. font-size: larger;
  4459. }
  4460. #pagetual-nextSwitch>.group>span:hover {
  4461. color: red;
  4462. }
  4463. #pagetual-nextSwitch>.group>span.current {
  4464. border: 2px dotted red;
  4465. border-radius: 10px;
  4466. }
  4467. #pagetual-nextSwitch>.closeSwitch {
  4468. position: absolute;
  4469. top: 3px;
  4470. right: 10px;
  4471. background: none;
  4472. border: none;
  4473. vertical-align: top;
  4474. transition: transform .15s ease-in-out;
  4475. float: right;
  4476. cursor: pointer;
  4477. }
  4478. #pagetual-nextSwitch svg {
  4479. width: 30px;
  4480. height: 30px;
  4481. vertical-align: middle;
  4482. fill: #161616;
  4483. overflow: hidden;
  4484. }
  4485. #pagetual-nextSwitch button:hover {
  4486. transform: scale(1.2);
  4487. }
  4488. `;
  4489. let frame = document.createElement("div");
  4490. frame.id = "pagetual-nextSwitch";
  4491. frame.innerHTML = createHTML(`
  4492. <div class="title">${i18n("nextSwitch")}</div>
  4493. <button type="button" class="closeSwitch">
  4494. <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2754">
  4495. <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">
  4496. </path>
  4497. </svg>
  4498. </button>
  4499. <div class="group"></div>
  4500. `);
  4501. let group = frame.querySelector(".group");
  4502. let closeBtn = frame.querySelector(".closeSwitch");
  4503. closeBtn.addEventListener("click", e => {
  4504. self.close();
  4505. }, true);
  4506. this.frame = frame;
  4507. let currentSpan;
  4508. ruleParser.curSiteRule.nextLink.forEach((link, i) => {
  4509. let span = document.createElement("span");
  4510. let target = getElement(link, document);
  4511. let index = "<b>" + (i + 1) + "</b>: ";
  4512. if (target) {
  4513. let targetInner = target.innerText.trim();
  4514. span.innerHTML = index + (targetInner || link);
  4515. } else {
  4516. span.innerHTML = index + "Not Found";
  4517. }
  4518. span.title = link;
  4519. span.addEventListener("click", e => {
  4520. if (currentSpan) currentSpan.classList.remove("current");
  4521. span.classList.add("current");
  4522. currentSpan = span;
  4523. nextIndex = i;
  4524. setListData("nextSwitch", location.host, nextIndex === 0 ? "" : nextIndex);
  4525. ruleParser.curUrl += "#pagetual";
  4526. ruleParser.oldUrl = ruleParser.curUrl;
  4527. autoLoadNum = -1;
  4528. if (!ruleParser.nextLinkHref) {
  4529. isLoading = false;
  4530. }
  4531. ruleParser.getNextLink(ruleParser.pageDoc || document);
  4532. self.close();
  4533. }, true);
  4534. if (i == nextIndex) {
  4535. span.classList.add("current");
  4536. currentSpan = span;
  4537. }
  4538. group.appendChild(span);
  4539. });
  4540. }
  4541.  
  4542. start() {
  4543. this.init();
  4544. if (!this.styleEle || !this.styleEle.parentNode) {
  4545. this.styleEle = _GM_addStyle(this.cssText);
  4546. }
  4547. document.documentElement.appendChild(this.frame);
  4548. }
  4549.  
  4550. close() {
  4551. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  4552. }
  4553. }
  4554. const nextSwitch = new NextSwitch();
  4555.  
  4556. class Picker {
  4557. //static picker;
  4558. constructor() {
  4559. this.inited = false;
  4560. }
  4561.  
  4562. /*static getInstance() {
  4563. if (!Picker.picker) {
  4564. Picker.picker = new Picker();
  4565. }
  4566. return Picker.picker;
  4567. }*/
  4568.  
  4569. init() {
  4570. if (this.inited) return;
  4571. this.inited = true;
  4572. let self = this;
  4573. this.signList = [];
  4574. this.cssText = `
  4575. body.pagetual-picker,
  4576. body.pagetual-picker *:hover,
  4577. body.pagetual-picker a:hover {
  4578. cursor: crosshair !important;
  4579. }
  4580. #pagetual-picker {
  4581. position: fixed;
  4582. top: 10px;
  4583. left: calc(50% - 178px);
  4584. background: aliceblue;
  4585. padding: 10px;
  4586. border-radius: 5px;
  4587. text-align: center;
  4588. opacity: 0.95;
  4589. color: #161616;
  4590. z-index: 2147483646;
  4591. font-size: 16px;
  4592. overflow: hidden;
  4593. box-shadow: rgb(0 0 0) 0px 0px 10px;
  4594. }
  4595. #pagetual-picker * {
  4596. margin: 0;
  4597. padding: 0;
  4598. font-family: Times New Roman;
  4599. overflow: initial;
  4600. user-select: none;
  4601. line-height: unset;
  4602. min-width: unset;
  4603. min-height: unset;
  4604. }
  4605. #pagetual-picker>.title {
  4606. margin: -5px 45px 10px 45px;
  4607. font-size: 20px;
  4608. font-weight: bold;
  4609. cursor: pointer;
  4610. border-bottom: 1px solid black;
  4611. user-select: none;
  4612. color: orangered;
  4613. height: initial;
  4614. width: initial;
  4615. position: initial;
  4616. transition: transform .3s ease;
  4617. }
  4618. #pagetual-picker>.title:hover {
  4619. transform: scale(1.1);
  4620. }
  4621. #pagetual-picker button {
  4622. background: none;
  4623. border: none;
  4624. vertical-align: top;
  4625. transition: transform .15s ease-in-out;
  4626. float: right;
  4627. cursor: pointer;
  4628. overflow: hidden;
  4629. background-color: unset!important;
  4630. }
  4631. #pagetual-picker button:hover {
  4632. transform: scale(1.2);
  4633. }
  4634. #pagetual-picker>.closePicker {
  4635. position: absolute;
  4636. top: 3px;
  4637. right: 10px;
  4638. }
  4639. #pagetual-picker>.logoIcon {
  4640. position: absolute;
  4641. top: 3px;
  4642. left: 10px;
  4643. }
  4644. #pagetual-picker>.logoIcon.showSign>svg>path {
  4645. fill: gray!important;
  4646. }
  4647. #pagetual-picker textarea{
  4648. display: inline-block;
  4649. width: calc(100% - 65px);
  4650. height: 20px;
  4651. min-width: 250px;
  4652. max-width: calc(65vw - 50px);
  4653. min-height: unset;
  4654. max-height: unset;
  4655. padding: 6px 12px;
  4656. font-size: 16px;
  4657. font-weight: 400;
  4658. line-height: 1.5;
  4659. color: #495057;
  4660. background-color: #fff;
  4661. background-clip: padding-box;
  4662. border: 1px solid #ced4da;
  4663. border-radius: 4px;
  4664. transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
  4665. box-sizing: content-box;
  4666. margin-right: 5px;
  4667. resize: both;
  4668. box-shadow: 0 1px 5px 1px #ddd;
  4669. overflow-wrap: anywhere;
  4670. }
  4671. #pagetual-picker textarea:focus {
  4672. color: black;
  4673. background-color: #fff;
  4674. border-color: #80bdff;
  4675. outline: 0;
  4676. box-shadow: 0 0 0 3.2px rgb(0 123 255 / 25%);
  4677. }
  4678. #pagetual-picker [type=checkbox],
  4679. #pagetual-picker [type=radio] {
  4680. line-height: 20px;
  4681. height: 25px;
  4682. width: 25px;
  4683. margin-left: 5px;
  4684. vertical-align: middle;
  4685. appearance: auto;
  4686. display: inline-block;
  4687. position: initial;
  4688. }
  4689. #pagetual-picker [type=checkbox]:after,
  4690. #pagetual-picker [type=radio]:after,
  4691. #pagetual-picker [type=checkbox]:before,
  4692. #pagetual-picker [type=radio]:before {
  4693. border: none;
  4694. background: none;
  4695. }
  4696. #pagetual-picker label {
  4697. font-size: 18px;
  4698. line-height: 25px;
  4699. vertical-align: middle;
  4700. display: inline-block;
  4701. color: black;
  4702. position: initial;
  4703. cursor: pointer;
  4704. }
  4705. #pagetual-picker .bottom {
  4706. text-align: left;
  4707. margin: 10px 0;
  4708. width: 100%;
  4709. }
  4710. #pagetual-picker .bottom>button {
  4711. float: right;
  4712. }
  4713. #pagetual-picker svg {
  4714. width: 30px;
  4715. height: 30px;
  4716. vertical-align: middle;
  4717. fill: #161616;
  4718. overflow: hidden;
  4719. }
  4720. #pagetual-picker svg * {
  4721. pointer-events: none;
  4722. }
  4723. #pagetual-picker .allpath {
  4724. font-size: 18px;
  4725. margin: 10px auto;
  4726. max-width: 330px;
  4727. word-break: break-all;
  4728. cursor: context-menu;
  4729. overflow: hidden;
  4730. max-height: 42px;
  4731. -moz-transition:max-height 1s ease-in;
  4732. -webkit-transition:max-height 1s ease-in;
  4733. transition:max-height 1s ease-in;
  4734. color: black;
  4735. }
  4736. #pagetual-picker .allpath:hover {
  4737. max-height: calc(100vh - 130px);
  4738. overflow: auto;
  4739. }
  4740. #pagetual-picker .allpath>span.path {
  4741. cursor: pointer;
  4742. }
  4743. #pagetual-picker .allpath>span.path:hover {
  4744. opacity: 0.6;
  4745. }
  4746. #pagetual-picker .allpath>span.path:hover,
  4747. #pagetual-picker .allpath>span.path.checked {
  4748. color: orangered;
  4749. }
  4750. #pagetual-picker .moreConfig {
  4751. display: flex;
  4752. justify-content: space-between;
  4753. border-top: 1px solid;
  4754. padding-top: 10px;
  4755. width: 100%;
  4756. }
  4757. #pagetual-picker .command {
  4758. width: 100%;
  4759. color: black!important;
  4760. text-align: center;
  4761. font-size: large;
  4762. margin-top: 10px;
  4763. box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.12);
  4764. border-radius: 5px;
  4765. }
  4766. #pagetual-picker .command:hover {
  4767. color: orangered;
  4768. }
  4769. #pagetual-picker #showDetail {
  4770. float: initial;
  4771. margin-top: 10px;
  4772. }
  4773. #pagetual-picker.showDetail #showDetail {
  4774. float: right;
  4775. }
  4776. #pagetual-picker #showDetail>svg {
  4777. -moz-transition:transform 0.3s ease;
  4778. -webkit-transition:transform 0.3s ease;
  4779. transition:transform 0.3 ease;
  4780. }
  4781. #pagetual-picker.showDetail #showDetail>svg {
  4782. transform: rotate(180deg);
  4783. }
  4784. #pagetual-picker .tempRule {
  4785. display: none;
  4786. margin-top: 10px;
  4787. height: 300px;
  4788. min-height: 150px;
  4789. }
  4790. #pagetual-picker.showDetail .tempRule {
  4791. display: inline-block;
  4792. word-break: break-all;
  4793. }
  4794. #pagetual-picker #saveDetail {
  4795. display: none;
  4796. position: absolute;
  4797. bottom: 10px;
  4798. right: 8px;
  4799. }
  4800. #pagetual-picker.showDetail #saveDetail {
  4801. display: inline-block;
  4802. }
  4803. #pagetual-picker #saveDetail svg {
  4804. width: 35px;
  4805. height: 35px;
  4806. }
  4807. #pagetual-picker .addProp {
  4808. display: none;
  4809. flex-direction: column;
  4810. position: absolute;
  4811. bottom: 45px;
  4812. right: 12px;
  4813. }
  4814. #pagetual-picker.showDetail .addProp {
  4815. display: flex;
  4816. }
  4817. #pagetual-picker .addProp>button {
  4818. font-size: 30px;
  4819. font-family: Arial,sans-serif;
  4820. line-height: 35px;
  4821. color: #161616;
  4822. }
  4823. #pagetual-picker #edit{
  4824. -webkit-animation: jumpAnimation .6s 5;
  4825. animation: jumpAnimation .6s 5;
  4826. }
  4827. @keyframes jumpAnimation {
  4828. 0% {
  4829. transform: scale(1) translateY(0);
  4830. animation-timing-function: ease-out;
  4831. }
  4832. 50% {
  4833. transform: scale(1.2) translateY(-5px);
  4834. animation-timing-function: ease-in;
  4835. }
  4836. 100% {
  4837. transform: scale(1) translateY(0);
  4838. animation-timing-function: ease-out;
  4839. }
  4840. }
  4841. @-webkit-keyframes jumpAnimation {
  4842. 0% {
  4843. -webkit-transform: scale(1) translateY(0);
  4844. animation-timing-function: ease-out;
  4845. }
  4846. 50% {
  4847. -webkit-transform: scale(1.2) translateY(-5px);
  4848. animation-timing-function: ease-in;
  4849. }
  4850. 100% {
  4851. -webkit-transform: scale(1) translateY(0);
  4852. animation-timing-function: ease-out;
  4853. }
  4854. }
  4855. `;
  4856. this.mainSignDiv = this.createSignDiv();
  4857. this.allSignDiv = [];
  4858. let frame = document.createElement("div");
  4859. frame.id = "pagetual-picker";
  4860. frame.innerHTML = createHTML(`
  4861. <button title="Pagetual" type="button" class="logoIcon">
  4862. <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>
  4863. </button>
  4864. <div class="title" title="${i18n("configure")}">${i18n("picker")}</div>
  4865. <button title="${i18n("closePicker")}" type="button" class="closePicker">
  4866. <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>
  4867. </button>
  4868. <div class="allpath" title="${i18n("switchSelector")}"></div>
  4869. <div>
  4870. <textarea class="selector" spellcheck="false" name="selector" placeholder="${i18n("pickerPlaceholder")}"></textarea>
  4871. <button id="check" title="${i18n("pickerCheck")}" type="button">
  4872. <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>
  4873. </button>
  4874. </div>
  4875. <div class="bottom">
  4876. <input name="xpath" id="checkbox_id" type="checkbox" />
  4877. <label for="checkbox_id">XPath</label>
  4878. <button id="edit" title="${i18n("gotoEdit")}" type="button">
  4879. <svg viewBox="0 0 1024 1024" style="color: orangered;fill: orangered;" version="1.1" xmlns="http://www.w3.org/2000/svg">
  4880. <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">
  4881. </path>
  4882. </svg>
  4883. </button>
  4884. </div>
  4885. <div class="moreConfig">
  4886. <div title="${i18n('forceStateIframe')}">
  4887. <input name="forceState" id="forceStateIframe" type="radio" />
  4888. <label for="forceStateIframe">${i18n('iframe')}</label>
  4889. </div>
  4890. <div title="${i18n('forceStateDynamic')}">
  4891. <input name="forceState" id="forceStateDynamic" type="radio" />
  4892. <label for="forceStateDynamic">${i18n('dynamic')}</label>
  4893. </div>
  4894. <div title="${i18n('forceStateDisable')}">
  4895. <input name="forceState" id="forceStateDisable" type="radio" />
  4896. <label for="forceStateDisable">${i18n('disable')}</label>
  4897. </div>
  4898. </div>
  4899. <button id="nextSwitch" class="command" title="${i18n("nextSwitch")}" type="button">${i18n("nextSwitch")}</button>
  4900. <button id="loadNow" class="command" title="${i18n("loadNow")}" type="button">${i18n("loadNow")}</button>
  4901. <button id="autoScroll" class="command" title="${i18n("toggleAutoScroll")}" type="button"></button>
  4902. <button id="ruleRequest" class="command" title="${i18n("ruleRequest")}" type="button">${i18n("ruleRequest")}</button>
  4903. <div>
  4904. <textarea class="tempRule" spellcheck="false" placeholder="{Rule object}" title="Rule for current site"></textarea>
  4905. <button id="showDetail" title="" type="button">
  4906. <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>
  4907. </button>
  4908. <div class="addProp">
  4909. <button id="addOtherProp" title="${i18n("addOtherProp")}" type="button">+</button>
  4910. <button id="addNextSelector" title="${i18n("addNextSelector")}" type="button">></button>
  4911. <button id="addPageSelector" title="${i18n("addPageSelector")}" type="button">❏</button>
  4912. </div>
  4913. <button id="saveDetail" title="${i18n("save")}" type="button">
  4914. <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>
  4915. </button>
  4916. </div>
  4917. `);
  4918. let forceStateIframe = frame.querySelector("#forceStateIframe");//forceState 1 禁用 2 强嵌 3 动态
  4919. let forceStateDynamic = frame.querySelector("#forceStateDynamic");
  4920. let forceStateDisable = frame.querySelector("#forceStateDisable");
  4921. let clickRadio = e => {
  4922. let radio = e.currentTarget.querySelector('input');
  4923. if (radio.checked) {
  4924. forceState = "";
  4925. } else {
  4926. switch (radio.id) {
  4927. case "forceStateIframe":
  4928. forceState = 2;
  4929. break;
  4930. case "forceStateDynamic":
  4931. forceState = 3;
  4932. break;
  4933. case "forceStateDisable":
  4934. forceState = 1;
  4935. break;
  4936. default:
  4937. return;
  4938. }
  4939. }
  4940. setListData("forceState", location.host, forceState);
  4941. self.close();
  4942. setTimeout(() => {
  4943. location.reload();
  4944. }, 500);
  4945. };
  4946. forceStateIframe.parentNode.addEventListener("mousedown", clickRadio);
  4947. forceStateDynamic.parentNode.addEventListener("mousedown", clickRadio);
  4948. forceStateDisable.parentNode.addEventListener("mousedown", clickRadio);
  4949. if (forceState == 1) forceStateDisable.checked = true;
  4950. else if (forceState == 2) forceStateIframe.checked = true;
  4951. else if (forceState == 3) forceStateDynamic.checked = true;
  4952. let closeBtn = frame.querySelector(".closePicker");
  4953. let logoBtn = frame.querySelector(".logoIcon");
  4954. let title = frame.querySelector(".title");
  4955. let allpath = frame.querySelector(".allpath");
  4956. let selectorInput = frame.querySelector(".selector");
  4957. let xpath = frame.querySelector("#checkbox_id");
  4958. let checkBtn = frame.querySelector("#check");
  4959. let editBtn = frame.querySelector("#edit");
  4960. let nextSwitchBtn = frame.querySelector("#nextSwitch");
  4961. let autoScrollBtn = frame.querySelector("#autoScroll");
  4962. let loadNow = frame.querySelector("#loadNow");
  4963. let tempRule = frame.querySelector(".tempRule");
  4964. let showDetailBtn = frame.querySelector("#showDetail");
  4965. let saveDetailBtn = frame.querySelector("#saveDetail");
  4966. let addOtherProp = frame.querySelector("#addOtherProp");
  4967. let addNextSelector = frame.querySelector("#addNextSelector");
  4968. let addPageSelector = frame.querySelector("#addPageSelector");
  4969. let ruleRequestBtn = frame.querySelector("#ruleRequest");
  4970. ruleRequestBtn.addEventListener("click", e => {
  4971. _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});
  4972. }, true);
  4973. autoScrollBtn.addEventListener("click", e => {
  4974. self.close();
  4975. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  4976. autoScroll = parseInt(autoScroll) || 0;
  4977. if (autoScroll < 0) autoScroll = 0;
  4978. if (autoScroll && autoScroll != autoScrollRate) {
  4979. autoScrollRate = autoScroll;
  4980. storage.setItem("autoScrollRate", autoScrollRate);
  4981. }
  4982. setListData("autoScroll", location.host + location.pathname, autoScroll);
  4983. startAutoScroll();
  4984. }, true);
  4985. addOtherProp.addEventListener("click", e => {
  4986. let propName = prompt(i18n("propName"), "author");
  4987. if (!propName) return;
  4988. let propValue = prompt(i18n("propValue"));
  4989. if (!propValue) return;
  4990. if (propValue === "true") propValue = true;
  4991. else if (propValue === "false") propValue = false;
  4992. else if (/^\d+$/.test(propValue)) propValue = parseInt(propValue);
  4993. if (propName === "author" && propValue) {
  4994. author = propValue;
  4995. storage.setItem("author", propValue);
  4996. }
  4997. let editTemp = self.getTempRule();
  4998. if (!editTemp) return;
  4999. editTemp[propName] = propValue;
  5000. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  5001. }, true);
  5002. addNextSelector.addEventListener("click", e => {
  5003. let editTemp = self.getTempRule();
  5004. if (!editTemp) return;
  5005. let selector = self.selectorInput.value;
  5006. if (selector) {
  5007. editTemp.nextLink = selector;
  5008. }
  5009. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  5010. }, true);
  5011. addPageSelector.addEventListener("click", e => {
  5012. let editTemp = self.getTempRule();
  5013. if (!editTemp) return;
  5014. let selector = self.selectorInput.value;
  5015. if (selector) {
  5016. editTemp.pageElement = selector;
  5017. }
  5018. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  5019. }, true);
  5020. showDetailBtn.addEventListener("click", e => {
  5021. frame.classList.toggle("showDetail");
  5022. }, true);
  5023. saveDetailBtn.addEventListener("click", e => {
  5024. let editTemp = self.getTempRule(true);
  5025. if (tempRule.value && !editTemp) {
  5026. return;
  5027. }
  5028. if(!ruleParser.customRules) {
  5029. ruleParser.customRules = [];
  5030. }
  5031. ruleParser.customRules = ruleParser.customRules.filter(item => {return item.url != editTemp.url || item.name != editTemp.name});
  5032. if (tempRule.value) {
  5033. ruleParser.customRules.unshift(editTemp);
  5034. ruleParser.curSiteRule = editTemp;
  5035. } else {
  5036. ruleParser.curSiteRule = {};
  5037. isPause = true;
  5038. }
  5039. storage.setItem("customRules", ruleParser.customRules);
  5040. if (ruleParser.hpRules && ruleParser.curSiteRule && !ruleParser.curSiteRule.smart) {
  5041. ruleParser.addToHpRules(true);
  5042. }
  5043. if (window.confirm(i18n("reloadPage"))) {
  5044. setTimeout(() => {location.reload()}, 100);
  5045. }
  5046. }, true);
  5047. nextSwitchBtn.addEventListener("click", e => {
  5048. self.close();
  5049. nextSwitch.start();
  5050. }, true);
  5051. loadNow.addEventListener("click", e => {
  5052. self.close();
  5053. let loadNum = window.prompt(i18n("loadConfirm"), "1");
  5054. if (loadNum === "" || loadNum === null) return;
  5055. autoLoadNum = Math.abs(parseInt(loadNum));
  5056. nextPage();
  5057. }, true);
  5058. closeBtn.addEventListener("click", e => {
  5059. self.close();
  5060. }, true);
  5061. this.showSign = true;
  5062. logoBtn.addEventListener("click", e => {
  5063. logoBtn.classList.toggle("showSign");
  5064. self.showSign = !self.showSign;
  5065. getBody(document).classList.toggle("pagetual-picker");
  5066. }, true);
  5067. let moving = false;
  5068. let initX = 0, initY = 0, initPos = {x: 0, y: 0};
  5069. let moveHanlder = e => {
  5070. if (moving) {
  5071. frame.style.left = e.clientX - initX + "px";
  5072. frame.style.top = e.clientY - initY + "px";
  5073. e.stopPropagation();
  5074. e.preventDefault();
  5075. } else if(Math.abs(e.clientX - initPos.x) + Math.abs(e.clientY - initPos.y) > 20) {
  5076. moving = true;
  5077. }
  5078. };
  5079. let upHanlder = e => {
  5080. if (moving) {
  5081. moving = false;
  5082. } else {
  5083. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  5084. }
  5085. document.removeEventListener("mousemove", moveHanlder, true);
  5086. title.removeEventListener("mouseup", upHanlder, true);
  5087. e.stopPropagation();
  5088. e.preventDefault();
  5089. };
  5090. title.addEventListener("mousedown", e => {
  5091. initPos = {x: e.clientX, y: e.clientY};
  5092. initX = e.clientX - parseInt(getComputedStyle(frame).left);
  5093. initY = e.clientY - parseInt(getComputedStyle(frame).top);
  5094. document.addEventListener("mousemove", moveHanlder, true);
  5095. title.addEventListener("mouseup", upHanlder, true);
  5096. });
  5097. frame.addEventListener("mouseenter", e => {
  5098. if (!self.showSign || moving) return;
  5099. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  5100. self.checkInputSelector(false);
  5101. });
  5102. frame.addEventListener("mouseleave", e => {
  5103. if (!self.showSign) {
  5104. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  5105. self.clearSigns();
  5106. return;
  5107. }
  5108. if (moving) return;
  5109. document.documentElement.appendChild(self.mainSignDiv);
  5110. self.clearSigns();
  5111. });
  5112. checkBtn.addEventListener("click", e => {
  5113. self.checkInputSelector();
  5114. if (this.selectorInput.value && self.foundEle) {
  5115. debug(self.foundEle);
  5116. self.foundEle[0].scrollIntoView({ behavior: "smooth" });
  5117. _GM_setClipboard(this.selectorInput.value);
  5118. showTips(i18n("copied"));
  5119. } else showTips("Null");
  5120. });
  5121. xpath.addEventListener("click", e => {
  5122. if (!selectorInput.value) {
  5123. self.setSelectorDiv("");
  5124. return;
  5125. }
  5126. let element = getElement(selectorInput.value, document);
  5127. let selector = self.getSelectorFromEle(element);
  5128. selectorInput.value = selector;
  5129. self.setSelectorDiv(selector);
  5130. });
  5131. editBtn.addEventListener("click", e => {
  5132. rulesData.editTemp = self.getTempRule();
  5133. storage.setItem("rulesData", rulesData);
  5134. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  5135. });
  5136. editBtn.oncontextmenu = e => {
  5137. e.preventDefault();
  5138. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  5139. };
  5140. this.frame = frame;
  5141. this.xpath = xpath;
  5142. this.allpath = allpath;
  5143. this.selectorInput = selectorInput;
  5144. this.nextSwitchBtn = nextSwitchBtn;
  5145. this.autoScrollBtn = autoScrollBtn;
  5146. this.loadNow = loadNow;
  5147. this.tempRule = tempRule;
  5148. this.logoBtn = logoBtn;
  5149. let setTitleTimer;
  5150. this.moveHandler = e => {
  5151. if (!self.showSign || e.target === document) return;
  5152. let target = self.getTarget(e.target);
  5153. self.adjustSignDiv(self.mainSignDiv, target);
  5154. clearTimeout(setTitleTimer);
  5155. setTitleTimer = setTimeout(() => {
  5156. if (self.inPicker && target.hasAttributes()) {
  5157. let title = target.nodeName.toLowerCase() + "\n";
  5158. for (const attr of target.attributes) {
  5159. title += `【${attr.name}】${attr.value ? " ➡️ " + attr.value : ""}\n`;
  5160. }
  5161. getBody(document).title = title;
  5162. }
  5163. }, 100);
  5164. };
  5165. this.clickHandler = e => {
  5166. if (!self.showSign) return;
  5167. if (self.inPicker) {
  5168. e.stopPropagation();
  5169. e.preventDefault();
  5170. }
  5171. let target = self.getTarget(e.target);
  5172. let selector = self.getSelectorFromEle(target);
  5173. selectorInput.value = selector;
  5174. self.setSelectorDiv(selector);
  5175. };
  5176. }
  5177.  
  5178. getTempRule(detail) {
  5179. if (this.tempRule.value) {
  5180. try {
  5181. this.editTemp = JSON.parse(this.tempRule.value);
  5182. } catch (e) {
  5183. this.editTemp = null;
  5184. if (detail) {
  5185. let pos = e && e.message && e.message.match(/position (\d+)/);
  5186. if (pos) {
  5187. pos = parseInt(pos[1]);
  5188. this.tempRule.value = this.tempRule.value.slice(0, pos) + "➡️" + this.tempRule.value.slice(pos);
  5189. }
  5190. showTips(i18n("errorJson"));
  5191. return null;
  5192. }
  5193. }
  5194. }
  5195. if (!this.editTemp) {
  5196. if (ruleParser.curSiteRule.url && !ruleParser.curSiteRule.smart) {
  5197. this.editTemp = ruleParser.curSiteRule;
  5198. } else {
  5199. this.editTemp = {
  5200. name: document.title,
  5201. url: "^" + (location.origin + location.pathname).replace(/[^\/]*$/, "").replace(/^https?/, "https?").replace(/\./g, "\\."),
  5202. example: location.href
  5203. };
  5204. if (author) this.editTemp.author = author;
  5205. }
  5206. delete this.editTemp.from;
  5207. delete this.editTemp.type;
  5208. delete this.editTemp.updatedAt;
  5209. }
  5210. if (this.selectorInput.value && (!this.frame.classList.contains("showDetail") || !this.editTemp || !this.editTemp.pageElement)) {
  5211. if (this.foundEle && this.foundEle.length === 1) {
  5212. let foundEleRect = this.foundEle[0].getBoundingClientRect();
  5213. if (foundEleRect.height < 100) {
  5214. showTips("Next Link", "", 500);
  5215. this.editTemp.nextLink = this.selectorInput.value;
  5216. return this.editTemp;
  5217. }
  5218. }
  5219. showTips("Page Element", "", 500);
  5220. this.editTemp.pageElement = this.selectorInput.value;
  5221. }
  5222. return this.editTemp;
  5223. }
  5224.  
  5225. getTarget(ele) {
  5226. while (ele.parentNode && (ele.offsetWidth === 0 || ele.offsetHeight === 0)) {
  5227. ele = ele.parentNode;
  5228. }
  5229. return ele;
  5230. }
  5231.  
  5232. close() {
  5233. this.clearSigns();
  5234. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  5235. if (this.mainSignDiv.parentNode) this.mainSignDiv.parentNode.removeChild(this.mainSignDiv);
  5236. getBody(document).classList.remove("pagetual-picker");
  5237. getBody(document).removeEventListener("mousemove", this.moveHandler, true);
  5238. getBody(document).removeEventListener("click", this.clickHandler, true);
  5239. getBody(document).title = "";
  5240. this.inPicker = false;
  5241. }
  5242.  
  5243. setImportant(ele, prop, value) {
  5244. ele.style.setProperty(prop, value, "important");
  5245. }
  5246.  
  5247. createSignDiv() {
  5248. let signDiv = document.createElement("div");
  5249. this.setImportant(signDiv, "position", "absolute");
  5250. this.setImportant(signDiv, "pointer-events", "none");
  5251. this.setImportant(signDiv, "z-index", "2147483645");
  5252. this.setImportant(signDiv, "background", "rgba(120, 170, 210, 0.6)");
  5253. this.setImportant(signDiv, "transition", "all 0.15s ease-out");
  5254. this.setImportant(signDiv, "box-shadow", "rgb(0 0 0) 0px 0px 3px 0px");
  5255. return signDiv;
  5256. }
  5257.  
  5258. adjustSignDiv(div, target) {
  5259. let rect = target.getBoundingClientRect();
  5260. this.setImportant(div, "width", rect.width + "px");
  5261. this.setImportant(div, "height", rect.height + "px");
  5262. this.setImportant(div, "left", rect.left + window.scrollX + "px");
  5263. this.setImportant(div, "top", rect.top + window.scrollY + "px");
  5264. }
  5265.  
  5266. getSelectorFromEle(ele) {
  5267. return this.xpath.checked ? createXPathFromElement(ele) : geneSelector(ele, true);
  5268. }
  5269.  
  5270. fillTempRuleTextarea() {
  5271. if (!this.frame.classList.contains("showDetail") || !this.editTemp || !this.editTemp.pageElement) this.tempRule.value = JSON.stringify(this.getTempRule(), null, 4);
  5272. }
  5273.  
  5274. setSelectorDiv(selector) {
  5275. let self = this;
  5276. this.allpath.innerHTML = createHTML("");
  5277. if (selector) {
  5278. if (this.xpath.checked) {
  5279. let span = document.createElement("span");
  5280. span.innerText = selector;
  5281. span.addEventListener("click", e => {
  5282. self.selectorInput.value = selector;
  5283. self.checkInputSelector();
  5284. }, true);
  5285. this.allpath.appendChild(span);
  5286. } else {
  5287. selector.split(">").forEach((item, index) => self.geneSelectorItem(item, index));
  5288. }
  5289. }
  5290. this.checkInputSelector();
  5291. }
  5292.  
  5293. geneSelectorItem(item, index) {
  5294. let self = this;
  5295. item = item.trim();
  5296. if (!item) return;
  5297. if (index !== 0) {
  5298. let span = document.createElement("span");
  5299. span.innerText = " > ";
  5300. this.allpath.appendChild(span);
  5301. }
  5302. let span = document.createElement("span");
  5303. span.className = "path";
  5304. span.innerText = item;
  5305. span.addEventListener("click", e => {
  5306. let selector = "";
  5307. let target = e.target;
  5308. while (target) {
  5309. selector = target.innerText + selector;
  5310. target = target.previousElementSibling;
  5311. }
  5312. self.selectorInput.value = selector;
  5313. self.checkInputSelector();
  5314. if (self.checkedPath) {
  5315. self.checkedPath.classList.remove("checked");
  5316. }
  5317. span.classList.add("checked");
  5318. self.checkedPath = span;
  5319. }, true);
  5320. this.allpath.appendChild(span);
  5321. }
  5322.  
  5323. checkInputSelector(fill = true) {
  5324. let self = this;
  5325. this.clearSigns();
  5326. if (!this.selectorInput.value) return;
  5327. let eles = getAllElements(this.selectorInput.value, document);
  5328. this.foundEle = null;
  5329. if (eles && eles.length > 0) {
  5330. this.foundEle = eles;
  5331. eles.forEach(ele => {
  5332. let sign = self.createSignDiv();
  5333. document.documentElement.appendChild(sign);
  5334. self.adjustSignDiv(sign, ele);
  5335. self.signList.push(sign);
  5336. });
  5337. if (fill) this.fillTempRuleTextarea();
  5338. }
  5339. }
  5340.  
  5341. clearSigns() {
  5342. this.signList.forEach(sign => {
  5343. if (sign.parentNode) sign.parentNode.removeChild(sign);
  5344. });
  5345. this.signList = [];
  5346. }
  5347.  
  5348. start() {
  5349. this.init();
  5350. if (this.inPicker) return;
  5351. this.inPicker = true;
  5352. if (!this.styleEle || !this.styleEle.parentNode) {
  5353. this.styleEle = _GM_addStyle(this.cssText);
  5354. }
  5355. document.documentElement.appendChild(this.frame);
  5356. document.documentElement.appendChild(this.mainSignDiv);
  5357. getBody(document).classList.add("pagetual-picker");
  5358.  
  5359. this.logoBtn.classList.remove("showSign");
  5360. this.showSign = true;
  5361.  
  5362. getBody(document).addEventListener("mousemove", this.moveHandler, true);
  5363. getBody(document).addEventListener("click", this.clickHandler, true);
  5364. this.xpath.checked = isXPath(ruleParser.curSiteRule.pageElement);
  5365. this.tempRule.value = "";
  5366. this.editTemp = null;
  5367. this.frame.classList.remove("showDetail");
  5368.  
  5369. this.loadNow.style.display = ruleParser.nextLinkHref ? "block" : "none";
  5370. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  5371. this.nextSwitchBtn.style.display = "block";
  5372. } else {
  5373. this.nextSwitchBtn.style.display = "none";
  5374. }
  5375. this.autoScrollBtn.innerText = i18n(autoScroll ? "disableAutoScroll" : "enableAutoScroll");
  5376.  
  5377. let pageElementSel = ruleParser.curSiteRule.pageElement || "";
  5378. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  5379. pageElementSel = pageElementSel[nextIndex < pageElementSel.length ? nextIndex : 0];
  5380. }
  5381. this.setSelectorDiv(pageElementSel);
  5382. this.fillTempRuleTextarea();
  5383. }
  5384. }
  5385. const picker = new Picker();
  5386.  
  5387. var editor, editorChanged = false, customRulesInput;
  5388. function createEdit() {
  5389. var options = {
  5390. mode: 'code',
  5391. modes: ['code', 'tree'],
  5392. templates: [
  5393. {
  5394. text: 'New site',
  5395. title: 'Insert a new site',
  5396. className: 'jsoneditor-type-object',
  5397. field: 'SiteTemplate',
  5398. value: {
  5399. 'name': 'Site name',
  5400. 'url': 'Site url'
  5401. }
  5402. }
  5403. ],
  5404. schema: {
  5405. "title": "Sites data",
  5406. "description": "Object containing site config",
  5407. "type": "array",
  5408. "items": {
  5409. "type": 'object',
  5410. "properties": {
  5411. "name": {
  5412. "title": "Site Name",
  5413. "description": "The site's name.",
  5414. "examples": [
  5415. "Google"
  5416. ],
  5417. "type": "string"
  5418. },
  5419. "url": {
  5420. "title": "Site Url",
  5421. "description": "The Regexp of site's url.",
  5422. "examples": [
  5423. "^https:\/\/yande\\.re\/"
  5424. ],
  5425. "type": "string"
  5426. }
  5427. },
  5428. "required": ["name", "url"]
  5429. }
  5430. },
  5431. onChange: () => {
  5432. editorChanged = true;
  5433. }
  5434. };
  5435. setTimeout(() => {
  5436. var container = document.getElementById("jsoneditor");
  5437. container.style.height = '800px';
  5438. container.innerHTML = "";
  5439. try {
  5440. editor = new _unsafeWindow.JSONEditor(container, options);
  5441. editor.set(ruleParser.customRules);
  5442. } catch (e) {
  5443. editor = null;
  5444. container.style.display = 'none';
  5445. customRulesInput.style.display = "";
  5446. }
  5447. }, 500);
  5448. }
  5449.  
  5450. function checkGuidePage(href) {
  5451. if (guidePage.test(href)) {
  5452. if (typeof _unsafeWindow.JSONEditor !== 'undefined') {
  5453. createEdit();
  5454. } else {
  5455. let timeout = 30;
  5456. let checkEditorReady = setInterval(() => {
  5457. if (typeof _unsafeWindow.JSONEditor !== 'undefined') {
  5458. createEdit();
  5459. clearInterval(checkEditorReady);
  5460. } else if (timeout-- <= 0) {
  5461. editor = null;
  5462. customRulesInput.style.display = "";
  5463. clearInterval(checkEditorReady);
  5464. }
  5465. }, 100);
  5466. }
  5467. return true;
  5468. }
  5469. return false;
  5470. }
  5471.  
  5472. function startAutoScroll() {
  5473. clearInterval(autoScrollInterval);
  5474. if (autoScroll <= 0) return;
  5475. let scrollRange_o = 1;
  5476. if (autoScroll > 1000) {
  5477. scrollRange_o = parseInt(autoScroll / 1000);
  5478. }
  5479. let devicePixelRatio = window.devicePixelRatio;
  5480. let scrollRange = Math.ceil(scrollRange_o / devicePixelRatio);
  5481.  
  5482. let scrollTarget, body = getBody(document);
  5483. let checkOverflow = ele => {
  5484. return ele.scrollHeight !== ele.clientHeight && getComputedStyle(ele).overflowY !== "hidden";
  5485. };
  5486. if (document.documentElement.scrollTop || checkOverflow(document.documentElement)) {
  5487. scrollTarget = document.documentElement;
  5488. } else if (body.scrollTop || checkOverflow(body)) {
  5489. scrollTarget = body;
  5490. } else {
  5491. let tempEle;
  5492. let img = body.querySelector('img');
  5493. if (img) {
  5494. tempEle = img;
  5495. while (tempEle && !checkOverflow(tempEle)) {
  5496. tempEle = tempEle.parentNode;
  5497. }
  5498. }
  5499. if (!tempEle && document.activeElement) {
  5500. let tempEle = document.activeElement;
  5501. while (tempEle && !checkOverflow(tempEle)) {
  5502. tempEle = tempEle.parentNode;
  5503. }
  5504. }
  5505. if (tempEle) scrollTarget = tempEle;
  5506. }
  5507. scrollTarget = scrollTarget || document.documentElement;
  5508.  
  5509. autoScrollInterval = setInterval(() => {
  5510. if (isPause) return;
  5511. if (devicePixelRatio !== window.devicePixelRatio) {
  5512. devicePixelRatio = window.devicePixelRatio;
  5513. scrollRange = Math.ceil(scrollRange_o / devicePixelRatio);
  5514. }
  5515. scrollTarget.scrollTop += scrollRange;
  5516. }, parseInt(1000 / autoScroll));
  5517. }
  5518.  
  5519. var inUpdate = false;
  5520. var importHandler, configCon;
  5521. function initConfig(href) {
  5522. if (location.hostname === "github.com") {
  5523. 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) {
  5524. let issue_body = document.getElementById("issue_body");
  5525. if (!issue_body) return true;
  5526. issue_body.value = issue_body.value.replace("\n", "\n" + location.hash.slice(1) + "\n");
  5527. let starButton = document.createElement("a");
  5528. starButton.href = "https://github.com/hoothin/UserScripts#star";
  5529. starButton.className = "js-toggler-target rounded-left-2 btn-with-aria-count btn-sm btn";
  5530. 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>');
  5531. starButton.style.float = "right";
  5532. document.querySelector(".Layout-main>h2").appendChild(starButton);
  5533. return true;
  5534. } else if (location.href === "https://github.com/hoothin/UserScripts#star") {
  5535. let starButton = document.querySelector(".starring-container:not(.on)>.unstarred>form>button");
  5536. if (starButton) emuClick(starButton);
  5537. return true;
  5538. }
  5539. }
  5540. let isGuidePage = checkGuidePage(href);
  5541. if (!isGuidePage) {
  5542. if (href.indexOf("PagetualGuide") != -1) return true;
  5543. if (location.hostname === "pagetual.hoothin.com") return true;
  5544. }
  5545.  
  5546. var click2import, importUrlPres;
  5547.  
  5548. let inConfig = isGuidePage;
  5549. if (!inConfig) {
  5550. for (let i = 0; i < configPage.length; i++) {
  5551. if (configPage[i] == location.href) {
  5552. inConfig = true;
  5553. break;
  5554. }
  5555. }
  5556. }
  5557. configCon = document.getElementById("configCon");
  5558. if (configCon) {
  5559. configCon.parentNode.removeChild(configCon);
  5560. }
  5561. if (ruleImportUrlReg.test(href) || inConfig) {
  5562. let importing = false;
  5563. if (!inUpdate && rulesData.uninited) {
  5564. setTimeout(() => {
  5565. if (!inUpdate && !importing) showTips(i18n("firstAlert"));
  5566. }, 3000);
  5567. showTips(i18n("firstAlert"));
  5568. }
  5569. let defaultOption = document.querySelector('#discussion_rating_4');
  5570. if (defaultOption) defaultOption.checked = true;
  5571. let createImportBtn = (pre) => {
  5572. let importBtn = document.createElement("button");
  5573. importBtn.id = "pagetualImport";
  5574. importBtn.innerText = i18n("import");
  5575. importBtn.style.marginTop = "100px";
  5576. importBtn.style.float = "right";
  5577. importBtn.style.position = "relative";
  5578. importBtn.style.display = "block";
  5579. importBtn.style.fontSize = "20px";
  5580. importBtn.addEventListener("click", e => {
  5581. let parentNode = importBtn.parentNode;
  5582. if (!parentNode) return;
  5583. parentNode.removeChild(importBtn);
  5584. try {
  5585. let rules = parentNode.innerText.trim();
  5586. let isContent = /['"]name['"]/i.test(rules);
  5587. if (isContent) {
  5588. let ruleList = JSON.parse(`[${rules}]`);
  5589. for (let i in ruleList) {
  5590. let hasRule = false;
  5591. let r = ruleList[i];
  5592. for (let j in ruleParser.customRules) {
  5593. if (ruleParser.customRules[j].name == r.name) {
  5594. ruleParser.customRules[j] = r;
  5595. hasRule = true;
  5596. break;
  5597. }
  5598. }
  5599. if (!hasRule) ruleParser.customRules.push(r);
  5600. ruleParser.hpRules.unshift(r);
  5601. }
  5602. storage.setItem("customRules", ruleParser.customRules);
  5603. storage.setItem("hpRules", ruleParser.hpRules);
  5604. storage.setItem("smartRules", []);
  5605. showTips(i18n("importSucc"));
  5606. } else {
  5607. rules = rules.split("\n");
  5608. let diff = false;
  5609. for (let c = 0; c < rules.length; c++) {
  5610. let urlArr = rules[c].split("|"), url, type = 1;
  5611. if (urlArr.length == 1) {
  5612. url = urlArr[0].trim();
  5613. if (!/^http/.test(url)) {
  5614. showTips(i18n("errorWrongUrl"));
  5615. return;
  5616. }
  5617. } else if (urlArr.length == 2) {
  5618. type = urlArr[0].trim();
  5619. url = urlArr[1].trim();
  5620. if (!/^http/.test(url)) {
  5621. showTips(i18n("errorWrongUrl"));
  5622. return;
  5623. }
  5624. } else {
  5625. break;
  5626. }
  5627. let maxId = 1, hasUrl = false;
  5628. if (!rulesData.urls) {
  5629. rulesData.urls = [];
  5630. maxId = 1;
  5631. } else {
  5632. rulesData.urls.forEach(u => {
  5633. if (maxId < u.id) {
  5634. maxId = u.id;
  5635. }
  5636. if (u.url == url) {
  5637. hasUrl = true;
  5638. }
  5639. });
  5640. if (hasUrl) break;
  5641. }
  5642. diff = true;
  5643. if (!rulesData.sort) rulesData.sort = [1];
  5644. rulesData.urls.push({id: maxId + 1, url: url, type: type});
  5645. rulesData.sort.unshift(maxId + 1);
  5646. }
  5647. if (!diff) {
  5648. showTips(i18n("errorAlreadyExists"));
  5649. setTimeout(() => {
  5650. showTips(i18n("beginUpdate"), "", 50000);
  5651. updateRules(() => {
  5652. showTips(i18n("updateSucc"));
  5653. location.reload();
  5654. }, (rule, err) => {
  5655. showTips(`Failed to update ${rule.url} rules!`);
  5656. debug(err);
  5657. });
  5658. }, 500);
  5659. return;
  5660. }
  5661. storage.setItem("rulesData", rulesData);
  5662.  
  5663. if (rulesData.urls) ruleUrls = ruleUrls.concat(rulesData.urls);
  5664. if (rulesData.sort) {
  5665. let urls = [];
  5666. rulesData.sort.forEach(id => {
  5667. for (let s = 0; s < ruleUrls.length; s++) {
  5668. if (id == ruleUrls[s].id) {
  5669. urls.push(ruleUrls[s]);
  5670. break;
  5671. }
  5672. }
  5673. });
  5674. ruleUrls = urls;
  5675. }
  5676. showTips(i18n("beginUpdate"), "", 30000);
  5677. updateRules(() => {
  5678. showTips(i18n("updateSucc"));
  5679. location.reload();
  5680. }, (rule, err) => {
  5681. showTips(`Failed to update ${rule.url} rules!`);
  5682. debug(err);
  5683. });
  5684. importing = true;
  5685. }
  5686. } catch (e) {
  5687. _GM_notification(e.toString());
  5688. }
  5689. });
  5690. if (pre) {
  5691. let clientHeight = 35 - pre.clientHeight;
  5692. if (clientHeight > -20) clientHeight = -20;
  5693. importBtn.style.marginTop = `${clientHeight}px`;
  5694. pre.appendChild(importBtn);
  5695. }
  5696. return importBtn;
  5697. };
  5698. [].forEach.call(document.querySelectorAll('pre[name=pagetual],pre[name=user-content-pagetual]'), pre => {
  5699. let importBtn = createImportBtn(pre);
  5700. });
  5701. if (!importHandler) {
  5702. importHandler = e => {
  5703. if (compareNodeName(e.target, ["pre"])) {
  5704. let nameAttr = e.target.getAttribute("name");
  5705. if (nameAttr == "pagetual" || nameAttr == "user-content-pagetual") {
  5706. if (e.target.querySelector('#pagetualImport')) return;
  5707. let importBtn = createImportBtn(e.target);
  5708. }
  5709. }
  5710. };
  5711. }
  5712. document.removeEventListener("mouseover", importHandler);
  5713. document.addEventListener("mouseover", importHandler);
  5714.  
  5715. if (inConfig) {
  5716. if (!inUpdate && _GM_info.script && _GM_info.script.version && _GM_info.script.version !== '1.0.0') {
  5717. let versionEle = document.querySelector('.markdown-body>h1[id],article>h1');
  5718. let latestVer = versionEle && versionEle.innerText.match(/\d[\d\.]+/)[0];
  5719. if (latestVer && latestVer != _GM_info.script.version) {
  5720. showTips(i18n('outOfDate'), "", 3000);
  5721. }
  5722. }
  5723. _GM_addStyle(`
  5724. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  5725. cursor: pointer;
  5726. user-select: none;
  5727. display: inline-block;
  5728. margin-right: 5px;
  5729. -moz-transition:color 0.3s ease, transform 0.3s;
  5730. -webkit-transition:color 0.3s ease, transform 0.3s;
  5731. transition:color 0.3s ease, transform 0.3s;
  5732. }
  5733. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  5734. color:red;
  5735. transform: scale(1.5);
  5736. -webkit-transform: scale(1.5);
  5737. }
  5738. .updateDate{
  5739. cursor: pointer;
  5740. user-select: none;
  5741. -moz-transition:color 0.3s ease, transform 0.3s;
  5742. -webkit-transition:color 0.3s ease, transform 0.3s;
  5743. transition:color 0.3s ease, transform 0.3s;
  5744. transform-origin: left;
  5745. -webkit-transform-origin: left;
  5746. }
  5747. .updateDate:hover{
  5748. color:red;
  5749. transform: scale(1.1);
  5750. -webkit-transform: scale(1.1);
  5751. }
  5752. input[type=number]::-webkit-inner-spin-button,
  5753. input[type=number]::-webkit-outer-spin-button {
  5754. -webkit-appearance: none;
  5755. margin: 0;
  5756. }
  5757. input[type=number] {
  5758. -moz-appearance:textfield;
  5759. }
  5760. table td>h3 {
  5761. margin: 16px!important;
  5762. padding: 0!important;
  5763. }
  5764. table td>h4 {
  5765. padding: 0!important;
  5766. }
  5767. #saveBtn {
  5768. width: 60vw;
  5769. position: fixed;
  5770. z-index: 999;
  5771. bottom: 0;
  5772. left: 20vw;
  5773. font-size: xx-large;
  5774. opacity: 0.6;
  5775. cursor: pointer;
  5776. -moz-transition:all 0.3s ease;
  5777. -webkit-transition:all 0.3s ease;
  5778. transition:all 0.3s ease;
  5779. }
  5780. #configCon #saveBtn:hover {
  5781. opacity: 1;
  5782. margin-bottom: 0px;
  5783. }
  5784. #configCon #saveBtn {
  5785. margin-bottom: -30px;
  5786. }
  5787. #configCon.showSave #saveBtn {
  5788. margin-bottom: 0px;
  5789. }
  5790. `);
  5791. click2import = document.querySelector("[name='user-content-click2import'],[name='click2import']");
  5792. if (click2import) click2import.innerText = i18n("click2ImportRule")
  5793. configCon = document.querySelector(".markdown-body,.theme-default-content");
  5794. if (!configCon) {
  5795. setTimeout(() => {
  5796. location.reload();
  5797. }, 1000);
  5798. return true;
  5799. }
  5800. let insertPos = configCon.querySelector("hr,#jsoneditor");
  5801. configCon = document.createElement("div");
  5802. configCon.id = "configCon";
  5803. insertPos.parentNode.insertBefore(configCon, insertPos);
  5804.  
  5805. importUrlPres = document.querySelectorAll("pre[name='user-content-pagetual'],pre[name='pagetual']");
  5806. if (importUrlPres) {
  5807. [].forEach.call(importUrlPres, importUrlPre => {
  5808. importUrlPre.style.overflow = "hidden";
  5809. importUrlPre.style.display = rulesData.uninited ? "block" : "none";
  5810. });
  5811. }
  5812. if (click2import) click2import.style.display = rulesData.uninited ? "block" : "none";
  5813. let otherconfig = document.querySelector("a[name='user-content-otherconfig'],a[name='otherconfig']");
  5814. if (otherconfig) otherconfig.parentNode.removeChild(otherconfig);
  5815. let rulesExample = document.querySelector("#user-content-rules-example+a,#rules-example>a");
  5816. if (rulesExample) {
  5817. rulesExample.innerText = i18n("rulesExample");
  5818. if (lang == "zh-CN") {
  5819. rulesExample.href = rulesExample.href.replace("en", "cn");
  5820. } else if (lang == "zh-TW" || lang == "zh-HK") {
  5821. rulesExample.href = rulesExample.href.replace("/en", "");
  5822. }
  5823. }
  5824.  
  5825. let newPos, lastPos = 0;
  5826. window.addEventListener('scroll', function(e) {
  5827. newPos = window.scrollY;
  5828. if (newPos > lastPos) {
  5829. configCon.classList.add("showSave");
  5830. } else {
  5831. configCon.classList.remove("showSave");
  5832. }
  5833. lastPos = newPos;
  5834. });
  5835. } else return false;
  5836. } else return false;
  5837. let ruleBarInsertPos = document.createTextNode(' ');
  5838. configCon.appendChild(ruleBarInsertPos);
  5839. class Rulebar {
  5840. init(ruleUrl) {
  5841. let id = ruleUrl.id;
  5842. this.ruleUrl = ruleUrl;
  5843. this.item = document.createElement("p");
  5844. this.item.dataset.id = id;
  5845. let url = document.createElement("a");
  5846. url.href = ruleUrl.url;
  5847. url.innerHTML = ruleUrl.url;
  5848. url.title = ruleUrl.url;
  5849. let up = document.createElement("span");
  5850. up.innerHTML = "↑ ";
  5851. up.title = i18n("sortTitle");
  5852. let down = document.createElement("span");
  5853. down.innerHTML = "↓ ";
  5854. down.title = i18n("sortTitle");
  5855. let del = document.createElement("span");
  5856. del.innerHTML = "× ";
  5857. up.onclick = e => {
  5858. this.moveUp();
  5859. };
  5860. down.onclick = e => {
  5861. this.moveDown();
  5862. };
  5863. del.onclick = e => {
  5864. this.del();
  5865. };
  5866. this.item.appendChild(up);
  5867. this.item.appendChild(down);
  5868. this.item.appendChild(del);
  5869. this.item.appendChild(url);
  5870. if (ruleParser.rules) {
  5871. url.style.maxWidth = "calc(100% - 150px)";
  5872. url.style.overflow = "hidden";
  5873. url.style.display = "inline-block";
  5874. url.style.textOverflow = "ellipsis";
  5875. url.style.verticalAlign = "bottom";
  5876. url.style.whiteSpace = "nowrap";
  5877. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == id ? 1 : 0), 0);
  5878. let idSpan = document.createElement("span");
  5879. idSpan.style.float = "right";
  5880. idSpan.innerHTML = `[rules: ${rulesLength}]`;
  5881. this.item.appendChild(idSpan);
  5882. this.idSpan = idSpan;
  5883. }
  5884. configCon.insertBefore(this.item, ruleBarInsertPos);
  5885. }
  5886. updateNum() {
  5887. if (ruleParser.rules) {
  5888. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == this.item.dataset.id ? 1 : 0), 0);
  5889. this.idSpan.innerHTML = `[rules: ${rulesLength}]`;
  5890. }
  5891. }
  5892. saveSort() {
  5893. let sort = [];
  5894. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i => {
  5895. sort.push(i.dataset.id);
  5896. });
  5897. rulesData.sort = sort;
  5898. let urls = [];
  5899. sort.forEach(id => {
  5900. for (let s = 0; s < ruleUrls.length; s++) {
  5901. if (id == ruleUrls[s].id) {
  5902. urls.push(ruleUrls[s]);
  5903. break;
  5904. }
  5905. }
  5906. });
  5907. ruleUrls = urls;
  5908. storage.setItem("rulesData", rulesData);
  5909. showTips(i18n("sortTitle"));
  5910. }
  5911. moveUp() {
  5912. let preE = this.item.previousElementSibling;
  5913. if (compareNodeName(preE, ["p"]) && preE.children.length > 1) {
  5914. this.item.parentNode.insertBefore(this.item, preE);
  5915. this.saveSort();
  5916. }
  5917. }
  5918. moveDown() {
  5919. let nextE = this.item.nextElementSibling;
  5920. if (compareNodeName(nextE, ["p"]) && nextE.children.length > 1) {
  5921. this.item.parentNode.insertBefore(nextE, this.item);
  5922. this.saveSort();
  5923. }
  5924. }
  5925. del() {
  5926. if (this.ruleUrl.id < 2) {
  5927. showTips(i18n("cantDel"));
  5928. } else if (window.confirm(i18n("confirmDel"))) {
  5929. for (let u = 0; u < rulesData.urls.length; u++) {
  5930. if (this.ruleUrl.id == rulesData.urls[u].id) {
  5931. rulesData.urls.splice(u, 1);
  5932. break;
  5933. }
  5934. }
  5935. for (let u = 0; u < ruleUrls.length; u++) {
  5936. if (this.ruleUrl.id == ruleUrls[u].id) {
  5937. ruleUrls.splice(u, 1);
  5938. break;
  5939. }
  5940. }
  5941. for (let u = 0; u < rulesData.sort.length; u++) {
  5942. if (this.ruleUrl.id == rulesData.sort[u]) {
  5943. rulesData.sort.splice(u, 1);
  5944. break;
  5945. }
  5946. }
  5947. rulesData.ruleVersion = 0;
  5948. storage.setItem("rulesData", rulesData);
  5949. ruleParser.rules = ruleParser.rules.filter(item => {return item.from != this.ruleUrl.id});
  5950. storage.setItem("rules", ruleParser.rules);
  5951. this.item.parentNode.removeChild(this.item);
  5952. //location.reload();
  5953. }
  5954. }
  5955. }
  5956. let langSelect = document.createElement("select");
  5957. langSelect.style.float = "right";
  5958. langSelect.style.position = "relative";
  5959. langSelect.style.zIndex = "1";
  5960. let option = document.createElement("option");
  5961. option.value = "";
  5962. option.innerText = "Language";
  5963. langSelect.appendChild(option);
  5964. for (let key in langList) {
  5965. let option = document.createElement("option");
  5966. option.value = key;
  5967. option.innerText = langList[key];
  5968. langSelect.appendChild(option);
  5969. }
  5970. langSelect.value = rulesData.lang || "";
  5971. configCon.appendChild(langSelect);
  5972.  
  5973. let updateP = document.createElement("p"), i = 0;
  5974. let now = new Date().getTime();
  5975.  
  5976.  
  5977. let pastDate = (new Date(updateDate)).toString(), passStr;
  5978. let passTime = (now - updateDate) / 1000;
  5979. if (isNaN(passTime)) {
  5980. passStr = i18n("firstUpdate");
  5981. } else {
  5982. if (passTime < 60) {
  5983. passStr = i18n("passSec", parseInt(passTime));
  5984. } else if (passTime < 60 * 60) {
  5985. passStr = i18n("passMin", parseInt(passTime / 60));
  5986. } else if (passTime < 60 * 60 * 24) {
  5987. passStr = i18n("passHour", parseInt(passTime / 3600));
  5988. } else {
  5989. passStr = i18n("passDay", parseInt(passTime / 86400));
  5990. }
  5991. passStr += " 🖱 " + i18n("click2update");
  5992. }
  5993.  
  5994. let rulebarList = [], updateFail = false;
  5995. updateP.className = "updateDate";
  5996. updateP.innerHTML = passStr;
  5997. updateP.title = i18n("update") + " - " + pastDate;
  5998. configCon.appendChild(updateP);
  5999. if (ruleUrls) {
  6000. ruleUrls.forEach(ruleUrl => {
  6001. let rulebar = new Rulebar();
  6002. rulebar.init(ruleUrl);
  6003. rulebarList.push(rulebar);
  6004. });
  6005. }
  6006. let customUrlsTitle = document.createElement("h2");
  6007. customUrlsTitle.innerHTML = i18n("customUrls");
  6008. configCon.appendChild(customUrlsTitle);
  6009. let customUrlsInput = document.createElement("textarea");
  6010. customUrlsInput.style.width = "100%";
  6011. customUrlsInput.style.position = "relative";
  6012. customUrlsInput.placeholder = "http://wedata.net/databases/AutoPagerize/items_all.json \nhttps://hoothin.github.io/UserScripts/Pagetual/pagetualRules.json";
  6013. customUrlsInput.spellcheck = false;
  6014. configCon.appendChild(customUrlsInput);
  6015.  
  6016. let btns = document.createElement("div");
  6017. btns.style.display = "flex";
  6018. configCon.appendChild(btns);
  6019. let upBtnImg = document.createElement("div");
  6020. upBtnImg.style.width = "33%";
  6021. let upBtnImgTitle = document.createElement("h2");
  6022. upBtnImgTitle.style.whiteSpace = "nowrap";
  6023. upBtnImgTitle.style.overflow = "auto";
  6024. upBtnImgTitle.innerHTML = i18n("upBtnImg");
  6025. upBtnImg.appendChild(upBtnImgTitle);
  6026. let upBtnImgInput = document.createElement("input");
  6027. upBtnImgInput.style.width = "100%";
  6028. upBtnImgInput.style.position = "relative";
  6029. upBtnImgInput.placeholder = "data:image/png;base64,UpBtn";
  6030. upBtnImgInput.value = rulesData.upBtnImg || '';
  6031. upBtnImgInput.spellcheck = false;
  6032. upBtnImg.appendChild(upBtnImgInput);
  6033. btns.appendChild(upBtnImg);
  6034.  
  6035. let downBtnImg = document.createElement("div");
  6036. downBtnImg.style.width = "33%";
  6037. let downBtnImgTitle = document.createElement("h2");
  6038. downBtnImgTitle.style.whiteSpace = "nowrap";
  6039. downBtnImgTitle.style.overflow = "auto";
  6040. downBtnImgTitle.innerHTML = i18n("downBtnImg");
  6041. downBtnImg.appendChild(downBtnImgTitle);
  6042. let downBtnImgInput = document.createElement("input");
  6043. downBtnImgInput.style.width = "100%";
  6044. downBtnImgInput.style.position = "relative";
  6045. downBtnImgInput.placeholder = "data:image/png;base64,DownBtn";
  6046. downBtnImgInput.value = rulesData.downBtnImg || '';
  6047. downBtnImgInput.spellcheck = false;
  6048. downBtnImg.appendChild(downBtnImgInput);
  6049. btns.appendChild(downBtnImg);
  6050.  
  6051. let sideControllerIconDiv = document.createElement("div");
  6052. sideControllerIconDiv.style.width = "33%";
  6053. let sideControllerIconTitle = document.createElement("h2");
  6054. sideControllerIconTitle.style.whiteSpace = "nowrap";
  6055. sideControllerIconTitle.style.overflow = "auto";
  6056. sideControllerIconTitle.innerHTML = i18n("sideControllerIcon");
  6057. sideControllerIconDiv.appendChild(sideControllerIconTitle);
  6058. let sideControllerIconInput = document.createElement("input");
  6059. sideControllerIconInput.style.width = "100%";
  6060. sideControllerIconInput.style.position = "relative";
  6061. sideControllerIconInput.placeholder = "📄";
  6062. sideControllerIconInput.value = rulesData.sideControllerIcon || '';
  6063. sideControllerIconInput.spellcheck = false;
  6064. sideControllerIconDiv.appendChild(sideControllerIconInput);
  6065. btns.appendChild(sideControllerIconDiv);
  6066.  
  6067. let otherBtns = document.createElement("div");
  6068. otherBtns.style.display = "flex";
  6069. configCon.appendChild(otherBtns);
  6070. let loadingText = document.createElement("div");
  6071. loadingText.style.width = "100%";
  6072. let loadingTextTitle = document.createElement("h2");
  6073. loadingTextTitle.style.whiteSpace = "nowrap";
  6074. loadingTextTitle.style.overflow = "auto";
  6075. loadingTextTitle.innerHTML = i18n("loadingTextTitle");
  6076. loadingText.appendChild(loadingTextTitle);
  6077. let loadingTextInput = document.createElement("input");
  6078. loadingTextInput.value = rulesData.loadingText || '';
  6079. loadingTextInput.placeholder = i18n("loadingText");
  6080. loadingTextInput.style.width = "100%";
  6081. loadingTextInput.style.position = "relative";
  6082. loadingTextInput.style.margin = "0";
  6083. loadingTextInput.spellcheck = false;
  6084. loadingText.appendChild(loadingTextInput);
  6085. otherBtns.appendChild(loadingText);
  6086.  
  6087. let opacity = document.createElement("div");
  6088. let opacityTitle = document.createElement("h2");
  6089. opacityTitle.style.whiteSpace = "nowrap";
  6090. opacityTitle.style.overflow = "visible";
  6091. opacityTitle.innerHTML = i18n("opacity");
  6092. opacity.appendChild(opacityTitle);
  6093. let opacityInput = document.createElement("input");
  6094. opacityInput.value = rulesData.opacity * 100;
  6095. opacityInput.type = "number";
  6096. opacityInput.min = 0;
  6097. opacityInput.max = 100;
  6098. opacityInput.style.width = "110px";
  6099. opacityInput.style.position = "relative";
  6100. opacityInput.style.margin = "0";
  6101. opacityInput.placeholder = i18n("opacityPlaceholder");
  6102. opacityInput.spellcheck = false;
  6103. opacityInput.oninput = e => {
  6104. if (opacityInput.value > 100) opacityInput.value = 100;
  6105. else if (opacityInput.value < 0) opacityInput.value = 0;
  6106. };
  6107. opacity.appendChild(opacityInput);
  6108. otherBtns.appendChild(opacity);
  6109.  
  6110. let pageElementCss = document.createElement("div");
  6111. pageElementCss.style.marginBottom = "30px";
  6112. let pageElementCssTitle = document.createElement("h2");
  6113. pageElementCssTitle.innerHTML = i18n("pageElementCss");
  6114. pageElementCss.appendChild(pageElementCssTitle);
  6115. let pageElementCssInput = document.createElement("input");
  6116. pageElementCssInput.value = rulesData.pageElementCss || '';
  6117. pageElementCssInput.style.width = "100%";
  6118. pageElementCssInput.style.position = "relative";
  6119. pageElementCssInput.style.margin = "0";
  6120. pageElementCssInput.placeholder = "font-size: xx-large;";
  6121. pageElementCssInput.spellcheck = false;
  6122. pageElementCss.appendChild(pageElementCssInput);
  6123. configCon.appendChild(pageElementCss);
  6124.  
  6125. let customCss = document.createElement("div");
  6126. customCss.style.marginBottom = "50px";
  6127. let customCssTitle = document.createElement("h2");
  6128. customCssTitle.innerHTML = i18n("customCss");
  6129. customCss.appendChild(customCssTitle);
  6130. let customCssInput = document.createElement("textarea");
  6131. customCssInput.value = rulesData.customCss || '';
  6132. customCssInput.style.width = "100%";
  6133. customCssInput.style.position = "relative";
  6134. customCssInput.style.margin = "0";
  6135. customCssInput.placeholder = ".pagetual {\n}";
  6136. customCssInput.spellcheck = false;
  6137. customCss.appendChild(customCssInput);
  6138. configCon.appendChild(customCss);
  6139.  
  6140. let configTable = document.createElement("table");
  6141. configTable.style.width = "100%";
  6142. let configTbody = document.createElement("tbody");
  6143. configTbody.style.width = "99%";
  6144. configTbody.style.display = "inline-table";
  6145. configTable.appendChild(configTbody);
  6146. configCon.appendChild(configTable);
  6147. function createCheckbox(innerText, val, tag, parentCheck, otherType, alwaysShow) {
  6148. if (typeof val == 'undefined') val = "";
  6149. let title = document.createElement(tag || "h3");
  6150. title.innerHTML = innerText;
  6151. title.style.overflowWrap = "normal";
  6152. let input = document.createElement("input");
  6153. if (otherType === 'key') {
  6154. input.type = 'text';
  6155. input.setAttribute('readOnly', 'readonly');
  6156. input.addEventListener("keydown", e => {
  6157. if (e.key === 'Escape' || e.key === 'Backspace') input.value = '';
  6158. else input.value = e.key;
  6159. e.stopPropagation();
  6160. e.preventDefault();
  6161. });
  6162. } else {
  6163. input.type = otherType || "checkbox";
  6164. }
  6165. input.style.width = "35px";
  6166. input.style.height = "20px";
  6167. input.style.float = "left";
  6168. input.style.margin = "0 2px";
  6169. input.value = val;
  6170. input.checked = val;
  6171. let td = document.createElement("td");
  6172. td.appendChild(input);
  6173. if (parentCheck) {
  6174. title.appendChild(input);
  6175. title.style.margin = "0";
  6176. td.appendChild(title);
  6177. let parent = parentCheck.parentNode.nextElementSibling;
  6178. let tr = parent.querySelector("tr");
  6179. if (!tr) {
  6180. tr = document.createElement("tr");
  6181. parent.appendChild(tr);
  6182. }
  6183. tr.appendChild(td);
  6184. if (!alwaysShow) {
  6185. if (!parentCheck.checked) {
  6186. td.style.display = "none";
  6187. }
  6188. parentCheck.addEventListener("click", e => {
  6189. td.style.display = parentCheck.checked ? "" : "none";
  6190. });
  6191. }
  6192. } else {
  6193. let tr = document.createElement("tr");
  6194. tr.appendChild(td);
  6195. td = document.createElement("td");
  6196. td.appendChild(title);
  6197. tr.appendChild(td);
  6198. configTable.children[0].appendChild(tr);
  6199. }
  6200. let xNodePos = innerText.indexOf('【X】');
  6201. if (xNodePos !== -1) {
  6202. input.style.float = "";
  6203. let xNode = title.firstChild.splitText(xNodePos);
  6204. xNode.splitText(3);
  6205. xNode.parentNode.replaceChild(input, xNode);
  6206. }
  6207. return input;
  6208. }
  6209.  
  6210. let setConfigPageInput = createCheckbox(i18n("setConfigPage"), false);
  6211. let enableWhiteListInput = createCheckbox(i18n("autoRun"), rulesData.enableWhiteList != true);
  6212. let sideControllerInput = createCheckbox(i18n("sideController"), rulesData.sideController);
  6213. let sideControllerAlwaysInput = createCheckbox(i18n("sideControllerAlways"), rulesData.sideControllerAlways, "h4", sideControllerInput);
  6214. let sideControllerScrollInput = createCheckbox(i18n("sideControllerScroll"), rulesData.sideControllerScroll !== false, "h4", sideControllerInput);
  6215. let sideControllerLoadNowInput = createCheckbox(i18n("loadNow"), rulesData.sideControllerLoadNow !== false, "h4", sideControllerInput);
  6216. let enableDebugInput = createCheckbox(i18n("enableDebug"), rulesData.enableDebug != false);
  6217. let enableHistoryInput = createCheckbox(i18n("enableHistory"), rulesData.enableHistory === true);
  6218. let enableHistoryAfterInsertInput = createCheckbox(i18n("enableHistoryAfterInsert"), rulesData.enableHistoryAfterInsert === true, "h4", enableHistoryInput);
  6219. let openInNewTabInput = createCheckbox(i18n("openInNewTab"), rulesData.openInNewTab != false);
  6220. let hidePageBarInput = createCheckbox(i18n("hideBarTips"), rulesData.opacity == 0);
  6221. let hidePageBarArrowInput = createCheckbox(i18n("hideBarArrow"), rulesData.hideBarArrow);
  6222. let hideLoadingIconInput = createCheckbox(i18n("hideLoadingIcon"), rulesData.hideLoadingIcon != false);
  6223. let initRunInput = createCheckbox(i18n("initRun"), rulesData.initRun != false);
  6224. let autoLoadNumInput = createCheckbox(i18n("autoLoadNum"), rulesData.autoLoadNum, "h4", initRunInput, "number");
  6225. let preloadInput = createCheckbox(i18n("preload"), rulesData.preload != false);
  6226. let rateInput = createCheckbox(i18n("turnRate"), rulesData.rate, "h4", preloadInput, "number", true);
  6227. let dbClick2StopInput = createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  6228. let manualModeInput = createCheckbox(i18n("manualMode"), rulesData.manualMode);
  6229. let clickModeInput = createCheckbox(i18n("clickMode"), rulesData.clickMode);
  6230. let pageBarMenuInput = createCheckbox(i18n("pageBarMenu"), rulesData.pageBarMenu != false);
  6231. let arrowToScrollInput = createCheckbox(i18n("arrowToScroll"), rulesData.arrowToScroll);
  6232. let contentVisibilityInput = createCheckbox(i18n("contentVisibility"), rulesData.contentVisibility);
  6233. let wedata2githubInput = createCheckbox(i18n("wedata2github"), rulesData.wedata2github);
  6234. let customFirstInput = createCheckbox(i18n("customFirst"), rulesData.customFirst);
  6235. let lastPageTipsInput = createCheckbox(i18n("lastPageTips"), rulesData.lastPageTips);
  6236. let updateNotificationInput = createCheckbox(i18n("updateNotification"), rulesData.updateNotification != false);
  6237.  
  6238. let hideBarInput = createCheckbox(i18n("hideBar"), rulesData.hideBar && !rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  6239. hideBarInput.name = 'hideBar';
  6240. let hideBarButNoStopInput = createCheckbox(i18n("hideBarButNoStop"), rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  6241. hideBarButNoStopInput.name = 'hideBar';
  6242. hideBarInput.addEventListener('mouseup', e => {
  6243. if (hideBarInput.checked) {
  6244. setTimeout(() => {hideBarInput.checked = false}, 0);
  6245. }
  6246. });
  6247. hideBarButNoStopInput.addEventListener('mouseup', e => {
  6248. if (hideBarButNoStopInput.checked) {
  6249. setTimeout(() => {hideBarButNoStopInput.checked = false}, 0);
  6250. }
  6251. });
  6252. hidePageBarInput.addEventListener('click', e => {
  6253. opacityInput.value = hidePageBarInput.checked ? 0 : 100;
  6254. });
  6255.  
  6256. let dbClick2StopCtrlInput = createCheckbox(i18n("dbClick2StopCtrl"), rulesData.dbClick2StopCtrl, "h4", dbClick2StopInput);
  6257. let dbClick2StopAltInput = createCheckbox(i18n("dbClick2StopAlt"), rulesData.dbClick2StopAlt, "h4", dbClick2StopInput);
  6258. let dbClick2StopShiftInput = createCheckbox(i18n("dbClick2StopShift"), rulesData.dbClick2StopShift, "h4", dbClick2StopInput);
  6259. let dbClick2StopMetaInput = createCheckbox(i18n("dbClick2StopMeta"), rulesData.dbClick2StopMeta, "h4", dbClick2StopInput);
  6260. let dbClick2StopKeyInput = createCheckbox(i18n("dbClick2StopKey"), rulesData.dbClick2StopKey, "h4", dbClick2StopInput, "key");
  6261.  
  6262. let otherConfigPage = (rulesData.configPage || configPage[0]) != location.href.replace(/#.*/, "");
  6263. if (!otherConfigPage) {
  6264. setConfigPageInput.parentNode.parentNode.style.display = "none";
  6265. }
  6266.  
  6267. updateP.onclick = e => {
  6268. updateFail = false;
  6269. //ruleParser.rules = [];
  6270. showTips(i18n("beginUpdate"), "", 30000);
  6271. updateRules(() => {
  6272. if (!updateFail) {
  6273. showTips(i18n("updateSucc"));
  6274. if (importUrlPres) {
  6275. [].forEach.call(importUrlPres, importUrlPre => {
  6276. importUrlPre.style.display = "none";
  6277. });
  6278. }
  6279. if (click2import) click2import.style.display = "none";
  6280. }
  6281. updateP.innerHTML = i18n("passSec", 0);
  6282. updateP.title = i18n("update");
  6283. rulebarList.forEach(rulebar => {
  6284. rulebar.updateNum();
  6285. });
  6286. }, (rule, err) => {
  6287. if (rule.id == 1) {
  6288. showTips(`Failed to update wedata rules! Try to switch to wedata mirror!`);
  6289. wedata2githubInput.scrollIntoView({ behavior: "smooth" });
  6290. } else {
  6291. showTips(`Failed to update ${rule.url} rules!`);
  6292. }
  6293. debug(err);
  6294. updateFail = true;
  6295. });
  6296. };
  6297. let customRulesTitle = document.createElement("h2");
  6298. 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');
  6299. configCon.appendChild(customRulesTitle);
  6300. customRulesInput = document.createElement("textarea");
  6301. customRulesInput.spellcheck = false;
  6302. configCon.appendChild(customRulesInput);
  6303. if (rulesData.editTemp) {
  6304. if (!ruleParser.customRules) {
  6305. ruleParser.customRules = [];
  6306. }
  6307. for (let i in ruleParser.customRules) {
  6308. if (ruleParser.customRules[i].url == rulesData.editTemp.url) {
  6309. ruleParser.customRules.splice(i, 1);
  6310. break;
  6311. }
  6312. }
  6313. ruleParser.customRules.unshift(rulesData.editTemp);
  6314. rulesData.editTemp = null;
  6315. storage.setItem("rulesData", rulesData);
  6316. customRulesInput.previousElementSibling.scrollIntoView();
  6317. }
  6318. customRulesInput.style.width = "100%";
  6319. customRulesInput.style.height = "800px";
  6320. 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]`;
  6321. let preCustom = getFormatJSON(ruleParser.customRules);
  6322. customRulesInput.value = preCustom;
  6323. if (isGuidePage) customRulesInput.style.display = "none";
  6324. let blacklistInput = document.createElement("textarea");
  6325. blacklistInput.style.width = "100%";
  6326. blacklistInput.style.height = "500px";
  6327. blacklistInput.style.display = "none";
  6328. blacklistInput.spellcheck = false;
  6329. 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";
  6330. blacklistInput.value = rulesData.blacklist ? rulesData.blacklist.join("\n") : "";
  6331. let blacklistBtn = document.createElement("button");
  6332. blacklistBtn.innerText = i18n("editBlacklist");
  6333. blacklistBtn.style.width = "100%";
  6334. blacklistBtn.onclick = e => {
  6335. blacklistInput.style.display = blacklistInput.style.display == "none" ? "" : "none";
  6336. };
  6337. configCon.appendChild(blacklistBtn);
  6338. configCon.appendChild(blacklistInput);
  6339. let saveBtn = document.createElement("button");
  6340. saveBtn.innerHTML = i18n("save");
  6341. saveBtn.id = "saveBtn";
  6342. configCon.appendChild(saveBtn);
  6343. saveBtn.onclick = e => {
  6344. try {
  6345. let customRules;
  6346. if (editor) {
  6347. if (editorChanged) {
  6348. editorChanged = false;
  6349. storage.setItem("hpRules", []);
  6350. storage.setItem("smartRules", []);
  6351. }
  6352. customRules = editor.get();
  6353. if (!customRules) {
  6354. customRules = "";
  6355. } else {
  6356. if (Array && Array.isArray && !Array.isArray(customRules)) {
  6357. showTips(i18n("errorRulesMustBeArray"));
  6358. return;
  6359. }
  6360. }
  6361. } else {
  6362. if (customRulesInput.value != preCustom) {
  6363. storage.setItem("hpRules", []);
  6364. storage.setItem("smartRules", []);
  6365. }
  6366. if (customRulesInput.value == "") {
  6367. customRules = "";
  6368. } else {
  6369. customRules = JSON.parse(customRulesInput.value);
  6370. if (Array && Array.isArray && !Array.isArray(customRules)) {
  6371. showTips(i18n("errorRulesMustBeArray"));
  6372. return;
  6373. }
  6374. customRulesInput.value = JSON.stringify(customRules, null, 4);
  6375. }
  6376. }
  6377. debug(customRules);
  6378. storage.setItem("customRules", customRules);
  6379. } catch(e) {
  6380. debug(e);
  6381. let pos = e && e.message && e.message.match(/position (\d+)/);
  6382. if (pos && !editor) {
  6383. pos = parseInt(pos[1]);
  6384. customRulesInput.value = customRulesInput.value.slice(0, pos) + "➡️" + customRulesInput.value.slice(pos);
  6385. }
  6386. showTips(i18n("errorJson"));
  6387. return;
  6388. }
  6389. rulesData.lang = langSelect.value || "";
  6390. if (setConfigPageInput.checked) rulesData.configPage = location.href;
  6391. rulesData.wedata2github = wedata2githubInput.checked;
  6392. let opacity = parseInt(opacityInput.value) || 0;
  6393. if (opacity > 100) opacity = 100;
  6394. else if (opacity < 0) opacity = 0;
  6395. rulesData.opacity = opacity / 100;
  6396. rulesData.blacklist = blacklistInput.value ? blacklistInput.value.trim().split("\n") : "";
  6397. rulesData.hideBar = hideBarInput.checked;
  6398. rulesData.hideBarButNoStop = hideBarButNoStopInput.checked;
  6399. rulesData.dbClick2Stop = dbClick2StopInput.checked;
  6400. rulesData.enableWhiteList = !enableWhiteListInput.checked;
  6401. rulesData.enableDebug = enableDebugInput.checked;
  6402. rulesData.updateNotification = updateNotificationInput.checked;
  6403. rulesData.enableHistory = enableHistoryInput.checked;
  6404. rulesData.enableHistoryAfterInsert = enableHistoryAfterInsertInput.checked;
  6405. rulesData.openInNewTab = openInNewTabInput.checked;
  6406. rulesData.hideLoadingIcon = hideLoadingIconInput.checked;
  6407. rulesData.hideBarArrow = hidePageBarArrowInput.checked;
  6408. rulesData.customFirst = customFirstInput.checked;
  6409. rulesData.lastPageTips = lastPageTipsInput.checked;
  6410. rulesData.initRun = initRunInput.checked;
  6411. rulesData.autoLoadNum = autoLoadNumInput.value !== "0" ? autoLoadNumInput.value : '';
  6412. rulesData.rate = parseFloat(rateInput.value) || 0;
  6413. rulesData.preload = preloadInput.checked;
  6414. rulesData.manualMode = manualModeInput.checked;
  6415. rulesData.clickMode = clickModeInput.checked;
  6416. rulesData.pageBarMenu = pageBarMenuInput.checked;
  6417. rulesData.arrowToScroll = arrowToScrollInput.checked;
  6418. rulesData.contentVisibility = contentVisibilityInput.checked;
  6419. if (rulesData.sideController != sideControllerInput.checked) {
  6420. rulesData.sideControllerPos = false;
  6421. }
  6422. rulesData.sideController = sideControllerInput.checked;
  6423. rulesData.sideControllerScroll = sideControllerScrollInput.checked;
  6424. rulesData.sideControllerLoadNow = sideControllerLoadNowInput.checked;
  6425. rulesData.sideControllerAlways = sideControllerAlwaysInput.checked;
  6426. rulesData.pageElementCss = pageElementCssInput.value;
  6427. rulesData.customCss = customCssInput.value;
  6428. rulesData.upBtnImg = upBtnImgInput.value;
  6429. rulesData.downBtnImg = downBtnImgInput.value;
  6430. rulesData.sideControllerIcon = sideControllerIconInput.value;
  6431. rulesData.loadingText = loadingTextInput.value;
  6432. rulesData.dbClick2StopCtrl = dbClick2StopCtrlInput.checked;
  6433. rulesData.dbClick2StopAlt = dbClick2StopAltInput.checked;
  6434. rulesData.dbClick2StopShift = dbClick2StopShiftInput.checked;
  6435. rulesData.dbClick2StopMeta = dbClick2StopMetaInput.checked;
  6436. rulesData.dbClick2StopKey = dbClick2StopKeyInput.value;
  6437. storage.setItem("rulesData", rulesData);
  6438. let customUrls = customUrlsInput.value.trim(), urlImported = false;
  6439. if (customUrls) {
  6440. customUrls = customUrls.split(/\n/);
  6441. for (let c = 0; c < customUrls.length; c++) {
  6442. let url;
  6443. if (/^0\s*\|/.test(customUrls[c])) {
  6444. url = customUrls[c].replace(/^0\s*\|\s*/, "").trim();
  6445. if (!/^http/.test(url)) {
  6446. showTips(i18n("errorWrongUrl"));
  6447. return;
  6448. }
  6449. } else {
  6450. url = customUrls[c].trim();
  6451. if (!/^http/.test(url)) {
  6452. showTips(i18n("errorWrongUrl"));
  6453. return;
  6454. }
  6455. }
  6456. let maxId = 1, hasUrl = false;
  6457. if (!rulesData.urls) {
  6458. rulesData.urls = [];
  6459. }
  6460. ruleUrls.forEach(u => {
  6461. if (maxId < u.id) {
  6462. maxId = u.id;
  6463. }
  6464. if (u.url == url) {
  6465. hasUrl = true;
  6466. }
  6467. });
  6468. if (hasUrl) break;
  6469. if (!rulesData.sort) rulesData.sort = [1];
  6470. let newRule = {id: maxId + 1, url: url};
  6471. ruleUrls.push(newRule);
  6472. rulesData.urls.push(newRule);
  6473. rulesData.sort.push(maxId + 1);
  6474. storage.setItem("rulesData", rulesData);
  6475. let rulebar = new Rulebar();
  6476. rulebar.init(newRule);
  6477. rulebarList.push(rulebar);
  6478. }
  6479. }
  6480. showTips(i18n("settingsSaved"));
  6481. };
  6482. return true;
  6483. }
  6484.  
  6485. function updateRules (success, fail, keepCache) {
  6486. if (!storage.supportCrossSave()) {
  6487. fail({url:''}, "Not support cross storage");
  6488. showTips("Current platform do not support cross storage!");
  6489. return;
  6490. }
  6491. if (inUpdate) return;
  6492. inUpdate = true;
  6493. let ruleIndex = ruleUrls.length - 1;
  6494. if (!keepCache) {
  6495. storage.setItem("hpRules", []);
  6496. storage.setItem("smartRules", []);
  6497. }
  6498. let allOk = true;
  6499. let preLength = ruleParser.rules.length;
  6500. let fetchVersion = -1;
  6501. async function needUpdate(url, id) {
  6502. if (!/^https:\/\/hoothin\.github\.io\/|\/hoothin\/UserScripts\/.*\/Pagetual\/pagetualRules\.json/i.test(url)) {
  6503. return true;
  6504. }
  6505. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == id ? 1 : 0), 0);
  6506. if (rulesLength === 0) return true;
  6507. if (fetchVersion >= 0) {
  6508. return fetchVersion > (rulesData.ruleVersion || 0);
  6509. }
  6510. fetchVersion = await new Promise(resolve => {
  6511. _GM_xmlhttpRequest({
  6512. url: url.replace(/\/\w+\.json/i, "/version"),
  6513. method: 'GET',
  6514. timeout: 20000,
  6515. headers: {
  6516. 'accept': 'application/json,text/html'
  6517. },
  6518. onload: function(res) {
  6519. let version = parseInt(res.response || res.responseText);
  6520. resolve(version || -1);
  6521. },
  6522. onerror: function(e) {
  6523. resolve(-1);
  6524. },
  6525. ontimeout: function(e) {
  6526. resolve(-1);
  6527. }
  6528. });
  6529. });
  6530. return fetchVersion > (rulesData.ruleVersion || 0);
  6531. }
  6532. async function addNextRule() {
  6533. if (ruleIndex < 0) {
  6534. let now = new Date().getTime();
  6535. storage.setItem("ruleLastUpdate", now);
  6536. storage.setItem("rules", ruleParser.rules);
  6537. let curLength = ruleParser.rules.length;
  6538. if (curLength !== preLength && rulesData.updateNotification) {
  6539. _GM_notification({
  6540. text: `Rules has updated( ${preLength} => ${curLength} )`,
  6541. title: "Pagetual rules updated",
  6542. onclick: (event) => {
  6543. event.preventDefault();
  6544. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  6545. }
  6546. });
  6547. }
  6548. inUpdate = false;
  6549. let rulesDataChanged = false;
  6550. if (fetchVersion >= 0 && rulesData.ruleVersion !== fetchVersion) {
  6551. rulesData.ruleVersion = fetchVersion;
  6552. rulesDataChanged = true;
  6553. }
  6554. if (rulesData.uninited && allOk && ruleUrls.length > 1) {
  6555. rulesData.uninited = false;
  6556. rulesDataChanged = true;
  6557. }
  6558. if (rulesDataChanged) {
  6559. storage.setItem("rulesData", rulesData);
  6560. }
  6561. success();
  6562. } else {
  6563. let rule = ruleUrls[ruleIndex--];
  6564. if (await needUpdate(rule.url, rule.id)) {
  6565. ruleParser.addRuleByUrl(rule.url, rule.id, (json, err) => {
  6566. if (!json) {
  6567. allOk = false;
  6568. fail(rule, err);
  6569. }
  6570. addNextRule();
  6571. });
  6572. } else {
  6573. addNextRule();
  6574. }
  6575. }
  6576. }
  6577. addNextRule();
  6578. }
  6579.  
  6580. function objIsArr(obj) {
  6581. return obj &&
  6582. typeof obj === 'object' &&
  6583. typeof obj.length === 'number' &&
  6584. !(obj.propertyIsEnumerable('length'));
  6585. }
  6586.  
  6587. function isVisible(el, win) {
  6588. if(!el || !el.offsetParent)return false;
  6589. var loopable = true,
  6590. visible = el.nodeName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  6591. while(loopable && visible) {
  6592. el = el.parentNode;
  6593.  
  6594. if(el && !compareNodeName(el, ["body"])) {
  6595. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  6596. }else {
  6597. loopable = false;
  6598. }
  6599. }
  6600. return visible;
  6601. }
  6602.  
  6603. function getElementTop(ele) {
  6604. if (!ele) return 0;
  6605. if (ele.getBoundingClientRect) {
  6606. return ele.getBoundingClientRect().top + document.documentElement.scrollTop;
  6607. }
  6608. var actualTop = ele.offsetTop;
  6609. var current = ele.offsetParent;
  6610. while (current) {
  6611. actualTop += current.offsetTop;
  6612. current = current.offsetParent;
  6613. }
  6614. return actualTop;
  6615. }
  6616.  
  6617. function getElementLeft(ele) {
  6618. if (!ele) return 0;
  6619. if (ele.getBoundingClientRect) {
  6620. return ele.getBoundingClientRect().left + document.documentElement.scrollLeft;
  6621. }
  6622. var actualLeft = ele.offsetLeft;
  6623. var current = ele.offsetParent;
  6624. while (current) {
  6625. actualLeft += current.offsetLeft;
  6626. current = current.offsetParent;
  6627. }
  6628. return actualLeft;
  6629. }
  6630.  
  6631. function getElementBottom(ele) {
  6632. return getElementTop(ele) + (ele.offsetHeight || ele.scrollHeight);
  6633. }
  6634.  
  6635. function getFormatJSON(obj){
  6636. if(!objIsArr(obj) || obj.length === 0)return "";
  6637. return JSON.stringify(obj, null, 4);
  6638. }
  6639.  
  6640. function globMatch(first, second) {
  6641. if (first === '*') {
  6642. return true;
  6643. }
  6644. if (first.length == 0 && second.length == 0){
  6645. return true;
  6646. }
  6647.  
  6648. if (first.length > 1 && first[0] == '*' &&
  6649. second.length == 0){
  6650. return false;
  6651. }
  6652.  
  6653. if ((first.length > 1 && first[0] == '?') ||
  6654. (first.length != 0 && second.length != 0 &&
  6655. first[0] == second[0])){
  6656. return globMatch(first.substring(1),
  6657. second.substring(1));
  6658. }
  6659.  
  6660. if (first.length > 0 && first[0] == '*'){
  6661. return globMatch(first.substring(1), second) ||
  6662. globMatch(first, second.substring(1));
  6663. }
  6664.  
  6665. return false;
  6666. }
  6667.  
  6668. let pageReady = false;
  6669. function initRules(callback) {
  6670. charset = (document.characterSet || document.charset || document.inputEncoding);
  6671. let equiv = document.querySelector('[http-equiv="Content-Type"]');
  6672. if (equiv && equiv.content) {
  6673. let innerCharSet = equiv.content.match(/charset\=([^;]+)/);
  6674. if (!innerCharSet) {
  6675. charsetValid = false;
  6676. } else if (innerCharSet[1].replace("-", "").toLowerCase() != charset.replace("-", "").toLowerCase()) {
  6677. charsetValid = false;
  6678. }
  6679. } else charsetValid = false;
  6680. storage.getItem("rulesData", data => {
  6681. /*0 wedata格式,1 pagetual格式*/
  6682. ruleUrls = [{
  6683. id: 1,
  6684. url: data && data.wedata2github ? 'https://hoothin.github.io/UserScripts/Pagetual/items_all.json' : 'http://wedata.net/databases/AutoPagerize/items_all.json',
  6685. type: 0,
  6686. }];
  6687. if (data) {
  6688. rulesData = data;
  6689. if (data.urls) ruleUrls = ruleUrls.concat(data.urls);
  6690. if (data.sort) {
  6691. let urls = [];
  6692. data.sort.forEach(id => {
  6693. for (let s = 0; s < ruleUrls.length; s++) {
  6694. if (id == ruleUrls[s].id) {
  6695. urls.push(ruleUrls[s]);
  6696. break;
  6697. }
  6698. }
  6699. });
  6700. ruleUrls = urls;
  6701. }
  6702. }
  6703. if (rulesData.lang) {
  6704. setLang(rulesData.lang);
  6705. }
  6706. if (rulesData.firstRun) {
  6707. rulesData.firstRun = false;
  6708. storage.setItem("rulesData", rulesData);
  6709. setTimeout(() => {
  6710. storage.getItem("rulesData", data => {
  6711. if (data.firstRun === false) {
  6712. _GM_openInTab(firstRunPage, {active: true});
  6713. }
  6714. });
  6715. }, 100);
  6716. }
  6717. _GM_registerMenuCommand(i18n("configure"), () => {
  6718. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  6719. });
  6720. if (rulesData.blacklist && rulesData.blacklist.length > 0) {
  6721. let href = location.href.slice(0, 500);
  6722. let commentStart = false;
  6723. for (let i = 0; i < rulesData.blacklist.length; i++) {
  6724. let curGlob = rulesData.blacklist[i];
  6725. if (!curGlob) continue;
  6726. if (curGlob.indexOf("//") == 0) continue;
  6727. if (commentStart) {
  6728. if (/\*\/$/.test(curGlob)) {
  6729. commentStart = false;
  6730. }
  6731. continue;
  6732. }
  6733. if (curGlob.indexOf("/*") == 0) {
  6734. commentStart = true;
  6735. continue;
  6736. }
  6737. if (curGlob.indexOf("/") == 0) {
  6738. let regMatch = curGlob.match(/^\/(.*)\/(\w*)$/);
  6739. if (regMatch && new RegExp(regMatch[1], regMatch[2]).test(href)) {
  6740. forceState == 1;
  6741. return;
  6742. }
  6743. } else if (globMatch(curGlob, href)) {
  6744. forceState == 1;
  6745. return;
  6746. }
  6747. }
  6748. }
  6749. _GM_registerMenuCommand(i18n("editCurrent"), () => {
  6750. picker.start();
  6751. });
  6752. ruleParser.initSavedRules(async () => {
  6753. let upBtnImg = rulesData.upBtnImg, downBtnImg = rulesData.downBtnImg, _sideControllerIcon = rulesData.sideControllerIcon;
  6754. if (upBtnImg && downBtnImg) {
  6755. downSvgCSS = downSvgCSS.replace("transform: rotate(180deg);", "");
  6756. } else if (upBtnImg && !downBtnImg) {
  6757. downBtnImg = upBtnImg;
  6758. } else if(downBtnImg && !upBtnImg) {
  6759. upBtnImg = downBtnImg;
  6760. }
  6761. if (upBtnImg) {
  6762. upSvg = /https?:|data/.test(upBtnImg) ? `<img class="pagetual" src="${upBtnImg}"/>` : `<span>${upBtnImg}</span>`;
  6763. }
  6764. if (downBtnImg) {
  6765. downSvg = /https?:|data/.test(downBtnImg) ? `<img class="pagetual" src="${downBtnImg}"/>` : `<span>${downBtnImg}</span>`;
  6766. }
  6767. if (_sideControllerIcon) {
  6768. sideControllerIcon = /https?:|data/.test(_sideControllerIcon) ? `<img class="pagetual" src="${_sideControllerIcon}"/>` : `<span>${_sideControllerIcon}</span>`;
  6769. }
  6770. setLoadingDiv(rulesData.loadingText || i18n("loadingText"));
  6771. if (typeof(rulesData.opacity) == "undefined") {
  6772. rulesData.opacity = 1;
  6773. }
  6774. if (typeof(rulesData.hideBar) == "undefined") {
  6775. rulesData.hideBar = false;
  6776. }
  6777. if (typeof(rulesData.dbClick2Stop) == "undefined") {
  6778. rulesData.dbClick2Stop = true;
  6779. }
  6780. if (typeof(rulesData.enableWhiteList) == "undefined") {
  6781. rulesData.enableWhiteList = false;
  6782. }
  6783. if (typeof(rulesData.enableHistory) == "undefined") {
  6784. rulesData.enableHistory = false;
  6785. }
  6786. if (typeof(rulesData.openInNewTab) == "undefined") {
  6787. rulesData.openInNewTab = false;
  6788. }
  6789. if (typeof(rulesData.enableDebug) == "undefined") {
  6790. rulesData.enableDebug = true;
  6791. }
  6792. if (typeof(rulesData.updateNotification) == "undefined") {
  6793. rulesData.updateNotification = true;
  6794. }
  6795. if (typeof(rulesData.initRun) == "undefined") {
  6796. rulesData.initRun = true;
  6797. }
  6798. if (typeof(rulesData.preload) == "undefined") {
  6799. rulesData.preload = true;
  6800. }
  6801. if (typeof(rulesData.customFirst) == "undefined") {
  6802. rulesData.customFirst = false;
  6803. }
  6804. if (typeof(rulesData.manualMode) == "undefined") {
  6805. rulesData.manualMode = false;
  6806. }
  6807. if (typeof(rulesData.clickMode) == "undefined") {
  6808. rulesData.clickMode = false;
  6809. }
  6810. if (typeof(rulesData.pageBarMenu) == "undefined") {
  6811. rulesData.pageBarMenu = true;
  6812. }
  6813. if (typeof(rulesData.arrowToScroll) == "undefined") {
  6814. rulesData.arrowToScroll = false;
  6815. }
  6816. if (typeof(rulesData.hideLoadingIcon) == "undefined") {
  6817. rulesData.hideLoadingIcon = false;
  6818. }
  6819. if (typeof(rulesData.hideBarArrow) == "undefined") {
  6820. rulesData.hideBarArrow = false;
  6821. }
  6822. if (typeof(rulesData.lastPageTips) == "undefined") {
  6823. rulesData.lastPageTips = true;
  6824. }
  6825. if (typeof(rulesData.rate) == "undefined") {
  6826. rulesData.rate = 1;
  6827. }
  6828. rate = rulesData.rate;
  6829. if (rulesData.autoLoadNum && rulesData.initRun) {
  6830. autoLoadNum = parseInt(rulesData.autoLoadNum);
  6831. }
  6832. openInNewTab = rulesData.openInNewTab ? 1 : 0;
  6833. enableDebug = rulesData.enableDebug;
  6834.  
  6835. let _nextSwitch = await getListData("nextSwitch", location.host);
  6836. if (typeof(_nextSwitch) !== "undefined") {
  6837. nextIndex = _nextSwitch || 0;
  6838. }
  6839.  
  6840. let _forceState = await getListData("forceState", location.host);
  6841. if (typeof(_forceState) == "undefined") {
  6842. _forceState = await getData("forceState_" + location.host);
  6843. }
  6844. if (typeof(_forceState) == "undefined") {
  6845. _forceState = (rulesData.enableWhiteList ? 1 : 0);
  6846. }
  6847. forceState = _forceState;
  6848.  
  6849. autoScroll = await getListData("autoScroll", location.host + location.pathname) || 0;
  6850.  
  6851. updateDate = await getData("ruleLastUpdate");
  6852.  
  6853. let _loadNowNum = await getData("loadNowNum");
  6854. if (typeof(_loadNowNum) != "undefined") {
  6855. loadNowNum = _loadNowNum;
  6856. }
  6857. let _autoScrollRate = await getData("autoScrollRate");
  6858. if (_autoScrollRate) {
  6859. autoScrollRate = _autoScrollRate;
  6860. }
  6861.  
  6862. author = await getData("author") || "";
  6863.  
  6864. manualPause = !!await getListData("pauseState", location.host);
  6865.  
  6866. let href = location.href.slice(0, 100);
  6867. try {
  6868. if (_unsafeWindow.initedPagetual) {
  6869. if (ruleImportUrlReg.test(href)) {
  6870. showTips(i18n('duplicate'));
  6871. }
  6872. return;
  6873. }
  6874. _unsafeWindow.initedPagetual = true;
  6875. } catch(e) {showTips(e)}
  6876. listenUrl();
  6877. _GM_registerMenuCommand(i18n("update"), () => {
  6878. showTips(i18n("beginUpdate"), "", 60000);
  6879. updateRules(() => {
  6880. showTips(i18n("updateSucc"));
  6881. location.reload();
  6882. },(rule, err) => {
  6883. showTips(`Failed to update ${rule.url} rules!`);
  6884. debug(err);
  6885. });
  6886. });
  6887. _GM_registerMenuCommand(i18n(forceState == 1 ? "enable" : "disableSite"), () => {
  6888. if (forceState == 1) {
  6889. forceState = 0;
  6890. showTips(i18n("enableSiteTips"));
  6891. changeStop(false, true);
  6892. } else {
  6893. forceState = 1;
  6894. showTips(i18n("disableSiteTips"));
  6895. changeStop(true, true);
  6896. sideController.remove();
  6897. }
  6898. setListData("forceState", location.host, forceState);
  6899. if (!ruleParser.curSiteRule.url) {
  6900. setTimeout(() => {
  6901. location.reload();
  6902. }, 500);
  6903. }
  6904. });
  6905. _GM_registerMenuCommand(i18n("toggleAutoScroll"), () => {
  6906. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  6907. autoScroll = parseInt(autoScroll) || 0;
  6908. if (autoScroll < 0) autoScroll = 0;
  6909. if (autoScroll && autoScroll != autoScrollRate) {
  6910. autoScrollRate = autoScroll;
  6911. storage.setItem("autoScrollRate", autoScrollRate);
  6912. }
  6913. setListData("autoScroll", location.host + location.pathname, autoScroll);
  6914. startAutoScroll();
  6915. });
  6916. startAutoScroll();
  6917.  
  6918.  
  6919. if (initConfig(href)) return;
  6920. pageReady = true;
  6921. if (forceState == 1) return;
  6922. let now = new Date().getTime();
  6923. if (!updateDate || now - updateDate > 2 * 24 * 60 * 60 * 1000) {
  6924. updateRules(() => {
  6925. }, (rule, err) => {}, true);
  6926. storage.setItem("ruleLastUpdate", now);
  6927. }
  6928. callback();
  6929. });
  6930. });
  6931. }
  6932.  
  6933. let xhrFailed = false;
  6934. function requestDoc(url, callback) {
  6935. let postParams = url.match(/#p{(.*)}$/);
  6936. if (postParams) {
  6937. postParams = postParams[1];
  6938. url = url.replace(/#p{.*/, "");
  6939. }
  6940. let ruleHeaders = ruleParser.curSiteRule.headers;
  6941. let headers = {
  6942. 'Referer': location.href,
  6943. 'User-Agent': navigator.userAgent,
  6944. 'accept': 'text/html,application/xhtml+xml,application/xml',
  6945. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + charset,
  6946. };
  6947. if (ruleHeaders) {
  6948. if (ruleHeaders.referer) {
  6949. headers.referer = ruleHeaders.referer;
  6950. }
  6951. if (ruleHeaders.userAgent) {
  6952. headers.userAgent = ruleHeaders.userAgent;
  6953. }
  6954. if (ruleHeaders.accept) {
  6955. headers.accept = ruleHeaders.accept;
  6956. }
  6957. if (ruleHeaders.contentType) {
  6958. headers.contentType = ruleHeaders.contentType;
  6959. let ruleCharset = ruleHeaders.contentType.match(/charset\=([^;]+)/);
  6960. if (ruleCharset) charset = ruleCharset[1];
  6961. }
  6962. if (ruleHeaders.cookie) {
  6963. headers.cookie = ruleHeaders.cookie;
  6964. }
  6965. }
  6966. _GM_xmlhttpRequest({
  6967. url: url,
  6968. method: postParams ? 'POST' : 'GET',
  6969. data: postParams,
  6970. overrideMimeType: 'text/html;charset=' + charset,
  6971. headers: headers,
  6972. timeout: 50000,
  6973. onload: async function(res) {
  6974. if (isPause) return callback(false);
  6975. var doc = null, response = res.response;
  6976. try {
  6977. doc = document.implementation.createHTMLDocument('');
  6978. doc.documentElement.innerHTML = response;
  6979. } catch (e) {
  6980. debug('parse error:' + e.toString());
  6981. }
  6982. let pageElement = null;
  6983. let preCode = ruleParser.curSiteRule.pagePre;
  6984. if (preCode) {
  6985. try {
  6986. let preResult;
  6987. if (typeof preCode == 'function') {
  6988. preResult = await preCode(response, doc);
  6989. } else if (preCode.length == 2) {
  6990. preResult = response.replace(new RegExp(preCode[0], "gi"), preCode[1]);
  6991. } else {
  6992. preResult = await new AsyncFunction("response", "doc", '"use strict";' + preCode)(response, doc);
  6993. }
  6994. if (typeof preResult !== "undefined") {
  6995. if (typeof preResult === "string") {
  6996. doc.documentElement.innerHTML = preResult;
  6997. } else pageElement = preResult;
  6998. }
  6999. } catch(e) {
  7000. debug(e);
  7001. }
  7002. }
  7003. let base = doc.querySelector("base");
  7004. ruleParser.basePath = base ? base.href : url;
  7005. if (charsetValid && !ruleHeaders) {
  7006. let equiv = doc.querySelector('[http-equiv="Content-Type"]');
  7007. if (equiv && equiv.content) {
  7008. let innerCharSet = equiv.content.match(/charset\=([^;]+)/);
  7009. if (innerCharSet && innerCharSet[1].replace("-", "").toLowerCase() != charset.replace("-", "").toLowerCase()) {
  7010. charset = innerCharSet[1];
  7011. return requestDoc(url, callback);
  7012. }
  7013. }
  7014. }
  7015. if (pageElement === null) {
  7016. pageElement = ruleParser.getPageElement(doc);
  7017. }
  7018. if ((!pageElement || pageElement.length == 0) && res.status >= 400) {
  7019. debug(res.status + " " + url, "Error status");
  7020. if (!ruleParser.curSiteRule.smart || !xhrFailed) {
  7021. xhrFailed = true;
  7022. return callback(false);
  7023. }
  7024. }
  7025. if (inCors && (!pageElement || pageElement.length == 0) && ruleParser.curSiteRule.smart) {
  7026. let article;
  7027. for (let i = 0; i < mainSel.length; i++) {
  7028. article = doc.querySelectorAll(mainSel[i]);
  7029. if (article && article.length === 1) break;
  7030. }
  7031. if (article && article.length == 1) {
  7032. article = article[0];
  7033. ruleParser.curSiteRule.pageElement = article.nodeName.toLowerCase() + (article.id ? "#" + article.id : "") + (article.className ? "." + article.className.replace(/ /g, ".") : "") + ">*";
  7034. pageElement = article.children;
  7035. } else {
  7036. ruleParser.curSiteRule.pageElement = allOfBody;
  7037. pageElement = ruleParser.getPageElement(doc);
  7038. }
  7039. ruleParser.getInsert(true);
  7040. }
  7041. //只有1的話怕不是圖片哦
  7042. if (pageElement && (pageElement.length > 1 || (pageElement.length == 1 && !compareNodeName(pageElement[0], ["img"])))) {
  7043. await ruleParser.insertPage(doc, pageElement, url, callback, false);
  7044. if (ruleParser.curSiteRule.action == 1) {
  7045. isLoading = true;
  7046. requestFromIframe(url, async (doc, eles) => {
  7047. if (eles) {
  7048. await ruleParser.insertPage(doc, eles, url, callback, true);
  7049. } else isLoading = false;
  7050. });
  7051. } else ruleParser.curSiteRule.action = 0;
  7052. } else if ((ruleParser.curSiteRule.smart || curPage == 1) && !inCors) {
  7053. ruleParser.curSiteRule.action = 1;
  7054. requestFromIframe(url, async (doc, eles) => {
  7055. if (eles) {
  7056. await ruleParser.insertPage(doc, eles, url, callback, true);
  7057. } else isLoading = false;
  7058. });
  7059. } else {
  7060. debug("Stop as no page element");
  7061. ruleParser.noValidContent(url);
  7062. changeStop(true);
  7063. callback(false);
  7064. }
  7065. },
  7066. onerror: function(e) {
  7067. debug(e, "NetError");
  7068. callback(false);
  7069. },
  7070. ontimeout: function(e) {
  7071. debug(e, "NetTimeout");
  7072. callback(false);
  7073. }
  7074. });
  7075. }
  7076.  
  7077. function initPage() {
  7078. ruleParser.initPage(() => {
  7079. if (ruleParser.curSiteRule.autoLoadNum) {
  7080. autoLoadNum = ruleParser.curSiteRule.autoLoadNum;
  7081. }
  7082. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  7083. _GM_registerMenuCommand(i18n("nextSwitch"), () => {
  7084. nextSwitch.start();
  7085. });
  7086. }
  7087. if (ruleParser.nextLinkHref) {
  7088. let isJs = ruleParser.hrefIsJs(ruleParser.nextLinkHref);
  7089. if (!isJs) {
  7090. let inForce = (forceState == 2 || forceState == 3);
  7091. _GM_registerMenuCommand(i18n(inForce ? "cancelForceIframe" : "forceIframe"), () => {
  7092. if (inForce) {
  7093. setListData("forceState", location.host, "");
  7094. } else {
  7095. let _state = ruleParser.curSiteRule.action > 0 || confirm(i18n("forceAllBody")) ? 2 : 3;
  7096. setListData("forceState", location.host, _state);
  7097. }
  7098. setTimeout(() => {
  7099. location.reload();
  7100. }, 500);
  7101. });
  7102. }
  7103. _GM_registerMenuCommand(i18n("loadNow"), () => {
  7104. if (autoLoadNum != -1) {
  7105. autoLoadNum = -1;
  7106. return;
  7107. }
  7108. let loadNum = window.prompt(i18n("loadConfirm"), loadNowNum);
  7109. if (loadNum === "" || loadNum === null) return;
  7110. loadNum = Math.abs(parseInt(loadNum)) || 0;
  7111. if (loadNowNum != loadNum) {
  7112. loadNowNum = loadNum;
  7113. storage.setItem("loadNowNum", loadNowNum);
  7114. }
  7115. autoLoadNum = loadNum;
  7116. nextPage();
  7117. });
  7118. }
  7119. initListener();
  7120. });
  7121. }
  7122.  
  7123. var pageBarStyle, mainStyleEle, mainStyleStyle;
  7124. function initView() {
  7125. if (!mainStyleStyle) {
  7126. mainStyleStyle = `
  7127. .pagetual_pageBar{
  7128. -moz-transition:all 0.3s ease-in-out 0s;
  7129. -webkit-transition:all 0.3s ease-in-out 0s;
  7130. transition:all 0.3s ease-in-out 0s;
  7131. font-family: Arial,sans-serif !important;
  7132. text-align: center !important;
  7133. }
  7134. .pagetual_pageBar.stop {
  7135. -webkit-filter: invert(100%);
  7136. filter: invert(100%);
  7137. opacity: 1!important;
  7138. }
  7139. .pagetual_pageBar.hide {
  7140. display: none!important;
  7141. }
  7142. .pagetual-hide {
  7143. display: none!important;
  7144. }
  7145. .pagetual_pageBar:hover {
  7146. opacity: 1!important;
  7147. box-shadow: 0px 0px 10px 0px #000000aa;
  7148. border-radius: 20px;
  7149. background-color: rgb(240 240 240 / 80%);
  7150. border-color: transparent!important;
  7151. }
  7152. .pagetual_pageBar span {
  7153. vertical-align: super;
  7154. }
  7155. .pagetual_pageBar a::before,
  7156. .pagetual_pageBar a::after {
  7157. content: none;
  7158. }
  7159. .pagetual_pageBar a>span {
  7160. margin-top: 0!important;
  7161. pointer-events: none;
  7162. padding: unset;
  7163. opacity: 0;
  7164. -moz-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  7165. -webkit-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  7166. transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  7167. transform: none;
  7168. left: 0;
  7169. margin-left: calc(50% - 20px);
  7170. }
  7171. .pagetual_pageBar a>span:hover {
  7172. color: red;
  7173. }
  7174. .pagetual_pageBar a:hover>span {
  7175. opacity: 1!important;
  7176. }
  7177. .pagetual_pageBar span.prevScreen,
  7178. .pagetual_pageBar span.nextScreen {
  7179. display: block!important;
  7180. top: unset !important;
  7181. padding: unset !important;
  7182. opacity: 0!important;
  7183. }
  7184. .pagetual_pageBar a:hover>span.prevScreen {
  7185. margin-top: -${rulesData.opacity == 1 ? 31 : 30}px!important;
  7186. pointer-events: all;
  7187. }
  7188. .pagetual_pageBar span.refreshRing {
  7189. position: absolute;
  7190. top: 0;
  7191. opacity: 0;
  7192. height: 30px;
  7193. margin-left: calc(50% - 23px);
  7194. display: block!important;
  7195. }
  7196. .pagetual_pageBar span.refreshRing>svg {
  7197. background: white;
  7198. border-radius: 50%;
  7199. }
  7200. .pagetual_pageBar a:hover>span.refreshRing {
  7201. opacity: 0.3;
  7202. -webkit-animation: pagetual_ring 2.0s infinite linear;
  7203. animation: pagetual_ring 2.0s infinite linear;
  7204. }
  7205. @-webkit-keyframes pagetual_ring {
  7206. 0% { -webkit-transform: rotate(0deg) }
  7207. 100% {
  7208. -webkit-transform: rotate(360deg);
  7209. }
  7210. }
  7211. @keyframes pagetual_ring {
  7212. 0% {
  7213. transform: rotate(0deg);
  7214. -webkit-transform: rotate(0deg);
  7215. } 100% {
  7216. transform: rotate(360deg);
  7217. -webkit-transform: rotate(360deg);
  7218. }
  7219. }
  7220. .pagetual_pageBar a:hover>span.nextScreen {
  7221. margin-top: 30px!important;
  7222. pointer-events: all;
  7223. }
  7224. .pagetual_pageBar span>svg {
  7225. -moz-transition:transform 0.5s ease, opacity 0.3s ease;
  7226. -webkit-transition:transform 0.5s ease, opacity 0.3s ease;
  7227. transition:transform 0.5 ease, opacity 0.3s ease;
  7228. opacity: 0;
  7229. }
  7230. .pagetual_pageBar.stop span>svg{
  7231. opacity: 1;
  7232. }
  7233. .pagetual_pageBar.stop span>svg>path{
  7234. transform: scale(.8);
  7235. transform-origin: center;
  7236. -moz-transition:transform 0.3s ease;
  7237. -webkit-transition:transform 0.3s ease;
  7238. transition:transform 0.3 ease;
  7239. }
  7240. .pagetual_pageBar.stop:hover span>svg>path{
  7241. transform: unset;
  7242. }
  7243. .pagetual_pageBar:hover span>svg {
  7244. opacity: 1;
  7245. }
  7246. .pagetual_pageBar span>svg.upSvg:hover {
  7247. transform: rotate(360deg) scale3d(1.2, 1.2, 1.2);
  7248. }
  7249. .pagetual_pageBar span>svg.downSvg:hover {
  7250. transform: rotate(540deg) scale3d(1.2, 1.2, 1.2)!important;
  7251. }
  7252. .pagetual_pageBar .pagetual_pageNum{
  7253. color: #55555f;
  7254. }
  7255. .pagetual_pageBar .pagetual_pageNum:hover{
  7256. color: #ff6464;
  7257. }
  7258. .pagetual_tipsWords {
  7259. font-size: 50px;
  7260. font-weight: bold;
  7261. font-family: "黑体", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
  7262. "Oxygen", "Ubuntu", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
  7263. "Segoe UI Emoji", "Segoe UI Symbol";
  7264. color: #ffffff;
  7265. min-height: 70px;
  7266. max-width: 80%;
  7267. line-height: 1.5;
  7268. position: fixed;
  7269. left: 50%;
  7270. top: 10%;
  7271. margin-left: -99999px;
  7272. padding: 0 15px;
  7273. z-index: 2147483647;
  7274. background-color: #000;
  7275. border: 1px solid #303030;
  7276. border-radius: 10px;
  7277. opacity: 0;
  7278. filter: alpha(opacity=65);
  7279. box-shadow: 5px 5px 20px 0px #000;
  7280. -moz-transition:opacity 0.3s ease-in-out 0s;
  7281. -webkit-transition:opacity 0.3s ease-in-out 0s;
  7282. transition:opacity 0.3s ease-in-out 0s;
  7283. pointer-events: none;
  7284. word-break: break-all;
  7285. }
  7286. .pagetual_tipsWords>a {
  7287. color: #ffffff;
  7288. }
  7289. .pagetual_loading {
  7290. width: 50px;
  7291. height: 50px;
  7292. margin: 10px auto;
  7293. border-radius: 100%;
  7294. display: flex;
  7295. -webkit-animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  7296. animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  7297. }
  7298. @-webkit-keyframes pagetual_loading_scaleout {
  7299. 0% { -webkit-transform: scale(0.0) }
  7300. 100% {
  7301. -webkit-transform: scale(1.0);
  7302. opacity: 0;
  7303. }
  7304. }
  7305. @keyframes pagetual_loading_scaleout {
  7306. 0% {
  7307. transform: scale(0.0);
  7308. -webkit-transform: scale(0.0);
  7309. } 100% {
  7310. transform: scale(1.0);
  7311. -webkit-transform: scale(1.0);
  7312. opacity: 0;
  7313. }
  7314. }
  7315. .pagetual_loading_text {
  7316. white-space: nowrap;
  7317. -webkit-animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  7318. animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  7319. }
  7320. @-webkit-keyframes pagetual_loading_opacity {
  7321. 0% { opacity: 1 }
  7322. 50% { opacity: 0.2 }
  7323. 100% { opacity: 1 }
  7324. }
  7325. @keyframes pagetual_loading_opacity {
  7326. 0% { opacity: 1 }
  7327. 50% { opacity: 0.2 }
  7328. 100% { opacity: 1 }
  7329. }
  7330. `;
  7331. 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%);"}`;
  7332. }
  7333. if (!mainStyleEle || !mainStyleEle.parentNode) {
  7334. mainStyleEle = _GM_addStyle(mainStyleStyle);
  7335. }
  7336. }
  7337. var loadingDiv = document.createElement("div");
  7338. 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;";
  7339.  
  7340. 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;`;
  7341. function setLoadingDiv(loadingText) {
  7342. 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>`}`);
  7343. }
  7344.  
  7345. 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>`;
  7346. 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;`;
  7347. 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>`;
  7348. 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);`;
  7349.  
  7350. 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;`;
  7351. 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;`;
  7352. var sideControllerIcon = '';
  7353.  
  7354. var tipsWords = document.createElement("div");
  7355. tipsWords.className = "pagetual_tipsWords";
  7356.  
  7357. function changeStop(stop, save) {
  7358. isPause = stop;
  7359. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar,#pagetual-sideController"), bar => {
  7360. if (isPause) {
  7361. bar.classList.add("stop");
  7362. } else {
  7363. bar.classList.remove("stop");
  7364. }
  7365. });
  7366. if (!isPause) ruleParser.showAddedElements();
  7367. manualPause = isPause;
  7368. if (save && sideController.inited) setListData("pauseState", location.host, isPause ? true : "");
  7369. }
  7370.  
  7371. function changeHideBar(hide) {
  7372. isHideBar = hide;
  7373. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar"), bar => {
  7374. if (isHideBar) {
  7375. bar.classList.add("hide");
  7376. } else {
  7377. bar.classList.remove("hide");
  7378. }
  7379. });
  7380. }
  7381.  
  7382. function isInViewPort(element) {
  7383. if (!getBody(document).contains(element)) return false;
  7384. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  7385. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  7386. const {
  7387. top,
  7388. right,
  7389. bottom,
  7390. left,
  7391. } = element.getBoundingClientRect();
  7392.  
  7393. return (
  7394. top >= 0 &&
  7395. left >= 0 &&
  7396. right <= viewWidth + 1 &&
  7397. top <= viewHeight * rate &&
  7398. isVisible(element, _unsafeWindow)
  7399. );
  7400. }
  7401.  
  7402. function getPageBar() {
  7403. let preBar = null, nextBar = null;
  7404. let pageBars = [].slice.call(document.querySelectorAll(".pagetual_pageBar"));
  7405. for (let i = 0; i < pageBars.length; i++) {
  7406. let pageBar = pageBars[i];
  7407. if (!pageBar || !getBody(document).contains(pageBar)) continue;
  7408. let {
  7409. top,
  7410. right,
  7411. bottom,
  7412. left,
  7413. } = pageBar.getBoundingClientRect();
  7414. if (top > 500) {
  7415. nextBar = pageBar;
  7416. preBar = (i - 1 >= 0 ? pageBars[i - 1] : null);
  7417. if (pageBar && getBody(document).contains(pageBar)) {
  7418. let {
  7419. top,
  7420. right,
  7421. bottom,
  7422. left,
  7423. } = pageBar.getBoundingClientRect();
  7424. if (top < -500) {
  7425. preBar = pageBar;
  7426. } else preBar = (i - 2 >= 0 ? pageBars[i - 2] : null);
  7427. }
  7428. break;
  7429. }
  7430. }
  7431. if (!nextBar) preBar = pageBars[pageBars.length - 2];
  7432. return {preBar: preBar, nextBar: nextBar};
  7433. }
  7434.  
  7435. var urlChanged = false;
  7436. var urlChanging = false;
  7437. var urlchangeHandler = e => {
  7438. if (ruleParser && ruleParser.curSiteRule && ruleParser.curSiteRule.listenUrlChange == false) return;
  7439. isPause = true;
  7440. setTimeout(() => {
  7441. lastActiveUrl = location.href;
  7442. if (urlChanging) return;
  7443. urlChanging = true;
  7444. let href = location.href.slice(0, 60);
  7445. if (href == configPage[1]) {
  7446. setTimeout(() => {
  7447. initConfig(href);
  7448. urlChanging = false;
  7449. }, 1000);
  7450. } else {
  7451. setTimeout(() => {
  7452. if (guidePage.test(href)) {
  7453. setTimeout(() => {
  7454. initConfig(href);
  7455. urlChanging = false;
  7456. }, 1000);
  7457. } else {
  7458. ruleParser.urlChanged();
  7459. if (!ruleParser.nextLinkHref) {
  7460. isLoading = false;
  7461. }
  7462. urlChanging = false;
  7463. //if (!pageReady && !ruleImportUrlReg.test(href)) location.reload();
  7464. }
  7465. }, 500);
  7466. }
  7467. }, 1);
  7468. };
  7469. window.addEventListener('pagetual_pushState', urlchangeHandler);
  7470. /*var _wr = function(type) {
  7471. var orig = history[type];
  7472. return function() {
  7473. var rv = orig.apply(this, arguments);
  7474. var e = new Event('pagetual_' + type);
  7475. e.arguments = arguments;
  7476. window.dispatchEvent(e);
  7477. return rv;
  7478. };
  7479. };
  7480. history.pushState = _wr('pushState');*/
  7481.  
  7482. function listenUrl() {
  7483. var prevPathname = window.location.pathname;
  7484. var prevSearch = window.location.search;
  7485. var checkUrlTime = 100;
  7486. var checkUrlTimer;
  7487. var checkClickedEle = null;
  7488. var checkFunc = () => {
  7489. if (forceState == 1) return;
  7490. if (checkClickedEle) {
  7491. if (!clickedSth && checkClickedEle && checkClickedEle.nodeName) {
  7492. if (compareNodeName(checkClickedEle, ["a", "button"])) {
  7493. clickedSth = true;
  7494. } else {
  7495. let targetStyle = _unsafeWindow.getComputedStyle(checkClickedEle);
  7496. if (targetStyle.cursor == "pointer") clickedSth = true;
  7497. }
  7498. }
  7499. checkClickedEle = null;
  7500. }
  7501. if (checkUrlTime < 5000) {
  7502. checkUrlTime += checkUrlTime>>1;
  7503. }
  7504. clearTimeout(checkUrlTimer);
  7505. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7506. if (document.hidden) return;
  7507. if (!ruleParser.canListenUrlChange()) {
  7508. return;
  7509. }
  7510. if ((prevPathname !== window.location.pathname || prevSearch !== window.location.search) && window.location.href != ruleParser.historyUrl) {
  7511. checkUrlTime = 2000;
  7512. urlWillChange = true;
  7513. var e = new Event('pagetual_pushState');
  7514. e.arguments = arguments;
  7515. window.dispatchEvent(e);
  7516. clickedSth = false;
  7517. }
  7518. prevPathname = window.location.pathname;
  7519. prevSearch = window.location.search;
  7520. };
  7521. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7522.  
  7523. document.addEventListener("click", e => {
  7524. if (!checkClickedEle) {
  7525. checkClickedEle = e.target;
  7526. checkUrlTime = 300;
  7527. clearTimeout(checkUrlTimer);
  7528. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7529. }
  7530. });
  7531. }
  7532.  
  7533. let scrollContainer;
  7534. function distToBottom () {
  7535. let scrolly = window.scrollY;
  7536. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  7537. if (!scrollContainer || !document.documentElement.contains(scrollContainer)) {
  7538. if (curPage > 1 || ruleParser.nextLinkHref) {
  7539. let pageEle = ruleParser.getPageElement(document);
  7540. if (pageEle && pageEle.length) {
  7541. let parent = pageEle[0].parentNode, pageScrollY = parent.scrollTop;
  7542. while (parent && pageScrollY == 0) {
  7543. parent = parent.parentNode;
  7544. pageScrollY = parent.scrollTop;
  7545. }
  7546. if (pageScrollY) {
  7547. scrollContainer = parent;
  7548. return scrollContainer.scrollHeight - pageScrollY - windowHeight;
  7549. }
  7550. }
  7551. }
  7552. }
  7553. if (scrollContainer) {
  7554. return scrollContainer.scrollHeight - scrollContainer.scrollTop - windowHeight;
  7555. }
  7556.  
  7557. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7558. return scrollH - scrolly - windowHeight;
  7559. }
  7560.  
  7561. let scrollHandler, clickToResetHandler, dblclickHandler, keydownHandler, hashchangeHandler, manualModeKeyHandler, pagetualNextHandler, keyupHandler, messageHandler;
  7562. function initListener () {
  7563. document.removeEventListener('scroll', scrollHandler, true);
  7564. document.removeEventListener('wheel', scrollHandler, true);
  7565. document.removeEventListener('dblclick', dblclickHandler);
  7566. document.removeEventListener('keydown', keydownHandler);
  7567. window.removeEventListener('hashchange', hashchangeHandler, false);
  7568. document.removeEventListener('keydown', manualModeKeyHandler);
  7569. document.removeEventListener('pagetual.next', pagetualNextHandler, false);
  7570. document.removeEventListener('keyup', keyupHandler);
  7571. _unsafeWindow.removeEventListener('message', messageHandler, true);
  7572. let loadmoreBtn, loadingMore = true, lastScroll = 0, checkLoadMoreTimes = 0, loadMoreInv;
  7573. if (ruleParser.curSiteRule.smart) {
  7574. loadingMore = false;
  7575. } else if (ruleParser.curSiteRule.loadMore) {
  7576. loadingMore = false;
  7577. }
  7578. clickMode = typeof ruleParser.curSiteRule.clickMode == 'undefined' ? rulesData.clickMode : ruleParser.curSiteRule.clickMode;
  7579. let clickingNext = false;
  7580. let clickNext = async () => {
  7581. if (clickingNext) return;
  7582. clickingNext = true;
  7583. setTimeout(() => {
  7584. clickingNext = false;
  7585. }, 1500);
  7586. let nextLink = ruleParser.nextLinkHref;
  7587. if (!nextLink) return;
  7588. let isJs = ruleParser.hrefIsJs(nextLink);
  7589. if (isJs) {
  7590. let nextBtn = ruleParser.nextLinkEle;
  7591. if (!nextBtn || !nextBtn.offsetParent) nextBtn = await ruleParser.getNextLink(document, true);
  7592. if (nextBtn) emuClick(nextBtn);
  7593. } else {
  7594. window.location.href = nextLink;
  7595. }
  7596. };
  7597. let checkScrollReach = () => {
  7598. let dist = distToBottom();
  7599. if (clickMode) {
  7600. if (dist < 10) {
  7601. clickNext();
  7602. }
  7603. } else if (dist < bottomGap) {
  7604. nextPage();
  7605. }
  7606. };
  7607. messageHandler = e => {
  7608. if (e.data.command === 'pagetual') {
  7609. let action = e.data.action;
  7610. let detail = e.data.detail;
  7611. switch (action) {
  7612. case "config":
  7613. if (!detail || typeof detail !== 'object') return;
  7614. rulesData = {
  7615. ...rulesData,
  7616. ...detail
  7617. }
  7618. storage.setItem("rulesData", rulesData);
  7619. break;
  7620. case "nextPage":
  7621. if (detail === "" || detail === null) return;
  7622. detail = parseInt(detail) || 0;
  7623. if (loadNowNum != detail) {
  7624. loadNowNum = detail;
  7625. }
  7626. autoLoadNum = detail;
  7627. nextPage();
  7628. break;
  7629. case "loadMore":
  7630. clearInterval(loadMoreInv);
  7631. if (detail === -1) return;
  7632. loadmoreBtn = getLoadMore(document, loadmoreBtn);
  7633. loadmoreBtn && emuClick(loadmoreBtn);
  7634. if (detail === 0) {
  7635. loadMoreInv = setInterval(() => {
  7636. loadmoreBtn = getLoadMore(document, loadmoreBtn);
  7637. loadmoreBtn && emuClick(loadmoreBtn);
  7638. }, 500);
  7639. }
  7640. break;
  7641. }
  7642. }
  7643. return true;
  7644. }
  7645. _unsafeWindow.addEventListener('message', messageHandler, true);
  7646. scrollHandler = e => {
  7647. if (urlChanged && !isLoading) {
  7648. ruleParser.initPage(() => {});
  7649. urlChanged = false;
  7650. loadingMore = false;
  7651. return;
  7652. }
  7653. if (isPause) return;
  7654. if (!loadingMore) {
  7655. loadmoreBtn = getLoadMore(document, loadmoreBtn);
  7656. if (loadmoreBtn) {
  7657. if (isInViewPort(loadmoreBtn)) {
  7658. emuClick(loadmoreBtn);
  7659. loadingMore = true;
  7660. setTimeout(() => {loadingMore = false}, 200);
  7661. }
  7662. } else {
  7663. loadingMore = true;
  7664. if (!ruleParser.curSiteRule.smart || checkLoadMoreTimes++ < 3) {
  7665. setTimeout(() => {loadingMore = false}, 200);
  7666. }
  7667. }
  7668. }
  7669. if (!isLoading && !stopScroll) {
  7670. checkScrollReach();
  7671. }
  7672. ruleParser.changeVisibility();
  7673. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  7674. if (ruleParser.curSiteRule.lockScroll) {
  7675. if (isLoading && Math.abs(lastScroll - curScroll) > 350) {
  7676. getBody(document).scrollTop = lastScroll;
  7677. document.documentElement.scrollTop = lastScroll;
  7678. } else {
  7679. lastScroll = curScroll;
  7680. }
  7681. }
  7682. if (targetY >= 0) {
  7683. if (Math.abs(targetY - curScroll) < 100) {
  7684. targetY = -1;
  7685. }
  7686. }
  7687. };
  7688. dblclickHandler = e => {
  7689. if (forceState == 1 || compareNodeName(e.target, ["input", "textarea", "select", "a", "button", "svg", "use", "img", "path"])) return;
  7690. if (!rulesData.dbClick2StopKey) {
  7691. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  7692. (rulesData.dbClick2StopAlt && !e.altKey) ||
  7693. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  7694. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  7695. return;
  7696. }
  7697. }
  7698. if (!compareNodeName(e.target, ["body"]) && !e.target.classList.contains('pagetual_pageBar')) {
  7699. try {
  7700. let selection = window.getSelection();
  7701. let selStr = selection.toString().trim();
  7702. if (!selStr) {
  7703. selection = selection.getRangeAt(0);
  7704. selStr = selection && selection.cloneContents().children[0];
  7705. if (selStr && !compareNodeName(selStr, ["img"])) selStr = false;
  7706. }
  7707. if (selStr) {
  7708. return;
  7709. }
  7710. } catch (e) {}
  7711. }
  7712. if (rulesData.dbClick2Stop && (ruleParser.nextLinkHref || loadmoreBtn)) {
  7713. setTimeout(() => {
  7714. if (rulesData.hideBarButNoStop || rulesData.hideBar) {
  7715. changeHideBar(!isHideBar);
  7716. }
  7717. if (!rulesData.hideBarButNoStop) {
  7718. changeStop(!isPause, true);
  7719. showTips(i18n(isPause ? "disable" : "enable"));
  7720. }
  7721. if (!isPause) {
  7722. checkScrollReach();
  7723. }
  7724. }, 10);
  7725. }
  7726. };
  7727. document.addEventListener('dblclick', dblclickHandler);
  7728. clickToResetHandler = e => {
  7729. if (!ruleParser.nextLinkHref) isLoading = false;
  7730. };
  7731. document.addEventListener('click', clickToResetHandler);
  7732. if (rulesData.dbClick2StopKey) {
  7733. keydownHandler = e => {
  7734. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  7735. (rulesData.dbClick2StopAlt && !e.altKey) ||
  7736. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  7737. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  7738. return;
  7739. }
  7740. if (document.activeElement &&
  7741. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  7742. document.activeElement.contentEditable == 'true')) {
  7743. return;
  7744. }
  7745. var key = e.key.toLowerCase();
  7746. if (rulesData.dbClick2StopKey.toLowerCase() == key) {
  7747. if (forceState == 1) {
  7748. forceState = 0;
  7749. showTips(i18n("enableSiteTips"));
  7750. changeStop(false, true);
  7751. } else {
  7752. forceState = 1;
  7753. showTips(i18n("disableSiteTips"));
  7754. changeStop(true, true);
  7755. sideController.remove();
  7756. }
  7757. if (!ruleParser.curSiteRule.url) {
  7758. setListData("forceState", location.host, forceState);
  7759. setTimeout(() => {
  7760. location.reload();
  7761. }, 500);
  7762. }
  7763. }
  7764. };
  7765. document.addEventListener('keydown', keydownHandler);
  7766. }
  7767. if (ruleParser.curSiteRule.listenHashChange) {
  7768. hashchangeHandler = () => {
  7769. isPause = true;
  7770. ruleParser.urlChanged();
  7771. if (!ruleParser.nextLinkHref) isLoading = false;
  7772. };
  7773. window.addEventListener('hashchange', hashchangeHandler, false);
  7774. }
  7775. let manualMode = typeof ruleParser.curSiteRule.manualMode == 'undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode;
  7776. if (manualMode) {
  7777. manualModeKeyHandler = e => {
  7778. if (document.activeElement &&
  7779. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  7780. document.activeElement.contentEditable == 'true')) {
  7781. return;
  7782. }
  7783. if (e.keyCode == 39) {
  7784. clickNext();
  7785. } else if (e.keyCode == 37) {
  7786. history.back();
  7787. }
  7788. };
  7789. document.addEventListener('keydown', manualModeKeyHandler);
  7790. pagetualNextHandler = () => {
  7791. clickNext();
  7792. };
  7793. document.addEventListener('pagetual.next', pagetualNextHandler, false);
  7794. return;
  7795. }
  7796. if (rulesData.arrowToScroll) {
  7797. keyupHandler = e => {
  7798. if (document.activeElement &&
  7799. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  7800. document.activeElement.contentEditable == 'true')) {
  7801. return;
  7802. }
  7803. if (e.keyCode == 39) {
  7804. let nextPageBar=getPageBar().nextBar;
  7805. if (nextPageBar) {
  7806. scrollToPageBar(nextPageBar);
  7807. } else {
  7808. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  7809. window.scrollTo({ top: scrollTop + (window.innerHeight || document.documentElement.clientHeight), behavior: 'instant'});
  7810. }
  7811. } else if (e.keyCode == 37) {
  7812. let prePageBar = getPageBar().preBar;
  7813. if (prePageBar) {
  7814. scrollToPageBar(prePageBar);
  7815. } else {
  7816. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  7817. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'instant'});
  7818. }
  7819. }
  7820. };
  7821. document.addEventListener('keyup', keyupHandler);
  7822. }
  7823. if (!ruleParser.curSiteRule.wheel) {
  7824. document.addEventListener('scroll', scrollHandler, true);
  7825. }
  7826. document.addEventListener('wheel', scrollHandler, true);
  7827. }
  7828.  
  7829. let hideTipsTimeout;
  7830. function showTips(content, href, time, wordColor, backColor) {
  7831. initView();
  7832. document.documentElement.appendChild(tipsWords);
  7833. tipsWords.style.color = wordColor || 0xFFFFFF;
  7834. tipsWords.style.backgroundColor = backColor || 0x000;
  7835. let _time = 1500;
  7836. if (href) {
  7837. _time = 3500;
  7838. tipsWords.innerHTML = createHTML(`<a href='${href}' target='_blank'>${content}</a>`);
  7839. tipsWords.style.pointerEvents = 'all';
  7840. } else {
  7841. tipsWords.innerHTML = createHTML(content);
  7842. }
  7843. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  7844. setTimeout(() => {
  7845. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  7846. }, 0);
  7847. setTimeout(() => {
  7848. tipsWords.style.opacity = 0.8;
  7849. clearTimeout(hideTipsTimeout);
  7850. hideTipsTimeout = setTimeout(() => {
  7851. tipsWords.style.opacity = 0;
  7852. tipsWords.style.pointerEvents = '';
  7853. }, time || _time);
  7854. }, 1);
  7855. }
  7856.  
  7857. const loadmoreReg = /^\s*((点击)?加载更多|(點擊)?加載更多|(load|view)\s*more|もっと読み込む)[.…▼\s]*$/i;
  7858. 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";
  7859. function getLoadMore(doc, loadmoreBtn) {
  7860. if (!loadmoreBtn || !getBody(doc).contains(loadmoreBtn) || /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  7861. if (!ruleParser.curSiteRule.smart && !ruleParser.curSiteRule.loadMore) return null;
  7862. if (loadmoreBtn) return loadmoreBtn;
  7863. let btnSel = ruleParser.curSiteRule.loadMore || defaultLoadmoreSel;
  7864. if (btnSel) {
  7865. loadmoreBtn = getElement(btnSel, doc, null, true);
  7866. }
  7867. if (!loadmoreBtn) {
  7868. let buttons = doc.querySelectorAll("input,button,a,div[onclick]");
  7869. for (let i = 0; i < buttons.length; i++) {
  7870. let button = buttons[i];
  7871. if (!button.innerText || button.innerText.length > 20) continue;
  7872. if (button && loadmoreReg.test(button.innerText)) {
  7873. loadmoreBtn = button;
  7874. break;
  7875. }
  7876. }
  7877. }
  7878. if (loadmoreBtn && !ruleParser.curSiteRule.loadMore && loadmoreBtn.dataset.ajax !== "true") {
  7879. let href = loadmoreBtn.getAttribute("href");
  7880. if (href && href != "/" && !ruleParser.hrefIsJs(href)) {
  7881. loadmoreBtn = null;
  7882. }
  7883. }
  7884. if (loadmoreBtn && /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  7885. if (loadmoreBtn) debug(loadmoreBtn, 'Load more button');
  7886. return loadmoreBtn;
  7887. }
  7888.  
  7889. var targetY = -1;
  7890. function scrollToPageBar(bar) {
  7891. if (window.pageYOffset == 0) {
  7892. bar.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" });
  7893. } else {
  7894. let yOffset = -20;
  7895. if (typeof ruleParser.curSiteRule.pageBarTop !== 'undefined') {
  7896. yOffset = -ruleParser.curSiteRule.pageBarTop;
  7897. }
  7898. targetY = bar.getBoundingClientRect().top + window.pageYOffset + yOffset;
  7899. window.scrollTo({ top: targetY, behavior: 'smooth'});
  7900. }
  7901. }
  7902.  
  7903. const pageNumReg=/[&\/\?](p=|page[=\/_-]?)\d+|[_-]\d+\./;
  7904. function createPageBar(url) {
  7905. curPage++;
  7906. sideController.setup();
  7907. let posEle = null;
  7908. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7909. let insert = ruleParser.getInsert();
  7910. if (!insert || !insert.parentNode) return;
  7911. if (forceState == 2) {
  7912. posEle = getBody(document);
  7913. posEle = posEle.children[posEle.children.length - 1];
  7914. } else {
  7915. posEle = insert;
  7916. }
  7917. while (posEle && !posEle.offsetParent) {
  7918. posEle = posEle.previousElementSibling || posEle.parentNode;
  7919. }
  7920. if (posEle) {
  7921. let actualBottom = getElementBottom(posEle);
  7922. bottomGap = scrollH - actualBottom + (window.innerHeight || document.documentElement.clientHeight) * rate;
  7923. if (bottomGap < 100) bottomGap = 100;
  7924. } else {
  7925. bottomGap = 1000;
  7926. }
  7927. if (rulesData.opacity == 0 || ruleParser.curSiteRule.pageBar === 0) return null;
  7928. url = url.replace(/#p{.*/, "");
  7929. let example = (ruleParser.curSiteRule.insertPos == 2 || ruleParser.curSiteRule.insertPos == "in") ? insert.children[0] : (insert.parentNode.children[0] || insert);
  7930. while (example && (compareNodeName(example, ["script", "style"]) || example.className == "pagetual_pageBar")) {
  7931. example = example.nextElementSibling;
  7932. }
  7933. if (!example || !example.parentNode) example = insert;
  7934. if (example.nodeType != 1) {
  7935. example = example.previousElementSibling || example.parentNode;
  7936. if (!example || example.nodeType != 1) return;
  7937. }
  7938. let exampleStyle = _unsafeWindow.getComputedStyle(example);
  7939. let inTable, inLi;
  7940. if (forceState == 2) {
  7941. inTable = inLi = false;
  7942. } else {
  7943. inTable = compareNodeName(example.parentNode, ["table", "tbody"]) ||
  7944. compareNodeName(example, ["tr", "tbody"]) ||
  7945. exampleStyle.display == "table-row" ||
  7946. (example.nextElementSibling && compareNodeName(example.nextElementSibling, ["tr", "tbody"]));
  7947. inLi = compareNodeName(example, ["li"]) || (example.nextElementSibling && compareNodeName(example.nextElementSibling, ["li"]));
  7948. }
  7949. let pageBar = document.createElement(inTable ? "tr" : (inLi ? "li" : "div"));
  7950. let upSpan = document.createElement("span");
  7951. let downSpan = document.createElement("span");
  7952. let pageText = document.createElement("a");
  7953. let pageNum;
  7954. pageBar.className = isHideBar ? "pagetual_pageBar hide" : "pagetual_pageBar";
  7955. pageBar.id = "pagetual_pageBar" + curPage;
  7956. pageBar.setAttribute("translate", "no");
  7957. if (isPause) {
  7958. pageBar.classList.add("stop");
  7959. }
  7960. pageBar.style.cssText = pageBarStyle;
  7961. pageBar.title = i18n(isPause ? "enable" : "disable");
  7962. upSpan.innerHTML = createHTML(upSvg);
  7963. upSpan.children[0].style.cssText = upSvgCSS;
  7964. upSpan.title = i18n("toTop");
  7965. downSpan.innerHTML = createHTML(downSvg);
  7966. downSpan.children[0].style.cssText = downSvgCSS;
  7967. downSpan.title = i18n("toBottom");
  7968. upSpan.style.cssText = initStyle;
  7969. downSpan.style.cssText = initStyle;
  7970. pageText.href = url;
  7971. pageText.style.cssText = pageTextStyle;
  7972. pageText.title = i18n("current");
  7973. if (openInNewTab == 1) pageText.target = "_blank";
  7974. pageBar.appendChild(upSpan);
  7975. pageBar.appendChild(pageText);
  7976. let touched = false;
  7977. let touchBodyHandler = e => {
  7978. touched = false;
  7979. getBody(document).removeEventListener('touchstart', touchBodyHandler, { passive: false, capture: false });
  7980. };
  7981. pageText.addEventListener("touchstart", e => {
  7982. if (touched) return;
  7983. touched = true;
  7984. pageText.style.pointerEvents = 'none';
  7985. setTimeout(() => {
  7986. pageText.style.pointerEvents = 'all';
  7987. }, 250);
  7988. getBody(document).addEventListener("touchstart", touchBodyHandler, { passive: false, capture: false });
  7989. }, { passive: false, capture: false });
  7990. if (ruleParser.nextTitle) {
  7991. pageText.innerHTML = createHTML(ruleParser.nextTitle + " ");
  7992. pageText.title = ruleParser.nextTitle;
  7993. }
  7994. if (ruleParser.curSiteRule.pageNum || pageNumReg.test(url)) {
  7995. pageText.innerHTML = createHTML(pageText.innerHTML + i18n("page"));
  7996. pageNum = document.createElement("span");
  7997. let num = ruleParser.getPageNumFromUrl(url, curPage);
  7998. pageNum.innerHTML = createHTML(num + "<i style='font-size: 0;'>&nbsp;</i>");
  7999. pageNum.className = "pagetual_pageNum";
  8000. pageNum.title = i18n("inputPageNum");
  8001. pageNum.style.cssText = pageTextStyle;
  8002. pageNum.style.cursor = "pointer";
  8003. pageNum.style.color = "";
  8004. pageNum.style.marginLeft = "5px";
  8005. pageNum.addEventListener("click", e => {
  8006. let pageInput = prompt(i18n("inputPageNum"), num || "1");
  8007. if (pageInput) {
  8008. let localPageBar = document.querySelector("#pagetual_pageBar" + pageInput);
  8009. if (localPageBar) {
  8010. scrollToPageBar(localPageBar);
  8011. } else {
  8012. let pageLink = ruleParser.getLinkByPage(url, pageInput);
  8013. if (pageLink) {
  8014. _GM_openInTab(pageLink, {active:true});
  8015. }
  8016. }
  8017. }
  8018. e.preventDefault();
  8019. e.stopPropagation();
  8020. });
  8021. pageBar.appendChild(pageNum);
  8022. } else {
  8023. pageText.innerHTML = createHTML(pageText.innerHTML + i18n("page") + curPage + "<i style='font-size: 0;'>&nbsp;</i>");
  8024. }
  8025. let preBtn = document.createElement("span");
  8026. preBtn.innerHTML = createHTML("∧");
  8027. preBtn.title = i18n("prevPage");
  8028. preBtn.className = "prevScreen";
  8029. 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; ";
  8030. let nextBtn = document.createElement("span");
  8031. nextBtn.innerHTML = createHTML("∨");
  8032. nextBtn.title = i18n("nextPage");
  8033. nextBtn.className = "nextScreen";
  8034. 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; ";
  8035. let localPage = curPage;
  8036. preBtn.addEventListener("click", e => {
  8037. e.stopPropagation();
  8038. e.preventDefault();
  8039. let prePageBar = document.querySelector("#pagetual_pageBar" + (localPage - 1));
  8040. if (prePageBar) {
  8041. scrollToPageBar(prePageBar);
  8042. } else {
  8043. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  8044. targetY = scrollTop - (window.innerHeight || document.documentElement.clientHeight);
  8045. window.scrollTo({ top: targetY, behavior: 'smooth'});
  8046. }
  8047. });
  8048. nextBtn.addEventListener("click", e => {
  8049. e.stopPropagation();
  8050. e.preventDefault();
  8051. let nextPageBar = document.querySelector("#pagetual_pageBar" + (localPage + 1));
  8052. if (nextPageBar) {
  8053. scrollToPageBar(nextPageBar);
  8054. } else {
  8055. scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  8056. targetY = scrollH || 9999999;
  8057. window.scrollTo({ top: targetY, behavior: 'smooth'});
  8058. }
  8059. });
  8060. if (!rulesData.hideBarArrow) {
  8061. pageText.insertBefore(preBtn, pageText.firstChild);
  8062. pageText.insertBefore(nextBtn, pageText.firstChild);
  8063. }
  8064. if (curForceIframe) {
  8065. let bgRing = document.createElement("span");
  8066. bgRing.className = "refreshRing";
  8067. bgRing.style.display = "none";
  8068. bgRing.innerHTML = createHTML(upSvg);
  8069. pageText.title = "Refresh";
  8070. pageText.appendChild(bgRing);
  8071. pageText.addEventListener("click", e => {
  8072. e.stopPropagation();
  8073. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  8074. e.preventDefault();
  8075. let nextEle = pageBar && pageBar.nextElementSibling;
  8076. if (nextEle && nextEle.name == 'pagetual-iframe') {
  8077. if (curForceIframe == nextEle) {
  8078. nextEle.setAttribute("loaded", "refresh");
  8079. }
  8080. nextEle.src = nextEle.src;
  8081. }
  8082. });
  8083. } else if (rulesData.pageBarMenu) {
  8084. pageText.addEventListener("click", e => {
  8085. e.stopPropagation();
  8086. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  8087. e.preventDefault();
  8088. picker.start();
  8089. });
  8090. }
  8091. pageBar.appendChild(downSpan);
  8092. if (forceState == 2) {
  8093. pageBar.style.width = "99%";
  8094. } else {
  8095. let parentStyle = _unsafeWindow.getComputedStyle(example.parentNode);
  8096. let parentWidth = example.parentNode.offsetWidth || parseInt(parentStyle.width);
  8097. pageBar.style.width = parentWidth - parseInt(parentStyle.paddingLeft) - parseInt(parentStyle.paddingRight) - 10 + "px";
  8098. pageBar.style.margin = '10px 5px';
  8099. if (parentStyle.display == "grid" || parentStyle.display == "inline-grid") {
  8100. pageBar.style.gridColumn = "1/-1";
  8101. }
  8102. if (inTable) {
  8103. example = compareNodeName(example, ["tr", "tbody"]) ? example : example.nextElementSibling || example;
  8104. if (compareNodeName(example, ["tbody"])) example = example.querySelector("tr");
  8105. let nextTr = example;
  8106. while (nextTr && nextTr.children.length == 0) nextTr = nextTr.nextElementSibling;
  8107. if (nextTr) example = nextTr;
  8108. let tdNum = 0;
  8109. if (exampleStyle.display == "table-row") {
  8110. [].forEach.call(example.children, el => {
  8111. tdNum += el.colSpan || 1;
  8112. });
  8113. } else {
  8114. [].forEach.call(example.children, el => {
  8115. if (compareNodeName(el, ["td", "th"])) {
  8116. tdNum += el.colSpan || 1;
  8117. }
  8118. });
  8119. }
  8120. pageBar.style.cssText = "";
  8121. pageBar.style.display = "table-row";
  8122. pageBar.style.backgroundColor = "unset";
  8123. pageBar.style.lineHeight = "20px";
  8124. pageBar.style.boxShadow = "";
  8125. let td = document.createElement("td");
  8126. td.colSpan = tdNum || 1;
  8127. let inTd = document.createElement("div");
  8128. inTd.style.cssText = pageBarStyle;
  8129. inTd.style.display = "";
  8130. inTd.className = pageBar.className;
  8131. pageBar.className = "";
  8132. inTd.appendChild(upSpan);
  8133. inTd.appendChild(pageText);
  8134. if (pageNum) inTd.appendChild(pageNum);
  8135. inTd.appendChild(downSpan);
  8136. td.appendChild(inTd);
  8137. pageBar.appendChild(td);
  8138. } else if (inLi) {
  8139. example = compareNodeName(example, ["li"]) ? example : example.nextElementSibling || example;
  8140. pageBar.style.opacity = 1;
  8141. pageBar.style.display = getComputedStyle(example).display;
  8142. pageBar.style.backgroundColor = "unset";
  8143. pageBar.style.lineHeight = "20px";
  8144. pageBar.style.boxShadow = "";
  8145. pageBar.style.border = "";
  8146. pageBar.style.width = "";
  8147. pageBar.style.maxWidth = "unset";
  8148. pageBar.style.flex = "auto";
  8149. let inTd = document.createElement("div");
  8150. inTd.style.cssText = pageBarStyle;
  8151. inTd.style.display = "";
  8152. inTd.style.margin = "0"
  8153. inTd.style.padding = "0 0";
  8154. inTd.style.textAlign = "center";
  8155. inTd.style.minWidth = "150px";
  8156. inTd.style.width = 'calc(100% - 20px)';
  8157. inTd.className = pageBar.className;
  8158. pageBar.className = "";
  8159. inTd.appendChild(upSpan);
  8160. inTd.appendChild(pageText);
  8161. if (pageNum) inTd.appendChild(pageNum);
  8162. inTd.appendChild(downSpan);
  8163. if (pageBar.style.display === 'table-row') {
  8164. let td = document.createElement("td");
  8165. td.colSpan = example.children.length;
  8166. td.style.width = '100%';
  8167. td.appendChild(inTd);
  8168. pageBar.appendChild(td);
  8169. } else {
  8170. inTd.style.width = '100%';
  8171. pageBar.appendChild(inTd);
  8172. }
  8173. }
  8174. }
  8175.  
  8176. upSpan.addEventListener("click", e => {
  8177. getBody(document).scrollTop = 0;
  8178. document.documentElement.scrollTop = 0;
  8179. e.preventDefault();
  8180. e.stopPropagation();
  8181. });
  8182. downSpan.addEventListener("click", e => {
  8183. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  8184. changeStop(true, true);
  8185. }
  8186. pageBar.title = i18n(isPause ? "enable" : "disable");
  8187. scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  8188. getBody(document).scrollTop = scrollH || 9999999;
  8189. document.documentElement.scrollTop = scrollH || 9999999;
  8190. e.preventDefault();
  8191. e.stopPropagation();
  8192. });
  8193. pageBar.addEventListener("click", e => {
  8194. changeStop(!isPause, true);
  8195. pageBar.title = i18n(isPause ? "enable" : "disable");
  8196. });
  8197. ruleParser.insertElement(pageBar);
  8198. ruleParser.runPageBar(pageBar);
  8199.  
  8200. return pageBar;
  8201. }
  8202.  
  8203. async function waitForElement(sel, doc) {
  8204. if (!sel) return null;
  8205. return new Promise((resolve) => {
  8206. let checkInv = setInterval(() => {
  8207. let result = getElement(sel, doc, null, true);
  8208. if (result) {
  8209. clearInterval(checkInv);
  8210. resolve(result);
  8211. }
  8212. }, 100);
  8213. });
  8214. }
  8215.  
  8216. async function clickAction(sel, doc) {
  8217. let btn = await waitForElement(sel, doc);
  8218. emuClick(btn, doc);
  8219. }
  8220.  
  8221. async function enterAction(sel, doc) {
  8222. let btn = await waitForElement(sel, doc);
  8223. let eventParam = { key: "Enter", keyCode: 13, bubbles: true };
  8224. let event = new KeyboardEvent('keydown', eventParam);
  8225. btn.dispatchEvent(event);
  8226. event = new KeyboardEvent('keyup', eventParam);
  8227. btn.dispatchEvent(event);
  8228. event = new KeyboardEvent('keypress', eventParam);
  8229. btn.dispatchEvent(event);
  8230. }
  8231.  
  8232. async function inputAction(sel, v, doc) {
  8233. let input = await waitForElement(sel, doc);
  8234. let event = new Event('focus', { bubbles: true });
  8235. input.dispatchEvent(event);
  8236. let lastValue = input.value;
  8237. if (input.nodeName.toUpperCase() == "INPUT") {
  8238. var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
  8239. nativeInputValueSetter.call(input, v);
  8240. } else if (input.nodeName.toUpperCase() == "TEXTAREA") {
  8241. var nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
  8242. nativeTextareaValueSetter.call(input, v);
  8243. } else {
  8244. input.innerHTML = createHTML(v);
  8245. }
  8246. event = new Event('input', { bubbles: true });
  8247. let tracker = input._valueTracker;
  8248. if (tracker) {
  8249. tracker.setValue(lastValue);
  8250. }
  8251. input.dispatchEvent(event);
  8252. event = new Event('change', { bubbles: true });
  8253. input.dispatchEvent(event);
  8254. debug(input, `input ${sel}`);
  8255. }
  8256.  
  8257. function emuClick(btn, doc) {
  8258. if (!doc) doc = document;
  8259. let curScroll = getBody(doc).scrollTop || doc.documentElement.scrollTop;
  8260. let orgHref = btn.getAttribute('href');
  8261. if (orgHref && orgHref.replace(location.origin + location.pathname, "").indexOf("#") === 0) {
  8262. let hashAction = e => {
  8263. e.preventDefault();
  8264. getBody(doc).scrollTop = curScroll;
  8265. doc.documentElement.scrollTop = curScroll;
  8266. btn.removeEventListener('click', hashAction, false);
  8267. };
  8268. btn.addEventListener('click', hashAction, false);
  8269. }
  8270. if (!PointerEvent) return btn.click();
  8271. let eventParam = {
  8272. isTrusted: true,
  8273. altKey: false,
  8274. azimuthAngle: 0,
  8275. bubbles: true,
  8276. button: 0,
  8277. buttons: 0,
  8278. clientX: 1,
  8279. clientY: 1,
  8280. cancelBubble: false,
  8281. cancelable: true,
  8282. composed: true,
  8283. ctrlKey: false,
  8284. defaultPrevented: false,
  8285. detail: 1,
  8286. eventPhase: 2,
  8287. fromElement: null,
  8288. height: 1,
  8289. isPrimary: false,
  8290. metaKey: false,
  8291. pointerId: 1,
  8292. pointerType: "mouse",
  8293. pressure: 0,
  8294. relatedTarget: null,
  8295. returnValue: true,
  8296. shiftKey: false,
  8297. toElement: null,
  8298. twist: 0,
  8299. which: 1
  8300. };
  8301. let mouseEvent = new PointerEvent("mousedown", eventParam);
  8302. btn.dispatchEvent(mouseEvent);
  8303. mouseEvent = new PointerEvent("mouseup", eventParam);
  8304. btn.dispatchEvent(mouseEvent);
  8305. let dispatchTouchEvent = (ele, type) => {
  8306. let touchEvent;
  8307. try {
  8308. touchEvent = document.createEvent('TouchEvent')
  8309. touchEvent.initTouchEvent(type, true, true)
  8310. } catch (err) {
  8311. try {
  8312. touchEvent = document.createEvent('UIEvent')
  8313. touchEvent.initUIEvent(type, true, true)
  8314. } catch (err) {
  8315. touchEvent = document.createEvent('Event')
  8316. touchEvent.initEvent(type, true, true)
  8317. }
  8318. }
  8319. if (touchEvent) {
  8320. try {
  8321. touchEvent.targetTouches = [{
  8322. pageX: 1,
  8323. pageY: 1,
  8324. clientX: 1,
  8325. clientY: 1,
  8326. target: btn
  8327. }];
  8328. touchEvent.touches = [{
  8329. pageX: 1,
  8330. pageY: 1,
  8331. clientX: 1,
  8332. clientY: 1,
  8333. target: btn
  8334. }];
  8335. touchEvent.changedTouches = [{
  8336. pageX: 1,
  8337. pageY: 1,
  8338. clientX: 1,
  8339. clientY: 1,
  8340. target: btn
  8341. }];
  8342. } catch (err) {}
  8343. ele.dispatchEvent(touchEvent);
  8344. }
  8345. }
  8346. dispatchTouchEvent(btn, "touchstart");
  8347. dispatchTouchEvent(btn, "touchend");
  8348.  
  8349. btn.click();
  8350. }
  8351.  
  8352. function emuInput(input, v) {
  8353. let result = false;
  8354. if (!input) return true;
  8355. let event = new Event('focus', { bubbles: true });
  8356. input.dispatchEvent(event);
  8357. let lastValue = input.value;
  8358. if (input.type == 'file') {
  8359. let file = v;
  8360. let blob = new Blob([file], {
  8361. type: 'text/plain'
  8362. });
  8363. file = new File([blob], 'noname.txt', { type: blob.type });
  8364. let dataTransfer = new DataTransfer();
  8365. dataTransfer.items.add(file);
  8366. input.files = dataTransfer.files;
  8367. v = "c:/fakepath/fakefile";
  8368. } else if (/INPUT/i.test(input.nodeName)) {
  8369. var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
  8370. nativeInputValueSetter.call(input, v);
  8371. } else if (/SELECT/i.test(input.nodeName)) {
  8372. var nativeSelectValueSetter = Object.getOwnPropertyDescriptor(window.HTMLSelectElement.prototype, "value").set;
  8373. nativeSelectValueSetter.call(input, v);
  8374. } else if (input.nodeName.toUpperCase() == "TEXTAREA") {
  8375. var nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
  8376. nativeTextareaValueSetter.call(input, v);
  8377. } else {
  8378. input.innerHTML = createHTML(v);
  8379. }
  8380. event = new Event('input', { bubbles: true });
  8381. let tracker = input._valueTracker;
  8382. if (tracker) {
  8383. tracker.setValue(lastValue);
  8384. }
  8385. input.dispatchEvent(event);
  8386. event = new Event('change', { bubbles: true });
  8387. input.dispatchEvent(event);
  8388. return result;
  8389. }
  8390.  
  8391. var failFromIframe = 0;
  8392. var inCors = false;
  8393. var checkRemoveIntv;
  8394. function requestFromIframe(url, callback){
  8395. if (location.protocol === 'https:' && !/^https:/.test(url)) {
  8396. ruleParser.noValidContent(url);
  8397. }
  8398. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  8399. let iframe = document.createElement('iframe');
  8400. iframe.name = 'pagetual-iframe';
  8401. iframe.width = '100%';
  8402. iframe.height = '1000';
  8403. iframe.frameBorder = '0';
  8404. if (ruleParser.curSiteRule.sandbox != false) {
  8405. iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  8406. }
  8407. 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;';
  8408. let waitTime = 100, checkEval;
  8409. ruleParser.runWait((_checkEval, _waitTime) => {
  8410. if (_checkEval) {
  8411. checkEval = _checkEval;
  8412. }
  8413. if (_waitTime) {
  8414. waitTime = _waitTime;
  8415. }
  8416. });
  8417. if (checkRemoveIntv) clearInterval(checkRemoveIntv);
  8418. checkRemoveIntv = setInterval(() => {
  8419. if (!iframe || !getBody(document).contains(iframe)) {
  8420. clearInterval(checkRemoveIntv);
  8421. loadPageOver();
  8422. }
  8423. }, 500);
  8424. let loadedHandler = async e => {
  8425. if (e.data != 'pagetual-iframe:DOMLoaded' && e.type != 'load') return;
  8426. clearInterval(checkRemoveIntv);
  8427. window.removeEventListener('message', loadedHandler, false);
  8428. iframe.removeEventListener('load', loadedHandler, false);
  8429. let pageEleTryTimes = 0;
  8430. async function checkIframe() {
  8431. if (urlChanged || isPause) {
  8432. return callback(false, false);
  8433. }
  8434. try {
  8435. let doc = iframe.contentDocument || iframe.contentWindow.document;
  8436. if (checkEval && !await checkEval(doc)) {
  8437. setTimeout(() => {
  8438. checkIframe();
  8439. }, waitTime);
  8440. return;
  8441. } else {
  8442. let preCode = ruleParser.curSiteRule.pagePre, eles = null;
  8443. if (preCode) {
  8444. try {
  8445. let preResult;
  8446. if (typeof preCode == 'function') {
  8447. preResult = await preCode(doc.documentElement.innerHTML, doc);
  8448. } else if (preCode.length == 2) {
  8449. preResult = doc.documentElement.innerHTML.replace(new RegExp(preCode[0], "gi"), preCode[1]);
  8450. } else {
  8451. preResult = await new AsyncFunction("response", "doc", '"use strict";' + preCode)(doc.documentElement.innerHTML, doc);
  8452. }
  8453. if (typeof preResult !== "undefined") {
  8454. if (typeof preResult === "string") {
  8455. doc.documentElement.innerHTML = preResult;
  8456. } else eles = preResult;
  8457. }
  8458. } catch(e) {
  8459. debug(e);
  8460. }
  8461. }
  8462. let base = doc.querySelector("base");
  8463. ruleParser.basePath = base ? base.href : url;
  8464. if (eles === null) eles = ruleParser.getPageElement(doc, iframe.contentWindow, pageEleTryTimes < 25);
  8465. if (eles && eles.length > 0) {
  8466. await ruleParser.hookUrl(doc);
  8467. await callback(doc, eles);
  8468. } else if (pageEleTryTimes++ < 100) {
  8469. getBody(doc).scrollTop = 9999999;
  8470. doc.documentElement.scrollTop = 9999999;
  8471. setTimeout(() => {
  8472. checkIframe();
  8473. }, waitTime);
  8474. return;
  8475. } else {
  8476. if (failFromIframe++ > 2) {
  8477. failFromIframe = 0;
  8478. debug("Stop as failFromIframe");
  8479. changeStop(true);
  8480. callback(false, false);
  8481. } else {
  8482. ruleParser.noValidContent(url);
  8483. callback(false, false);
  8484. }
  8485. }
  8486. }
  8487. } catch(e) {
  8488. inCors = true;
  8489. if (forceState === 3) {
  8490. debug("Stop as cors");
  8491. isPause = true;
  8492. }
  8493. if (!ruleParser.curSiteRule.pageElement) {
  8494. ruleParser.curSiteRule.pageElement = allOfBody;
  8495. ruleParser.getInsert(true);
  8496. }
  8497. ruleParser.curSiteRule.action = 0;
  8498. ruleParser.nextLinkHref = url;
  8499. callback(false, false);
  8500. nextPage();
  8501. }
  8502. if (iframe && iframe.parentNode) iframe.parentNode.removeChild(iframe);
  8503. }
  8504. setTimeout(() => {
  8505. checkIframe();
  8506. }, waitTime);
  8507. };
  8508. let code = ruleParser.curSiteRule.iframeInit;
  8509. if (code) {
  8510. let checkReady = setInterval(() => {
  8511. let doc;
  8512. try {
  8513. doc = iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document);
  8514. } catch(e) {
  8515. clearInterval(checkReady);
  8516. return;
  8517. }
  8518. if (doc) {
  8519. clearInterval(checkReady);
  8520. try {
  8521. Function('win', 'iframe', '"use strict";' + code)(iframe.contentWindow, iframe);
  8522. } catch(e) {
  8523. debug(e);
  8524. }
  8525. }
  8526. }, 50);
  8527. }
  8528. window.addEventListener('message', loadedHandler, false);
  8529. iframe.addEventListener('load', loadedHandler, false);
  8530. iframe.src = url;
  8531. try {
  8532. getBody(document).appendChild(iframe);
  8533. } catch (e) {
  8534. return callback(false, false);
  8535. }
  8536. }
  8537.  
  8538. var emuIframe, lastActiveUrl, orgContent, meetCors = false;
  8539. function emuPage(callback) {
  8540. let orgPage = null, preContent = null, iframeDoc, checkTimes = 0, loadmoreBtn, pageEle, nextLink, loadmoreEnd = false, waitTimes = 80, changed = false;
  8541. function returnFalse(log) {
  8542. if (curPage > 1) {
  8543. if (rulesData.lastPageTips) showTips(i18n("lastPage"), "", 800);
  8544. _unsafeWindow.postMessage({
  8545. action: "lastPage",
  8546. command: 'pagetual'
  8547. }, '*');
  8548. } else {
  8549. sideController.remove();
  8550. }
  8551. debug(log);
  8552. isPause = true;
  8553. callback(false, false);
  8554. if (emuIframe && emuIframe.parentNode) {
  8555. emuIframe.parentNode.removeChild(emuIframe);
  8556. emuIframe = null;
  8557. }
  8558. }
  8559. function cloneStatus() {
  8560. if (!iframeDoc) return;
  8561. let inputs = document.querySelectorAll("input:not([type=button],[type=image],[type=reset],[type=submit])");
  8562. let selectOptions = document.querySelectorAll("select>option");
  8563. [...inputs].forEach(input => {
  8564. let sel = geneSelector(input, true, true);
  8565. let mirrorEle = iframeDoc.querySelector(sel);
  8566. if (!mirrorEle) return;
  8567. emuInput(mirrorEle, input.value);
  8568. });
  8569. [...selectOptions].forEach(option => {
  8570. let sel = geneSelector(option, true, true);
  8571. let mirrorEle = iframeDoc.querySelector(sel);
  8572. if (!mirrorEle) return;
  8573. let selected = option.selected;
  8574. mirrorEle.selected = !!selected;
  8575. mirrorEle.parentNode.dispatchEvent(new Event('change'));
  8576. });
  8577. }
  8578. async function checkPage() {
  8579. if (isPause) return loadPageOver();
  8580. try {
  8581. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  8582. } catch(e) {
  8583. returnFalse("Stop as cors");
  8584. return;
  8585. }
  8586.  
  8587. let waitTime = 200, checkEval;
  8588. ruleParser.runWait((_checkEval, _waitTime) => {
  8589. if (_checkEval) {
  8590. checkEval = _checkEval;
  8591. }
  8592. if (_waitTime) {
  8593. waitTime = _waitTime;
  8594. }
  8595. });
  8596.  
  8597. if (!orgPage) {
  8598. if (!loadmoreEnd) {
  8599. loadmoreBtn = getLoadMore(iframeDoc);
  8600. if (loadmoreBtn && isVisible(loadmoreBtn, emuIframe.contentWindow)) {
  8601. emuClick(loadmoreBtn, iframeDoc);
  8602. let intv = setInterval(() => {
  8603. loadmoreBtn = getLoadMore(iframeDoc);
  8604. if (!loadmoreBtn || !getBody(document).contains(loadmoreBtn) || !isVisible(loadmoreBtn, emuIframe.contentWindow)) {
  8605. clearInterval(intv);
  8606. loadmoreEnd = true;
  8607. setTimeout(() => {
  8608. checkPage();
  8609. }, 500);
  8610. } else if (isInViewPort(loadmoreBtn)) {
  8611. emuClick(loadmoreBtn, iframeDoc);
  8612. }
  8613. }, 200);
  8614. return;
  8615. } else {
  8616. loadmoreEnd = true;
  8617. }
  8618. }
  8619. if (checkEval && !await checkEval(iframeDoc)) {
  8620. waitTimes = 50;
  8621. setTimeout(() => {
  8622. checkPage();
  8623. }, waitTime);
  8624. return;
  8625. } else {
  8626. if (!nextLink || !nextLink.offsetParent) nextLink = await ruleParser.getNextLink(iframeDoc, true);
  8627. if (nextLink) pageEle = ruleParser.getPageElement(iframeDoc, emuIframe.contentWindow, true);
  8628. if (!pageEle || pageEle.length == 0 || !nextLink) {
  8629. getBody(iframeDoc).scrollTop = 9999999;
  8630. iframeDoc.documentElement.scrollTop = 9999999;
  8631. if (waitTimes-- > 0) {
  8632. setTimeout(() => {
  8633. checkPage();
  8634. }, waitTime);
  8635. return;
  8636. }
  8637. }
  8638. }
  8639. if (!pageEle || pageEle.length == 0) {
  8640. returnFalse("Stop as no page when emu");
  8641. return;
  8642. }
  8643. pageEle = [].filter.call(pageEle, ele => {return ele && !compareNodeName(ele, ["style", "script", "meta"])});
  8644. if (compareNodeName(pageEle[0], ["ul"]) || pageEle.length == 1) pageEle = pageEle[0];
  8645. else if (pageEle[0].parentNode == pageEle[1].parentNode) {
  8646. pageEle = pageEle[0].parentNode;
  8647. } else {
  8648. pageEle = pageEle[0];
  8649. }
  8650. if (ruleParser.curSiteRule.smart && orgContent != pageEle.innerHTML) {
  8651. orgContent = pageEle.innerHTML;
  8652. if (waitTimes-- > 0) {
  8653. setTimeout(() => {
  8654. checkPage();
  8655. }, 500);
  8656. return;
  8657. }
  8658. }
  8659. orgPage = pageEle;
  8660. if (nextLink) {
  8661. if (compareNodeName(orgPage, ["img"])) {
  8662. if (!ruleParser.curSiteRule.lazyImgSrc) ruleParser.curSiteRule.lazyImgSrc = "0";
  8663. if (orgPage.src) {
  8664. orgContent = orgPage.src;
  8665. } else {
  8666. setTimeout(() => {
  8667. checkPage();
  8668. }, 500);
  8669. return;
  8670. }
  8671. } else {
  8672. orgContent = orgPage.innerHTML;
  8673. }
  8674. preContent = orgContent;
  8675. if (!isVisible(nextLink, emuIframe.contentWindow)) {
  8676. returnFalse("Stop as next hide when emu");
  8677. } else {
  8678. emuClick(nextLink, iframeDoc);
  8679. setTimeout(() => {
  8680. checkPage();
  8681. }, 500);
  8682. }
  8683. } else {
  8684. returnFalse("Stop as no next when emu");
  8685. }
  8686. return;
  8687. }
  8688. if (!ruleParser.checkStopSign(nextLink, iframeDoc)) {
  8689. return returnFalse("Stop as stopSign");
  8690. }
  8691. if (checkTimes++ > 200) {
  8692. returnFalse("Stop as timeout when emu");
  8693. return;
  8694. }
  8695. if (checkEval && !await checkEval(iframeDoc)) {
  8696. checkTimes = 0;
  8697. setTimeout(() => {
  8698. checkPage();
  8699. }, waitTime);
  8700. return;
  8701. }
  8702. let eles = ruleParser.getPageElement(iframeDoc, emuIframe.contentWindow, true), checkItem;
  8703. if (eles && eles.length > 0) {
  8704. eles = [].filter.call(eles, ele => {return ele && !compareNodeName(ele, ["style", "script", "meta"])});
  8705. if (compareNodeName(eles[0], ["ul"]) || eles.length == 1) checkItem = eles[0];
  8706. else if (eles[0].parentNode == eles[1].parentNode) {
  8707. checkItem = eles[0].parentNode;
  8708. } else {
  8709. checkItem = eles[0];
  8710. }
  8711. }
  8712. if (!checkItem) {
  8713. setTimeout(() => {
  8714. checkPage();
  8715. }, waitTime);
  8716. } else {
  8717. let checkInner;
  8718. if (compareNodeName(checkItem, ["img"])) {
  8719. if (checkItem.src) {
  8720. checkInner = checkItem.src;
  8721. } else {
  8722. setTimeout(() => {
  8723. checkPage();
  8724. }, waitTime);
  8725. return;
  8726. }
  8727. } else {
  8728. checkInner = checkItem.innerHTML;
  8729. }
  8730. if (orgPage != checkItem || checkInner != preContent) {
  8731. changed = true;
  8732. orgPage = checkItem;
  8733. preContent = checkInner;
  8734. setTimeout(() => {
  8735. checkPage();
  8736. }, 500);
  8737. } else if (changed) {
  8738. checkTimes = 0;
  8739. if (orgContent == preContent && (ruleParser.curSiteRule.smart || ruleParser.curSiteRule.stopSame)) {
  8740. returnFalse("Stop as same content");
  8741. } else {
  8742. orgContent = preContent;
  8743. await ruleParser.hookUrl(iframeDoc);
  8744. callback(iframeDoc, eles);
  8745. }
  8746. } else {
  8747. if (checkTimes % 10 === 5) {
  8748. if (!nextLink || !nextLink.offsetParent) {
  8749. nextLink = await ruleParser.getNextLink(iframeDoc, true);
  8750. }
  8751. if (nextLink) {
  8752. emuClick(nextLink, iframeDoc);
  8753. }
  8754. }
  8755. setTimeout(() => {
  8756. checkPage();
  8757. }, waitTime);
  8758. }
  8759. }
  8760. }
  8761. if (!emuIframe) {
  8762. let loaded = false;
  8763. emuIframe = document.createElement('iframe');
  8764. emuIframe.name = 'pagetual-iframe';
  8765. let notSetSandbox = typeof ruleParser.curSiteRule.sandbox == 'undefined';
  8766. if (notSetSandbox || ruleParser.curSiteRule.sandbox == true) {
  8767. emuIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  8768. } else if (ruleParser.curSiteRule.sandbox) {
  8769. emuIframe.sandbox = ruleParser.curSiteRule.sandbox;
  8770. }
  8771. emuIframe.width = '100%';
  8772. emuIframe.height = '100%';
  8773. emuIframe.frameBorder = '0';
  8774. 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;';
  8775. emuIframe.addEventListener("load", e => {
  8776. try {
  8777. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  8778. } catch(e) {
  8779. if (e.message && e.message.indexOf("cross-origin") != -1 && notSetSandbox && emuIframe.hasAttribute("sandbox")) {
  8780. emuIframe.removeAttribute("sandbox");
  8781. meetCors = true;
  8782. callback(false, false);
  8783. if (ruleParser.curSiteRule.smart) {
  8784. ruleParser.findNoNext();
  8785. }
  8786. } else {
  8787. returnFalse("Stop as cors");
  8788. }
  8789. return;
  8790. }
  8791. setTimeout(async () => {
  8792. if (meetCors && ruleParser.curSiteRule.smart) {
  8793. ruleParser.smartRules = ruleParser.smartRules.filter(item => {return item && item.url !== ruleParser.curSiteRule.url;});
  8794. storage.setItem("smartRules", ruleParser.smartRules);
  8795. }
  8796. meetCors = false;
  8797. let code = ruleParser.curSiteRule.init;
  8798. if (code) {
  8799. try {
  8800. 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)});
  8801. } catch(e) {
  8802. debug(e);
  8803. }
  8804. } else {
  8805. let refreshByClickSel = ruleParser.curSiteRule.refreshByClick;
  8806. if (iframeDoc && refreshByClickSel) {
  8807. let clickBtn = await waitForElement(refreshByClickSel, iframeDoc);
  8808. await sleep(500);
  8809. cloneStatus();
  8810. emuClick(clickBtn, iframeDoc);
  8811. await sleep(500);
  8812. }
  8813. }
  8814. if (loaded) return;
  8815. loaded = true;
  8816. checkPage();
  8817. }, 500);
  8818. });
  8819. let code = ruleParser.curSiteRule.iframeInit;
  8820. if (code) {
  8821. let checkReady = setInterval(() => {
  8822. try {
  8823. iframeDoc = emuIframe.contentDocument || (emuIframe.contentWindow && emuIframe.contentWindow.document);
  8824. } catch(e) {
  8825. clearInterval(checkReady);
  8826. return;
  8827. }
  8828. if (iframeDoc) {
  8829. clearInterval(checkReady);
  8830. try {
  8831. Function('win', 'iframe', '"use strict";' + code)(emuIframe.contentWindow, emuIframe);
  8832. } catch(e) {
  8833. debug(e);
  8834. }
  8835. }
  8836. }, 50);
  8837. }
  8838. if (!lastActiveUrl) lastActiveUrl = location.href;
  8839. emuIframe.src = lastActiveUrl;
  8840. getBody(document).appendChild(emuIframe);
  8841. } else {
  8842. if (emuIframe.src != lastActiveUrl || meetCors) {
  8843. emuIframe.src = lastActiveUrl;
  8844. return;
  8845. }
  8846. checkPage();
  8847. }
  8848. }
  8849.  
  8850. var scrollToResizeInited = false;
  8851. var resizePool = [];
  8852. var scrollingToResize = false;
  8853.  
  8854. function isTouchViewPort(element) {
  8855. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  8856. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  8857. const {
  8858. top,
  8859. right,
  8860. bottom,
  8861. left,
  8862. } = element.getBoundingClientRect();
  8863.  
  8864. return (
  8865. top < viewHeight &&
  8866. left < viewWidth &&
  8867. right > 0 &&
  8868. bottom > 0
  8869. );
  8870. }
  8871.  
  8872. function resizeIframe(iframe, frameDoc, pageEle) {
  8873. if (targetY >= 0) {
  8874. window.scrollTo({ top: targetY, behavior: 'instant'});
  8875. targetY = -1;
  8876. }
  8877. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  8878. if (ruleParser.curSiteRule.smart || forceState === 2) {
  8879. let height = (getBody(frameDoc).scrollHeight || getBody(frameDoc).offsetHeight || 500);
  8880. if (!iframe.style.height || parseInt(iframe.style.height) === 0 || height - parseInt(iframe.style.height) > window.innerHeight) {
  8881. iframe.style.height = height + "px";
  8882. iframe.style.minHeight = iframe.style.height;
  8883. }
  8884. iframe.style.width = "100%";
  8885. frameDoc.documentElement.scrollTop = 0;
  8886. frameDoc.documentElement.scrollLeft = 0;
  8887. } else {
  8888. if (pageEle) {
  8889. if (document.body.scrollWidth) frameDoc.documentElement.style.width = document.body.scrollWidth + "px";
  8890. let fitWidth = ruleParser.curSiteRule.fitWidth !== false;
  8891. let targetElement = pageEle[0];
  8892. if (!targetElement) return;
  8893. if (pageEle.length > 1) {
  8894. targetElement = targetElement.parentNode;
  8895. }
  8896. let scrollHeight = targetElement.scrollHeight || targetElement.offsetHeight || 500;
  8897. iframe.style.height = scrollHeight + "px";
  8898. let scrollTop = 0, scrollLeft = 0;
  8899. getBody(frameDoc).scrollTop = 0;
  8900. getBody(frameDoc).scrollLeft = 0;
  8901. while (targetElement && targetElement.offsetParent) {
  8902. targetElement.offsetParent.scrollTop = targetElement.offsetTop;
  8903. if (targetElement.offsetParent.scrollTop == 0) {
  8904. scrollTop += targetElement.offsetTop;
  8905. }
  8906. if (fitWidth) {
  8907. targetElement.offsetParent.scrollLeft = targetElement.offsetLeft;
  8908. if (targetElement.offsetParent.scrollLeft == 0) {
  8909. scrollLeft += targetElement.offsetLeft;
  8910. }
  8911. }
  8912. targetElement = targetElement.offsetParent;
  8913. }
  8914. frameDoc.documentElement.scrollTop = scrollTop;
  8915. frameDoc.documentElement.scrollLeft = scrollLeft;
  8916. if (frameDoc.documentElement.scrollTop == 0 && frameDoc.documentElement.scrollLeft == 0) {
  8917. getBody(frameDoc).scrollTop += scrollTop;
  8918. getBody(frameDoc).scrollLeft += scrollLeft;
  8919. }
  8920. if (!fitWidth && iframe.style.marginLeft == '0px') {
  8921. iframe.style.width = "100vw";
  8922. iframe.style.maxWidth = "100vw";
  8923. iframe.style.minWidth = "100vw";
  8924. var cWidth = document.body.clientWidth || document.documentElement.clientWidth;
  8925. var iWidth = window.innerWidth;
  8926. iframe.style.marginLeft = -iframe.getBoundingClientRect().left - (iWidth - cWidth) / 2 + "px";
  8927. }
  8928. }
  8929. }
  8930. let newScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  8931. if (newScroll != curScroll) {
  8932. getBody(document).scrollTop = curScroll;
  8933. document.documentElement.scrollTop = curScroll;
  8934. }
  8935. }
  8936.  
  8937. function scrollToResize(e) {
  8938. if (scrollingToResize) return;
  8939. else {
  8940. scrollingToResize = true;
  8941. let resizeHandler = () => {
  8942. let touched = 0;
  8943. for (let i = 0; i < resizePool.length; i++) {
  8944. let resizeArr = resizePool[i];
  8945. let iframe = resizeArr[1]();
  8946. if (isTouchViewPort(iframe)) {
  8947. touched++;
  8948. let pageEle = resizeArr[0]();
  8949. let frameDoc = resizeArr[2]();
  8950. resizeIframe(iframe, frameDoc, pageEle);
  8951. } else if (touched) {
  8952. if (touched == 1) {
  8953. let pageEle = resizeArr[0]();
  8954. let frameDoc = resizeArr[2]();
  8955. resizeIframe(iframe, frameDoc, pageEle);
  8956. }
  8957. break;
  8958. } else if (!iframe.parentNode) {
  8959. resizePool.splice(i, 1);
  8960. break;
  8961. }
  8962. }
  8963. };
  8964. setTimeout(() => {
  8965. scrollingToResize = false;
  8966. }, 300);
  8967. resizeHandler();
  8968. }
  8969. }
  8970.  
  8971. var curForceIframe;
  8972. function forceIframe(url, callback) {
  8973. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  8974. let curIframe = document.createElement('iframe'), iframeDoc, pageElement = null, inAction = true;
  8975. let loadedHandler = () => {
  8976. let getPageEle = () => {
  8977. if (ruleParser.curSiteRule.smart) {
  8978. return null;
  8979. } else {
  8980. if (!pageElement || pageElement.length === 0 || !pageElement[0].offsetParent) {
  8981. pageElement = ruleParser.getPageElement(iframeDoc, curIframe.contentWindow);
  8982. }
  8983. return pageElement;
  8984. }
  8985. };
  8986. resizeIframe(curIframe, iframeDoc, getPageEle());
  8987. let loaded = curIframe.getAttribute("loaded");
  8988. if (loaded == "true") {
  8989. return;
  8990. }
  8991. curIframe.setAttribute("loaded", "true");
  8992. let getIframe = () => {
  8993. return curIframe;
  8994. };
  8995. let getFrameDoc = () => {
  8996. return iframeDoc;
  8997. };
  8998. ruleParser.insertPage(iframeDoc, [], url, ele => {
  8999. callback(curIframe, loaded == "refresh");
  9000. inAction = false;
  9001. }, true);
  9002. if (!loaded) {
  9003. resizePool.push([getPageEle, getIframe, getFrameDoc]);
  9004. }
  9005. };
  9006. let checkIframeTimer = setInterval(() => {
  9007. if (!curIframe.parentNode) {
  9008. clearInterval(checkIframeTimer);
  9009. return curIframe.getAttribute("loaded") == "true" || callback(false);
  9010. }
  9011. }, 500);
  9012. let code = ruleParser.curSiteRule.iframeInit;
  9013. if (code) {
  9014. let checkReady = setInterval(() => {
  9015. try {
  9016. iframeDoc = curIframe.contentDocument || (curIframe.contentWindow && curIframe.contentWindow.document);
  9017. } catch(e) {
  9018. clearInterval(checkReady);
  9019. return;
  9020. }
  9021. if (iframeDoc) {
  9022. clearInterval(checkReady);
  9023. try {
  9024. Function('win', 'iframe', '"use strict";' + code)(curIframe.contentWindow, curIframe);
  9025. } catch(e) {
  9026. debug(e);
  9027. }
  9028. }
  9029. }, 50);
  9030. }
  9031. let waitTime = 300, checkEval;
  9032. ruleParser.runWait((_checkEval, _waitTime) => {
  9033. if (_checkEval) {
  9034. checkEval = _checkEval;
  9035. }
  9036. if (_waitTime) {
  9037. waitTime = _waitTime;
  9038. }
  9039. });
  9040. async function checkIframe() {
  9041. if (checkEval && !await checkEval(iframeDoc)) {
  9042. setTimeout(() => {
  9043. checkIframe();
  9044. }, waitTime);
  9045. return;
  9046. }
  9047. loadedHandler();
  9048. }
  9049. curIframe.name = 'pagetual-iframe';
  9050. curIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  9051. curIframe.frameBorder = '0';
  9052. curIframe.scrolling = "no";
  9053. 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;';
  9054. curIframe.addEventListener("load", async e => {
  9055. clearInterval(checkIframeTimer);
  9056. if (isPause) return callback(false);
  9057. try {
  9058. iframeDoc = curIframe.contentDocument || curIframe.contentWindow.document;
  9059. } catch(e) {
  9060. debug("Stop as cors");
  9061. isPause = true;
  9062. callback(false);
  9063. return;
  9064. }
  9065. let css = ruleParser.curSiteRule.css || rulesData.customCss;
  9066. if (css) {
  9067. let cssArr = css.split("inIframe:");
  9068. if (cssArr && cssArr.length > 1) {
  9069. let styleEle = iframeDoc.createElement("style");
  9070. styleEle.innerHTML = cssArr[1];
  9071. iframeDoc.head.appendChild(styleEle);
  9072. }
  9073. }
  9074. checkIframe();
  9075. iframeDoc.addEventListener('wheel', e => {
  9076. document.dispatchEvent(new Event('wheel'));
  9077. }, true);
  9078. });
  9079. let checkTimes = 0, findPageEle = false;
  9080. let forceRefresh = e => {
  9081. if (inAction || !iframeDoc) return;
  9082. inAction = true;
  9083. let foundNext = () => {
  9084. document.removeEventListener("scroll", forceRefresh);
  9085. }
  9086. setTimeout(async () => {
  9087. inAction = false;
  9088. if (!ruleParser.nextLinkHref && !isPause) {
  9089. checkTimes++;
  9090. await ruleParser.getNextLink(iframeDoc, true);
  9091. if (ruleParser.nextLinkHref) {
  9092. foundNext();
  9093. if (isLoading) isLoading = false;
  9094. } else if (checkTimes >= 10) {
  9095. foundNext();
  9096. } else if (checkTimes >= 3 && !findPageEle) {
  9097. if (!pageElement) pageElement = ruleParser.getPageElement(iframeDoc, curIframe.contentWindow);
  9098. if (!pageElement) {
  9099. inAction = true;
  9100. curIframe.contentWindow.location.reload();
  9101. } else {
  9102. findPageEle = true;
  9103. }
  9104. }
  9105. } else {
  9106. foundNext();
  9107. }
  9108. }, 100);
  9109. };
  9110. document.addEventListener("scroll", forceRefresh);
  9111. curIframe.src = url;
  9112. curForceIframe = curIframe;
  9113. let insert = ruleParser.getInsert();
  9114. let body = getBody(document);
  9115. let curScroll = body.scrollTop || document.documentElement.scrollTop;
  9116. if (forceState == 2) {
  9117. document.documentElement.appendChild(loadingDiv);
  9118. body.appendChild(curIframe);
  9119. let bodyStyle = getComputedStyle(body);
  9120. if (bodyStyle.display == "flex" || bodyStyle.display == "inline-flex") {
  9121. body.style.flexDirection = "column";
  9122. }
  9123. } else {
  9124. ruleParser.insertElement(curIframe);
  9125. }
  9126. body.scrollTop = curScroll;
  9127. document.documentElement.scrollTop = curScroll;
  9128.  
  9129. if (!scrollToResizeInited) {
  9130. scrollToResizeInited = true;
  9131. document.addEventListener("scroll", scrollToResize);
  9132. }
  9133. return curIframe;
  9134. }
  9135.  
  9136. function loadPageOver() {
  9137. isLoading = false;
  9138. stopScroll = true;
  9139. setTimeout(() => {stopScroll = false;}, 300);
  9140. if (loadingDiv.parentNode) {
  9141. loadingDiv.parentNode.removeChild(loadingDiv);
  9142. }
  9143. if (rate !== 1 && !clickMode) {
  9144. setTimeout(() => {
  9145. if (distToBottom() < bottomGap) {
  9146. nextPage();
  9147. }
  9148. }, 1);
  9149. }
  9150. }
  9151.  
  9152. function checkAutoLoadNum() {
  9153. if (autoLoadNum >= 0) {
  9154. if (autoLoadNum !== 0 && --autoLoadNum === 0) {
  9155. autoLoadNum = -1;
  9156. } else {
  9157. setTimeout(() => nextPage(), 1);
  9158. }
  9159. }
  9160. }
  9161.  
  9162. async function nextPage() {
  9163. if (isPause || isLoading || forceState === 1) return;
  9164. if (ruleParser.curSiteRule.delay) {
  9165. try {
  9166. let checkDelay = ((typeof ruleParser.curSiteRule.delay === 'function') ? ruleParser.curSiteRule.delay : Function('"use strict";' + ruleParser.curSiteRule.delay))();
  9167. if (!checkDelay) return;
  9168. } catch(e) {
  9169. debug(e);
  9170. }
  9171. }
  9172. let nextLink = ruleParser.nextLinkHref;
  9173. if (!nextLink) {
  9174. isLoading = true;
  9175. if (curPage === 1) {
  9176. await ruleParser.getNextLink(document, true);
  9177. nextLink = ruleParser.nextLinkHref;
  9178. }
  9179. if (!nextLink) {
  9180. if (curPage === 1) {
  9181. if (ruleParser.curSiteRule.pinUrl) {
  9182. setTimeout(() => {isLoading = false;}, 500);
  9183. } else if (tryTimes++ < 5) {
  9184. setTimeout(() => {isLoading = false;}, 1000);
  9185. } else {
  9186. ruleParser.findNoNext();
  9187. }
  9188. } else if (!showedLastPageTips) {
  9189. if (rulesData.lastPageTips) {
  9190. showTips(i18n("lastPage"), "", 800);
  9191. }
  9192. showedLastPageTips = true;
  9193. _unsafeWindow.postMessage({
  9194. action: "lastPage",
  9195. command: 'pagetual'
  9196. }, '*');
  9197. }
  9198. return;
  9199. }
  9200. isLoading = false;
  9201. }
  9202. showedLastPageTips = false;
  9203. let pvGallery = document.querySelector("span.pv-gallery-container");
  9204. if (pvGallery && pvGallery.style.display !== "none") return;
  9205. let insert = ruleParser.getInsert();
  9206. if (insert) {
  9207. if (curPage === 1) initView();
  9208. /*if (curPage == 1) {
  9209. window.postMessage({
  9210. command: 'pagetual.insert'
  9211. }, '*');
  9212. }*/
  9213. let isJs = ruleParser.curSiteRule.action == 3 || ruleParser.hrefIsJs(nextLink);
  9214. if (!isJs) {
  9215. emuIframe = null;
  9216. lastActiveUrl = nextLink;
  9217. if (location.protocol === "https:" && /^http:/.test(nextLink)) {
  9218. nextLink = nextLink.replace(/^http/, "https");
  9219. }
  9220. }
  9221. isLoading = true;
  9222. if (curPage !== 1 || !isJs || !ruleParser.curSiteRule.smart) {
  9223. ruleParser.beginLoading(loadingDiv);
  9224. }
  9225. let sleep = ruleParser.curSiteRule.sleep || 0;
  9226. setTimeout(() => {
  9227. if (ruleParser.curSiteRule.pageElementByJs) {
  9228. var over = eles => {
  9229. if (urlChanged || isPause) {
  9230. loadPageOver();
  9231. return;
  9232. }
  9233. if (eles) {
  9234. ruleParser.insertPage(document, eles, nextLink, () => {
  9235. createPageBar(nextLink);
  9236. checkAutoLoadNum();
  9237. }, true);
  9238. } else {
  9239. debug("Stop as no page when get by js");
  9240. isPause = true;
  9241. loadPageOver();
  9242. }
  9243. };
  9244. try {
  9245. ((typeof ruleParser.curSiteRule.pageElementByJs === 'function') ? ruleParser.curSiteRule.pageElementByJs : Function("over", "pageNum",'"use strict";' + ruleParser.curSiteRule.pageElementByJs))(over, curPage);
  9246. } catch(e) {
  9247. debug(e);
  9248. }
  9249. } else if ((forceState === 2 || ruleParser.curSiteRule.action == 2) && !isJs) {
  9250. forceIframe(nextLink, (iframe, refresh) => {
  9251. if (urlChanged || isPause) {
  9252. loadPageOver();
  9253. return;
  9254. }
  9255. if (!refresh) {
  9256. let pageBar = createPageBar(nextLink);
  9257. if (pageBar && iframe && iframe.parentNode) iframe.parentNode.insertBefore(pageBar, iframe);
  9258. }
  9259. loadPageOver();
  9260. checkAutoLoadNum();
  9261. });
  9262. } else if ((forceState === 3 || ruleParser.curSiteRule.action == 1) && !isJs) {
  9263. requestFromIframe(nextLink, async (doc, eles) => {
  9264. if (urlChanged || isPause) {
  9265. loadPageOver();
  9266. return;
  9267. }
  9268. if (eles) {
  9269. await ruleParser.insertPage(doc, eles, nextLink, () => {
  9270. createPageBar(nextLink);
  9271. checkAutoLoadNum();
  9272. }, true);
  9273. } else loadPageOver();
  9274. });
  9275. } else {
  9276. if (!isJs) {
  9277. requestDoc(nextLink, (eles) => {
  9278. if (urlChanged || isPause) {
  9279. loadPageOver();
  9280. return;
  9281. }
  9282. if (eles) {
  9283. createPageBar(nextLink);
  9284. checkAutoLoadNum();
  9285. } else loadPageOver();
  9286. });
  9287. } else {
  9288. emuPage((doc, eles) => {
  9289. if (urlChanged || isPause) {
  9290. loadPageOver();
  9291. return;
  9292. }
  9293. if (eles) {
  9294. ruleParser.insertPage(doc, eles, "", () => {
  9295. createPageBar(nextLink);
  9296. checkAutoLoadNum();
  9297. }, true);
  9298. } else loadPageOver();
  9299. });
  9300. }
  9301. }
  9302. }, sleep);
  9303. }
  9304. }
  9305.  
  9306. function init() {
  9307. if (document.readyState === 'loading' || document.readyState === 'uninitialized') {
  9308. let domReady = e => {
  9309. initRules(() => {
  9310. initPage();
  9311. });
  9312. document.removeEventListener("DOMContentLoaded", domReady, false);
  9313. };
  9314. document.addEventListener("DOMContentLoaded", domReady, false);
  9315. } else {
  9316. initRules(() => {
  9317. initPage();
  9318. });
  9319. }
  9320. }
  9321.  
  9322. function visibilitychangeHandler() {
  9323. document.removeEventListener('visibilitychange', visibilitychangeHandler);
  9324. init();
  9325. }
  9326.  
  9327. setTimeout(() => {
  9328. if (document.hidden) {
  9329. document.addEventListener('visibilitychange', visibilitychangeHandler);
  9330. } else {
  9331. init();
  9332. }
  9333. }, 300);
  9334. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址