东方永页机

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

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

  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.72
  14. // @description Perpetual pages - powerful auto-pager script. Auto fetching next paginated web pages and inserting into current page for infinite scroll. Support thousands of web sites without any rule.
  15. // @description:zh-CN 终极自动翻页 - 加载并拼接下一分页内容至当前页尾,智能适配任意网页
  16. // @description:zh-TW 終極自動翻頁 - 加載並拼接下一分頁內容至當前頁尾,智能適配任意網頁
  17. // @description:ja Webページを自動で読み込み継ぎ足し表示を行うブラウザ拡張です、次のページ付けされた Web ページの自動読み込みと現在のページへの挿入 ルールなしで何千もの Web サイトをサポートします。
  18. // @description:ko 페이지가 매겨진 다음 웹 페이지를 자동으로 로드하고 현재 페이지에 삽입합니다. 규칙 없이 수천 개의 웹 사이트를 지원합니다.
  19. // @description:ru Автоматическая подгрузка следующих страниц и вставка их содержимого в текущую страницу. Поддерживает тысячи сайтов даже с настройками по умолчанию.
  20. // @description:de Automatisches Laden der nächsten paginierten Webseiten und Einfügen in die aktuelle Seite. Unterstützen Sie Tausende von Websites ohne Regeln.
  21. // @description:es Carga automática de las siguientes páginas web paginadas e inserción en la página actual. Admite miles de sitios web sin ninguna regla.
  22. // @description:fr Chargement automatique des pages Web paginées suivantes et insertion dans la page en cours. Prend en charge des milliers de sites Web sans aucune règle.
  23. // @description:it Caricamento automatico delle pagine Web impaginate successive e inserimento nella pagina corrente. Supporta migliaia di siti web senza alcuna regola.
  24. // @author hoothin
  25. // @license MPL-2.0
  26. // @match *://*/*
  27. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAdVBMVEUAAAD3VU33VU32VEz8U073VU32VU33VU32VUz0Uk/3VE32VU32VUz2VU32VU32VU32VU33VU33U0z2VU34Wkv3VE32VUz/mpj/nJj2VUz2VU32VE33VEz2VU32VU32VUz3VE32VEz3VE3/mZf2Vkz2VU3/mpilFFolAAAAJXRSTlMA3Lp/GvTBT5YQLuawZ/DOyZwlPQeKc21N04+FX1bqpm9DNoB4T68ePwAAAitJREFUWMPt1tuasiAUBuCFCG5Rs3QybTPV1/1f4v/3PDkyIojn8x5qBrI+ltAfh32/yysmBKvyXb+njb6bDL9kzTd5SzjDAsYT8nFoGSxYe6BVqoNDp2jFDit25BRgVUAODB4YWcETWVTwVNGiGN5iWtBgg4YMCpsoI38dNunmmWyxUTvbPwwbsYR0fIzZLQ0pTG8eieRmBLMmpdH9uimQEf6TNRnXXKLZHixpJtywLzOgMHtFCqdM64DahHRnOE1dsrekm9wr2WtLcAlpdHwcp1pAJySXYnERclzp4+v19jXdmcTvQUJtz+ZaI4i05/V/UGYrCxbaAsOYoNfIKEQxpqQuzCgJJJ/3f42O8ywEZuMVWi/8hODxGj3GW2b0udkbGULLDOjimAG0S3fLGlBnXQM9irG1CiQdVQi0dqQsOSDlyEEz7Vy9OxxfR71VCXsSB23jMrKJYZXSjw57sqgLn5Z0wolsOCz0RyJkyeYjgz7pwwVq20eboZwtVUl2EnN5gJ50dQZFdryATvABRTr/tJXkUMdaAK5pwtCapwtFLskguwuyMh/Sd9WChQ4sIvIUYSk3PYqQvCQlOC04IfN7PkdjOyRKWhdKXMmiAFt9i3sJ5jxoRuR0vqAghxxwHuqfQE5OHGDKOrwEnqs1DgAZ2e4Eev1d45TN7JfhrQLKgfwMFYAsvp33dXII073aVQLI2gN5S58lfmGnKKFtah7nkgnBZB7zlP7Y/QNiTM6sYNzawwAAAABJRU5ErkJggg==
  28. // @grant GM_xmlhttpRequest
  29. // @grant GM_registerMenuCommand
  30. // @grant GM_notification
  31. // @grant GM_getValue
  32. // @grant GM_setValue
  33. // @grant GM_addStyle
  34. // @grant GM_openInTab
  35. // @grant GM_deleteValue
  36. // @grant GM_info
  37. // @grant GM_setClipboard
  38. // @grant GM.xmlHttpRequest
  39. // @grant GM.registerMenuCommand
  40. // @grant GM.notification
  41. // @grant GM.getValue
  42. // @grant GM.setValue
  43. // @grant GM.addStyle
  44. // @grant GM.openInTab
  45. // @grant GM.deleteValue
  46. // @grant GM.info
  47. // @grant GM.setClipboard
  48. // @homepage https://github.com/hoothin/UserScripts/tree/master/Pagetual
  49. // @supportURL https://github.com/hoothin/UserScripts/issues
  50. // @connect wedata.net
  51. // @connect githubusercontent.com
  52. // @connect ghproxy.com
  53. // @connect hoothin.github.io
  54. // @run-at document-idle
  55. // @connect *
  56. // @contributionURL https://ko-fi.com/hoothin
  57. // @contributionAmount 1
  58. // ==/UserScript==
  59.  
  60. (function() {
  61. 'use strict';
  62. const pauseVideo = () => {
  63. setTimeout(() => {
  64. [].forEach.call(document.querySelectorAll("video"), video => {
  65. video.removeAttribute && video.removeAttribute("autoplay");
  66. video.pause && video.pause();
  67. });
  68. }, 1000);
  69. };
  70. if (window.name === 'pagetual-iframe' || (window.frameElement && window.frameElement.name === 'pagetual-iframe')) {
  71. [].forEach.call(document.querySelectorAll("iframe"), iframe => {
  72. iframe.name = 'pagetual-iframe';
  73. });
  74. var domloaded = function() {
  75. window.parent.postMessage('pagetual-iframe:DOMLoaded', '*');
  76. };
  77. if (window.opera) {
  78. document.addEventListener('DOMContentLoaded', domloaded, false);
  79. pauseVideo();
  80. } else {
  81. domloaded();
  82. if (document.readystate === 'complete') {
  83. pauseVideo();
  84. } else {
  85. window.addEventListener('load', () => {
  86. pauseVideo();
  87. }, false);
  88. }
  89. }
  90. if (getComputedStyle(document.documentElement).display === 'none') {
  91. document.documentElement.style.display = 'block';
  92. }
  93. if (document.body && getComputedStyle(document.body).display === 'none') {
  94. document.body.style.display = 'block';
  95. }
  96. return;
  97. }
  98.  
  99. if (window.top !== window.self) {
  100. try {
  101. if (window.self.innerWidth < 300 || window.self.innerHeight < 300) {
  102. return;
  103. }
  104. } catch(e) {
  105. return;
  106. }
  107. }
  108.  
  109. const noRuleTest = false;
  110. const lang = navigator.appName === "Netscape" ? navigator.language : navigator.userLanguage;
  111. const langData = [
  112. {
  113. // English translation update by github.com/https433, admin@abby0666.xyz.
  114. name: "English",
  115. match: ["en"],
  116. lang: {
  117. enableDebug: "Enable debug output",
  118. updateNotification: "Notification after rules updated",
  119. disable: "Disable",
  120. disableSite: "Toggle disabled state",
  121. disableSiteTips: "Disabled on this site",
  122. enableSiteTips: "Enabled on this site",
  123. enable: "Enable",
  124. toTop: "To Top",
  125. toBottom: "To Bottom",
  126. current: "Current Page",
  127. forceIframe: "Force to join next page",
  128. cancelForceIframe: "Cancel Force join",
  129. configure: "Configure",
  130. firstUpdate: "Click here to initialize the default rule list",
  131. update: "Update online rules",
  132. click2update: "Click to update rules from url now",
  133. loadNow: "Load next automatically",
  134. loadConfirm: "How many pages do you want to load? (0 means infinite)",
  135. noNext: "No next link found, please create a new rule",
  136. passSec: "Updated #t# seconds ago",
  137. passMin: "Updated #t# minutes ago",
  138. passHour: "Updated #t# hours ago",
  139. passDay: "Updated #t# days ago",
  140. cantDel: "Can't delete builtin rules",
  141. confirmDel: "Are you sure you want to delete this rule?",
  142. updateSucc: "Update succeeded",
  143. beginUpdate: "Begin update, wait a moment please",
  144. customUrls: "Import Pagetual or AutoPagerize rule url, one url per line.",
  145. customRules: "Input custom rules. <a href='#t#'>✍️Contribute rules</a>",
  146. save: "Save",
  147. loadingText: "Shojo Now Loading...",
  148. opacity: "Opacity",
  149. opacityPlaceholder: "0: hide spacer",
  150. hideBar: "Hide the pagnation spacer",
  151. hideBarButNoStop: "Hide but not stop",
  152. dbClick2Stop: "Double-click on the blank space to pause",
  153. sortTitle: "Sorting takes effect after the next rule update",
  154. autoRun: "Auto enable (blacklist mode)",
  155. autoLoadNum: "Amount for preload pages",
  156. turnRate: "Turn the next page when it's less than 【X】 times page height from the footer",
  157. inputPageNum: "Enter page number to jump",
  158. enableHistory: "Write browsing history after page turning",
  159. enableHistoryAfterInsert: "Write browsing history immediately after splicing, otherwise write after browsing",
  160. contentVisibility: "Automatically switch contentVisibility to improve rendering performance",
  161. initRun: "Turn pages immediately after opening",
  162. preload: "Preload next page for speeding up",
  163. click2ImportRule: "Click to import base rules link, and then wait until the update is complete: ",
  164. forceAllBody: "Join full body of page?",
  165. openInNewTab: "Open urls of additions in new tab",
  166. importSucc: "Import complete",
  167. import: "Import",
  168. editCurrent: "Edit rule for current",
  169. editBlacklist: "Edit the url blacklist, one entry per line, Support ? * for wildcard",
  170. upBtnImg: "Icon of back to top",
  171. downBtnImg: "Icon of go to footer",
  172. sideControllerIcon: "Icon of sidebar",
  173. loadingTextTitle: "Loading text",
  174. dbClick2StopCtrl: "Ctrl key",
  175. dbClick2StopAlt: "Alt key",
  176. dbClick2StopShift: "Shift key",
  177. dbClick2StopMeta: "Meta key",
  178. dbClick2StopKey: "Shortcut key",
  179. pageElementCss: "Custom style for main page elements",
  180. customCss: "Custom complete css",
  181. firstAlert: "You have not imported the base rule, please select the appropriate rule to import",
  182. picker: "Pagetual page element picker",
  183. closePicker: "Close Pagetual picker",
  184. pickerPlaceholder: "Element selector, (Advanced users only, leave blank otherwise)",
  185. pickerCheck: "Check selector and copy",
  186. switchSelector: "Click to switch element",
  187. gotoEdit: "Go to edit rule with current selector",
  188. manualMode: "Disable splicing, manually advance next page using the right arrow key (or dispatch event 'pagetual.next')",
  189. clickMode: "Disable splicing, automatically click the next page when scrolling to the end of the page",
  190. pageBarMenu: "Click the center of the page bar to open the picker menu",
  191. nextSwitch: "Switch next link",
  192. arrowToScroll: "Press left arrow to scroll back and right arrow to advance page",
  193. sideController: "Display the paging control bar in the sidebar",
  194. sideControllerScroll: "Scroll toggle",
  195. sideControllerAlways: "Always show",
  196. hideLoadingIcon: "Hide loading animation",
  197. hideBarArrow: "Hide arrow for page bar",
  198. duplicate: "Duplicate Pagetual have been installed, check your script manager!",
  199. forceStateIframe: "Embed full page as iframe",
  200. forceStateDynamic: "Load dynamic content via iframe",
  201. forceStateDisable: "Disable page turning on this site",
  202. autoScrollRate: "Scroll speed (1~1000)",
  203. disableAutoScroll: "Stop Auto Scroll",
  204. enableAutoScroll: "Enable Auto Scroll",
  205. toggleAutoScroll: "Toggle Auto Scroll",
  206. ruleRequest: "Rule Request",
  207. page: "Page ",
  208. prevPage: "Prev page",
  209. nextPage: "Next page",
  210. errorRulesMustBeArray: "Rules must be a Array!",
  211. errorJson: "JSON error, Check again!",
  212. editSuccess: "Edit successfully",
  213. errorWrongUrl: "Wrong url, Check again!",
  214. errorAlreadyExists: "A rule already exists!",
  215. settingsSaved: "The settings are saved, refresh to view",
  216. iframe: "Iframe",
  217. dynamic: "Dynamic",
  218. reloadPage: "Edit completed, reload now?",
  219. copied: "Copied",
  220. noValidContent: "No valid content detected, a Captcha may be present",
  221. outOfDate: "The script is outdated, update to the latest version please.",
  222. hideBarTips: "Hide the pagination bar, toggle immersive experience",
  223. setConfigPage: "Set current page as the default configuration page",
  224. wedata2github: "Change the wedata address to the mirror address in the github repository",
  225. addOtherProp: "Add rule property",
  226. addNextSelector: "Add selector content as nextLink",
  227. addPageSelector: "Add selector content as pageElement",
  228. propName: "Enter rule property name",
  229. propValue: "Enter rule property value",
  230. customFirst: "Ignore cache for local custom rules",
  231. rulesExample: "Rules Example",
  232. lastPage: "Reached the last page",
  233. lastPageTips: "Show tips when reaching the last page"
  234. }
  235. },
  236. {
  237. // Translated by SrKalopsia (srkalopsia@gmail.com).
  238. name: "Español",
  239. match: ["es", "es-ES"],
  240. lang: {
  241. enableDebug: "Habilitar salida de depuración",
  242. updateNotification: "Notificación después de actualizar las reglas",
  243. disable: "Desactivar",
  244. disableSite: "Alternar estado desactivado",
  245. disableSiteTips: "Desactivado en este sitio",
  246. enableSiteTips: "Activado en este sitio",
  247. enable: "Habilitar",
  248. toTop: "Ir al inicio",
  249. toBottom: "Ir al final",
  250. current: "Página actual",
  251. forceIframe: "Forzar para unirse a la siguiente página",
  252. cancelForceIframe: "Cancelar unión forzada",
  253. configure: "Configurar",
  254. firstUpdate: "Haga clic aquí para inicializar las reglas",
  255. update: "Actualizar reglas en línea",
  256. click2update: "Haga clic para actualizar las reglas desde la URL ahora",
  257. loadNow: "Cargar el siguiente automáticamente",
  258. loadConfirm: "¿Cuántas páginas desea cargar? (0 significa infinito)",
  259. noNext: "No se encontró el enlace siguiente, por favor cree una nueva regla",
  260. passSec: "Actualizado hace #t# segundos",
  261. passMin: "Actualizado hace #t# minutos",
  262. passHour: "Actualizado hace #t# horas",
  263. passDay: "Actualizado hace #t# días",
  264. cantDel: "No se pueden eliminar las reglas incorporadas",
  265. confirmDel: "¿Está seguro de que desea eliminar esta regla?",
  266. updateSucc: "Actualización exitosa",
  267. beginUpdate: "Comenzar actualización, espere un momento por favor",
  268. customUrls: "Importar URL de reglas de Pagetual o AutoPagerize, una URL por línea",
  269. customRules: "Introduzca reglas personalizadas. <a href='#t#'>✍️Contribuir reglas</a>",
  270. save: "Guardar",
  271. loadingText: "Shojo Cargando...",
  272. opacity: "Opacidad",
  273. opacityPlaceholder: "0: ocultar espaciador",
  274. hideBar: "Ocultar el espaciador de paginación",
  275. hideBarButNoStop: "Ocultar pero no detener",
  276. dbClick2Stop: "Haga doble clic en el espacio en blanco para pausar",
  277. sortTitle: "La ordenación surtirá efecto después de la próxima actualización de reglas",
  278. autoRun: "Habilitar automáticamente (modo lista negra)",
  279. autoLoadNum: "Cantidad de páginas para precargar",
  280. turnRate: "Pasar a la siguiente página cuando esté a menos de 【X】 veces la altura de la página desde el pie de página",
  281. inputPageNum: "Ingrese el número de página para saltar",
  282. enableHistory: "Escribir historial de navegación después de pasar la página",
  283. enableHistoryAfterInsert: "Escribir historial de navegación inmediatamente después de unir, de lo contrario escribir después de navegar",
  284. contentVisibility: "Cambiar automáticamente la visibilidad del contenido para mejorar el rendimiento de renderización",
  285. initRun: "Pasar páginas inmediatamente después de abrir",
  286. preload: "Precargar la siguiente página para acelerar",
  287. click2ImportRule: "Haga clic para importar el enlace de reglas base, luego espere hasta que la actualización esté completa: ",
  288. forceAllBody: "¿Unir el cuerpo completo de la página?",
  289. openInNewTab: "Abrir URLs de adiciones en una nueva pestaña",
  290. importSucc: "Importación completada",
  291. import: "Importar",
  292. editCurrent: "Editar regla para la actual",
  293. editBlacklist: "Editar URLs de la lista negra, una por línea, admite ? * para comodín",
  294. upBtnImg: "Icono de volver al inicio",
  295. downBtnImg: "Icono de ir al pie de página",
  296. sideControllerIcon: "Icono de la barra lateral",
  297. loadingTextTitle: "Texto de carga",
  298. dbClick2StopCtrl: "Tecla Ctrl",
  299. dbClick2StopAlt: "Tecla Alt",
  300. dbClick2StopShift: "Tecla Shift",
  301. dbClick2StopMeta: "Tecla Meta",
  302. dbClick2StopKey: "Tecla de acceso rápido",
  303. pageElementCss: "Estilo personalizado para los elementos principales de la página",
  304. customCss: "CSS completo personalizado",
  305. firstAlert: "No ha importado la regla base, por favor seleccione la regla adecuada para importar",
  306. picker: "Selector de elementos de página de Pagetual",
  307. closePicker: "Cerrar selector de Pagetual",
  308. pickerPlaceholder: "Selector de elementos, déjelo vacío si no tiene idea",
  309. pickerCheck: "Comprobar selector y copiar",
  310. switchSelector: "Haga clic para cambiar el elemento",
  311. gotoEdit: "Ir a editar la regla con el selector actual",
  312. manualMode: "Deshabilitar unión, pasar páginas manualmente con las teclas de flecha derecha (o despachar evento 'pagetual.next')",
  313. clickMode: "Deshabilitar unión, hacer clic automáticamente en la siguiente página al desplazarse al final de la página",
  314. pageBarMenu: "Haga clic en el centro de la barra de página para abrir el menú del selector",
  315. nextSwitch: "Cambiar al siguiente enlace",
  316. arrowToScroll: "Presione la tecla de flecha izquierda para desplazarse anterior y la tecla de flecha derecha para desplazarse siguiente",
  317. sideController: "Mostrar la barra de control de paginación en la barra lateral",
  318. sideControllerScroll: "Alternar desplazamiento",
  319. sideControllerAlways: "Mostrar siempre",
  320. hideLoadingIcon: "Ocultar animación de carga",
  321. hideBarArrow: "Ocultar flecha para la barra de página",
  322. duplicate: "Pagetual duplicado ha sido instalado, ¡revise su gestor de scripts!",
  323. forceStateIframe: "Incrustar página completa como iframe",
  324. forceStateDynamic: "Cargar contenido dinámico a través de iframe",
  325. forceStateDisable: "Deshabilitar pasar páginas en este sitio",
  326. autoScrollRate: "Velocidad de desplazamiento (1~1000)",
  327. disableAutoScroll: "Detener desplazamiento automático",
  328. enableAutoScroll: "Habilitar desplazamiento automático",
  329. toggleAutoScroll: "Alternar desplazamiento automático",
  330. ruleRequest: "Solicitud de regla",
  331. page: "Página ",
  332. prevPage: "Página anterior",
  333. nextPage: "Página siguiente",
  334. errorRulesMustBeArray: "¡Las reglas deben ser un array!",
  335. errorJson: "Error JSON, ¡verifique de nuevo!",
  336. editSuccess: "Editado exitosamente",
  337. errorWrongUrl: "URL incorrecta, ¡verifique de nuevo!",
  338. errorAlreadyExists: "¡Ya existe!",
  339. settingsSaved: "La configuración se ha guardado, actualice para ver",
  340. iframe: "Iframe",
  341. dynamic: "Dinámico",
  342. reloadPage: "Edición completada, ¿recargar página ahora?",
  343. copied: "Copiado",
  344. noValidContent: "No se detectó contenido válido, puede ser necesario realizar una acción de Captcha, haga clic para ver",
  345. outOfDate: "El script está desactualizado, ¡actualice a la última versión a tiempo!",
  346. hideBarTips: "Ocultar la barra de paginación, alternar experiencia inmersiva",
  347. setConfigPage: "Establecer la página actual como la página de configuración predeterminada",
  348. wedata2github: "Cambiar la dirección de wedata a la dirección espejo en el repositorio de GitHub",
  349. addOtherProp: "Agregar propiedad de regla",
  350. addNextSelector: "Agregar contenido del selector como nextLink",
  351. addPageSelector: "Agregar contenido del selector como pageElement",
  352. propName: "Ingrese el nombre de la propiedad de la regla",
  353. propValue: "Ingrese el valor de la propiedad de la regla",
  354. customFirst: "Ignorar caché para reglas personalizadas locales",
  355. rulesExample: "Ejemplo de reglas",
  356. lastPage: "Llegó a la última página",
  357. lastPageTips: "Mostrar consejos al llegar a la última página"
  358. }
  359. },
  360. {
  361. // Translated by Prankster 199 (vfggf95565).
  362. name: "Arabic",
  363. match: ["ar", "ar-AE", "ar-BH", "ar-DZ", "ar-EG", "ar-IQ", "ar-JO", "ar-KW", "ar-LB", "ar-LY", "ar-MA", "ar-OM", "ar-QA", "ar-SA", "ar-SY", "ar-TN", "ar-YE"],
  364. lang: {
  365. enableDebug: "تمكين تصحيح الأخطاء",
  366. updateNotification: "إشعار بعد تحديث القواعد",
  367. disable: "معطل",
  368. disableSite: "تبديل حالة التعطيل/التفعيل للموقع",
  369. disableSiteTips: "معطل على هذا الموقع",
  370. enableSiteTips: "مفعل على هذا الموقع",
  371. enable: "مفعل",
  372. toTop: "إلى الأعلى",
  373. toBottom: "إلى الأسفل",
  374. current: "الصفحة الحالية",
  375. forceIframe: "إجبار على الانضمام للصفحة التالية",
  376. cancelForceIframe: "إلغاء الانضمام القسري",
  377. configure: "إعداد",
  378. firstUpdate: "انقر هنا لتفعيل القواعد لأول مرة",
  379. update: "تحديث القواعد عبر الإنترنت",
  380. click2update: "انقر لتحديث القواعد من الرابط الآن",
  381. loadNow: "تحميل التالي تلقائيًا",
  382. loadConfirm: "كم عدد الصفحات التي ترغب تحميلها؟ (0 يعني لانهائي)",
  383. noNext: "لم يتم العثور على رابط الصفحة التالية، يرجى إنشاء قاعدة جديدة",
  384. passSec: "تم التحديث منذ #t# ثانية",
  385. passMin: "تم التحديث منذ #t# دقيقة",
  386. passHour: "تم التحديث منذ #t# ساعة",
  387. passDay: "تم التحديث منذ #t# يوم",
  388. cantDel: "لا يمكن حذف القواعد المدمجة",
  389. confirmDel: "هل أنت متأكد من حذف هذه القاعدة؟",
  390. updateSucc: "تم التحديث بنجاح",
  391. beginUpdate: "بدأ التحديث، يرجى الانتظار لحظة",
  392. customUrls: "استيراد رابط قاعدة Pagetual أو AutoPagerize، رابط واحد لكل سطر",
  393. customRules: "إدخال القواعد المخصصة. <a href='#t#'>✍️ساهم بالقواعد</a>",
  394. save: "حفظ",
  395. /* From the creator hoothin :
  396. "Shojo Now Loading..." is a meme that refers to the game loading text in the Japanese Touhou (東方) game series. */
  397. loadingText: "جارٍ التحميل...",
  398. opacity: "الشفافية",
  399. opacityPlaceholder: "0: إخفاء الفاصل",
  400. hideBar: "إخفاء الفاصل التصفحي",
  401. hideBarButNoStop: "إخفاء، لكن لا تتوقف",
  402. dbClick2Stop: "انقر مزدوج على المساحة الفارغة للإيقاف",
  403. sortTitle: "يتم تفعيل الفرز بعد التحديث التالي للقواعد",
  404. autoRun: "تمكين تلقائي (وضع القائمة السوداء)",
  405. autoLoadNum: "عدد صفحات التحميل المسبق",
  406. turnRate: "الانتقال للصفحة التالية عندما تكون المسافة أقل من 【X】 مرات ارتفاع الصفحة من التذييل",
  407. inputPageNum: "أدخل رقم الصفحة للانتقال",
  408. enableHistory: "كتابة سجل التصفح بعد تحويل الصفحة",
  409. enableHistoryAfterInsert: "كتابة سجل التصفح فورًا بعد الدمج، أو بعد التصفح",
  410. contentVisibility: "التنقل التلقائي لرؤية المحتوى, لتحسين أداء العرض",
  411. initRun: "الانتقال بين الصفحات فور الفتح",
  412. preload: "تحميل الصفحة التالية مسبقًا لتسريع الأداء",
  413. click2ImportRule: "انقر لاستيراد رابط القواعد الأساسية، ثم انتظر حتى يكتمل التحديث",
  414. forceAllBody: "دمج كامل الصفحة كإطار؟",
  415. openInNewTab: "فتح الروابط الإضافية في علامة تبويب جديدة",
  416. importSucc: "تم الاستيراد بنجاح",
  417. import: "استيراد",
  418. editCurrent: "تحرير القاعدة للحالية",
  419. editBlacklist: "تحرير عناوين القائمة السوداء، سطر بسطر، دعم؟ * للرموز المتحركة",
  420. upBtnImg: "أيقونة العودة إلى الأعلى",
  421. downBtnImg: "أيقونة الانتقال إلى الأسفل",
  422. sideControllerIcon: "أيقونة الشريط الجانبي",
  423. loadingTextTitle: "تحميل النص",
  424. dbClick2StopCtrl: "مفتاح Ctrl",
  425. dbClick2StopAlt: "مفتاح Alt",
  426. dbClick2StopShift: "مفتاح Shift",
  427. dbClick2StopMeta: "مفتاح Meta",
  428. dbClick2StopKey: "مفاتيح الاختصار",
  429. pageElementCss: "نمط مخصص لعناصر الصفحة الرئيسية",
  430. customCss: "مخصص بالكامل CSS نمط",
  431. firstAlert: "لم تستورد القاعدة الأساسية بعد، يرجى اختيار القاعدة المناسبة للاستيراد",
  432. picker: "محدد عناصر الصفحة Pagetual",
  433. closePicker: "إغلاق محدد Pagetual",
  434. pickerPlaceholder: "محدد العناصر، اتركه فارغًا إذا كنت لا تعرف",
  435. pickerCheck: "تحقق من المحدد ونسخ",
  436. switchSelector: "انقر للتبديل بين العناصر",
  437. gotoEdit: "اذهب لتحرير القاعدة بالمحدد الحالي",
  438. manualMode: "تعطيل الدمج/الربط، واستخدام مفتاح الاتجاه الأيمن يدويًا للتمرير، واستخدام مفتاح السهم الأيسر للرجوع",
  439. clickMode: "تعطيل الدمج/الربط، عند التمرير إلى نهاية الصفحة، سيتم النقر تلقائيًا على الصفحة التالية",
  440. pageBarMenu: "انقر على مركز شريط الصفحة لفتح قائمة التحديد",
  441. nextSwitch: "تبديل الرابط التالي",
  442. arrowToScroll: "انقر على مفتاح السهم الأيمن للتمرير التالي ومفتاح السهم الأيسر للتمرير السابق",
  443. sideController: "عرض شريط التحكم في التصفح الترقيم في الشريط الجانبي",
  444. sideControllerScroll: "تبديل التمرير",
  445. sideControllerAlways: "عرض دائمًا",
  446. hideLoadingIcon: "إخفاء رمز التحميل",
  447. hideBarArrow: "إخفاء سهم شريط الصفحة",
  448. duplicate: "تم تثبيت Pagetual مكرر، تحقق من مدير النصوص البرمجية الخاص بك!",
  449. forceStateIframe: "تضمين الصفحة بالكامل كإطار",
  450. forceStateDynamic: "تحميل المحتوى الديناميكي عبر الإطار",
  451. forceStateDisable: "تعطيل تحويل الصفحات على هذا الموقع",
  452. autoScrollRate: "سرعة التمرير (1~1000)",
  453. disableAutoScroll: "إيقاف التمرير التلقائي",
  454. enableAutoScroll: "تمكين التمرير التلقائي",
  455. toggleAutoScroll: "تبديل التمرير التلقائي",
  456. ruleRequest: "طلب قاعدة",
  457. page: "صفحة ",
  458. prevPage: "الصفحة السابقة",
  459. nextPage: "الصفحة التالية",
  460. errorRulesMustBeArray: "يجب أن تكون القواعد مصفوفة!",
  461. errorJson: "خطأ في JSON، تحقق مرة أخرى!",
  462. editSuccess: "تم التحرير بنجاح",
  463. errorWrongUrl: "عنوان URL خاطئ، تحقق مرة أخرى!",
  464. errorAlreadyExists: "موجود بالفعل!",
  465. settingsSaved: "تم حفظ الإعدادات، قم بالتحديث لعرض",
  466. iframe: "إطار",
  467. dynamic: "ديناميكي",
  468. reloadPage: "اكتمل التحرير، إعادة تحميل الصفحة الآن؟",
  469. copied: "تم النسخ",
  470. noValidContent: "لم يتم الكشف عن محتوى صالح، قد يكون الإجراء Captcha مطلوبًا، انقر لعرض",
  471. outOfDate: "النص البرمجي قديم، قم بالتحديث إلى الإصدار الأحدث في الوقت المناسب!",
  472. hideBarTips: "إخفاء شريط التحكم في التصفح الترقيم ، والتبديل لوضع كامل الصفحة",
  473. setConfigPage: "تعيين الصفحة الحالية كصفحة الإعداد الافتراضية",
  474. wedata2github: "تغيير عنوان الويب داتا إلى العنوان البديل المرآة, في مستودع جيت هاب",
  475. addOtherProp: "إضافة خاصية قاعدة",
  476. addNextSelector: "إضافة محتوى المحدد كـ nextLink",
  477. addPageSelector: "إضافة محتوى المحدد كـ pageElement",
  478. propName: "أدخل اسم خاصية القاعدة",
  479. propValue: "أدخل قيمة خاصية القاعدة",
  480. customFirst: "تجاهل ذاكرة التخزين المؤقت للقواعد المخصصة المحلية",
  481. rulesExample: "مثال على القواعد",
  482. lastPage: "تم الوصول إلى الصفحة الأخيرة",
  483. lastPageTips: "عرض تلميحات عند الوصول إلى الصفحة الأخيرة"
  484. }
  485. },
  486. {
  487. name: "简体中文",
  488. match: ["zh-CN", "zh-SG"],
  489. lang: {
  490. enableDebug: "调试模式,输出信息至控制台",
  491. updateNotification: "规则更新后提示",
  492. disable: "暂时禁用",
  493. disableSite: "站点禁用开关",
  494. disableSiteTips: "已在此站禁用",
  495. enableSiteTips: "已在此站启用",
  496. enable: "启用自动翻页",
  497. toTop: "回到顶部",
  498. toBottom: "前往页尾",
  499. current: "当前页",
  500. forceIframe: "强制拼接",
  501. cancelForceIframe: "取消强制拼接",
  502. configure: "打开配置页面",
  503. firstUpdate: "点击此处初始化规则",
  504. update: "更新在线规则",
  505. click2update: "点击立即更新规则",
  506. loadNow: "立即翻页",
  507. loadConfirm: "要翻几页?(0为不间断)",
  508. noNext: "没有找到下一页,请新建规则",
  509. passSec: "更新于 #t# 秒前",
  510. passMin: "更新于 #t# 分钟前",
  511. passHour: "更新于 #t# 小时前",
  512. passDay: "更新于 #t# 天前",
  513. cantDel: "无法删除内置规则",
  514. confirmDel: "是否确认要删除此规则?",
  515. updateSucc: "更新成功",
  516. beginUpdate: "正在更新,请耐心等待,不要关闭页面",
  517. customUrls: "导入 Pagetual 或 AutoPagerize 规则 url,一行一条",
  518. customRules: "输入【东方永页机】格式的自定义规则 <a href='#t#'>✍️贡献规则</a>",
  519. save: "保存设置",
  520. loadingText: "少女祈祷中...",
  521. opacity: "不透明值",
  522. opacityPlaceholder: "0: 隐藏分隔条",
  523. hideBar: "隐藏分页隔条",
  524. hideBarButNoStop: "隐藏但不停止",
  525. dbClick2Stop: "空白处双击暂停翻页",
  526. sortTitle: "排序在下次更新规则后生效",
  527. autoRun: "自动启用,否则为白名单模式",
  528. autoLoadNum: "自动加载指定页数",
  529. turnRate: "距离页尾【X】倍页面高度时就开始翻页",
  530. inputPageNum: "输入页码跳转",
  531. enableHistory: "翻页后写入历史记录",
  532. enableHistoryAfterInsert: "拼接后立即写入历史记录,否则浏览完毕后再行写入",
  533. contentVisibility: "自动切换 contentVisibility,提升渲染性能",
  534. initRun: "打开页面后立即尝试翻页,否则滚动至页尾再翻页",
  535. preload: "翻页前预读下一页,加速浏览",
  536. click2ImportRule: "点击下方任意一条添加规则库,并静待更新成功,请预先打开链接确认能正常访问再行导入:",
  537. forceAllBody: "是否拼接整个页面?",
  538. openInNewTab: "使拼接页面的内容在新页面打开",
  539. importSucc: "导入成功",
  540. import: "导入",
  541. editCurrent: "编辑此站规则",
  542. editBlacklist: "编辑黑名单网址,一行一条,支持? *通配符与正则",
  543. upBtnImg: "回到页首图标",
  544. downBtnImg: "前往页尾图标",
  545. sideControllerIcon: "侧边栏图标",
  546. loadingTextTitle: "加载中文字",
  547. dbClick2StopCtrl: "Ctrl",
  548. dbClick2StopAlt: "Alt",
  549. dbClick2StopShift: "Shift",
  550. dbClick2StopMeta: "Meta",
  551. dbClick2StopKey: "快捷键",
  552. pageElementCss: "页面主体框架的样式",
  553. customCss: "自定义 css",
  554. firstAlert: "你还未导入规则库,请选择合适的规则库导入哦",
  555. picker: "东方永页机主体元素抓取器",
  556. closePicker: "关闭东方永页机抓取器",
  557. pickerPlaceholder: "元素选择器,没想法建议留空",
  558. pickerCheck: "检查你编辑的选择器并复制",
  559. switchSelector: "点击切换元素",
  560. gotoEdit: "使用当前的选择器前往编辑规则",
  561. manualMode: "禁用拼接,手动用右方向键翻页,可使用左方向键返回",
  562. clickMode: "禁用拼接,滚动至页尾时自动点击下一页",
  563. pageBarMenu: "点击分隔条中间弹出菜单",
  564. nextSwitch: "切换其他页码",
  565. arrowToScroll: "左方向键滚动至上一页,右方向键滚动至下一页",
  566. sideController: "在侧边显示翻页控制栏",
  567. sideControllerScroll: "滚动开关",
  568. sideControllerAlways: "始终显示",
  569. hideLoadingIcon: "隐藏加载动画",
  570. hideBarArrow: "隐藏分隔条定位箭头",
  571. duplicate: "检测到永页机重复安装,请删除其他脚本管理器中的永页机!",
  572. forceStateIframe: "以 iframe 嵌入整页",
  573. forceStateDynamic: "通过 iframe 加载动态内容后取出",
  574. forceStateDisable: "在此站禁用",
  575. autoScrollRate: "滚动速度(1~1000)",
  576. disableAutoScroll: "停止自动滚动",
  577. enableAutoScroll: "开启自动滚动",
  578. toggleAutoScroll: "自动滚动开关",
  579. ruleRequest: "适配请求",
  580. page: "Page ",
  581. prevPage: "上一页",
  582. nextPage: "下一页",
  583. errorRulesMustBeArray: "规则必须为数组形式!",
  584. errorJson: "JSON 格式有错,请重新检查!",
  585. editSuccess: "编辑成功",
  586. errorWrongUrl: "URL 错误, 请重新检查!",
  587. errorAlreadyExists: "已经存在!",
  588. settingsSaved: "设置已保存,刷新后生效",
  589. iframe: "强制拼接",
  590. dynamic: "动态加载",
  591. reloadPage: "编辑完成,是否立即刷新页面?",
  592. copied: "已复制",
  593. noValidContent: "没有检测到有效内容,可能需要人机校验,点击查看",
  594. outOfDate: "脚本已过时,请及时更新到最新版本!",
  595. hideBarTips: "隐藏分页隔条,沉浸式体验",
  596. setConfigPage: "将当前页面设为默认配置页",
  597. wedata2github: "将 wedata 地址更改为 github 仓库内的镜像地址",
  598. addOtherProp: "添加规则属性",
  599. addNextSelector: "添加选择器内容为 nextLink",
  600. addPageSelector: "添加选择器内容为 pageElement",
  601. propName: "输入规则属性名",
  602. propValue: "输入规则属性值",
  603. customFirst: "为本地自定义规则忽略缓存",
  604. rulesExample: "自定义规则详解",
  605. lastPage: "已到达最后一页",
  606. lastPageTips: "到达最后一页时进行提示"
  607. }
  608. },
  609. {
  610. name: "正體中文",
  611. match: ["zh", "zh-TW", "zh-HK"],
  612. lang: {
  613. enableDebug: "調試模式,輸出信息至控制台",
  614. updateNotification: "規則更新后提示",
  615. disable: "暫時禁用",
  616. disableSite: "站點禁用開關",
  617. disableSiteTips: "已在此站禁用",
  618. enableSiteTips: "已在此站啟用",
  619. enable: "啟用自動翻頁",
  620. toTop: "回到頂部",
  621. toBottom: "前往頁尾",
  622. current: "當前頁",
  623. forceIframe: "強制拼接",
  624. cancelForceIframe: "取消强制拼接",
  625. configure: "打開配置頁面",
  626. firstUpdate: "點擊此處初始化規則",
  627. update: "更新在綫規則",
  628. click2update: "點擊立即更新規則",
  629. loadNow: "立即翻頁",
  630. loadConfirm: "要翻几頁?(0為不間斷)",
  631. noNext: "沒有找到下一頁,請新建規則",
  632. passSec: "更新于 #t# 秒前",
  633. passMin: "更新于 #t# 分鐘前",
  634. passHour: "更新于 #t# 小時前",
  635. passDay: "更新于 #t# 天前",
  636. cantDel: "無法刪除内置規則",
  637. confirmDel: "是否確認要刪除此規則?",
  638. updateSucc: "更新成功",
  639. beginUpdate: "正在更新,請稍候",
  640. customUrls: "導入 Pagetual 或 AutoPagerize 規則 url,一行一條",
  641. customRules: "輸入【東方永頁機】格式的自定義規則 <a href='#t#'>✍️貢獻規則</a>",
  642. save: "存儲設置",
  643. loadingText: "少女祈禱中...",
  644. opacity: "不透明值",
  645. opacityPlaceholder: "0: 隱藏分隔條",
  646. hideBar: "隱藏分頁隔條",
  647. hideBarButNoStop: "隱藏但不停止",
  648. dbClick2Stop: "空白處雙擊暫停翻頁",
  649. sortTitle: "排序在下次更新規則後生效",
  650. autoRun: "自動啓用,否則為白名單模式",
  651. autoLoadNum: "自動加載指定頁數",
  652. turnRate: "距離頁尾【X】倍頁面高度時就開始翻頁",
  653. inputPageNum: "輸入頁碼跳轉",
  654. enableHistory: "翻頁后寫入歷史記錄",
  655. enableHistoryAfterInsert: "拼接後立即寫入歷史記錄,否則瀏覽完畢後再行寫入",
  656. contentVisibility: "自動切換 contentVisibility,提升渲染性能",
  657. initRun: "打開頁面后立即嘗試翻頁,否則滾動至頁尾再翻頁",
  658. preload: "翻頁前預讀下一頁,加速瀏覽",
  659. click2ImportRule: "點擊下方添加特殊規則庫,并靜待更新成功:",
  660. forceAllBody: "是否拼接整個頁面?",
  661. openInNewTab: "使拼接頁面的内容在新頁面打開",
  662. importSucc: "導入成功",
  663. import: "導入",
  664. editCurrent: "編輯此站規則",
  665. editBlacklist: "編輯黑名單網址,一行一條,支持? *通配符與正則",
  666. upBtnImg: "回到頁首圖標",
  667. downBtnImg: "前往頁尾圖標",
  668. sideControllerIcon: "側邊欄圖標",
  669. loadingTextTitle: "加載中文字",
  670. dbClick2StopCtrl: "Ctrl",
  671. dbClick2StopAlt: "Alt",
  672. dbClick2StopShift: "Shift",
  673. dbClick2StopMeta: "Meta",
  674. dbClick2StopKey: "快捷鍵",
  675. pageElementCss: "頁面主體框架的樣式",
  676. customCss: "自定義 css",
  677. firstAlert: "你還未導入規則庫,請選擇合適的規則庫導入哦",
  678. picker: "東方永頁機主體元素抓取器",
  679. closePicker: "關閉東方永頁機抓取器",
  680. pickerPlaceholder: "元素選擇器,沒想法建議留空",
  681. pickerCheck: "檢查你編輯的選擇器並複製",
  682. switchSelector: "點擊切換元素",
  683. gotoEdit: "使用當前的選擇器前往編輯規則",
  684. manualMode: "禁用拼接,手動用右方向鍵翻頁,左方向鍵返回",
  685. clickMode: "禁用拼接,滾動至頁尾時自動點擊下一頁",
  686. pageBarMenu: "點擊分隔條中間彈出菜單",
  687. nextSwitch: "切換其他頁碼",
  688. arrowToScroll: "左方向鍵滾動至上一頁,右方向鍵滾動至下一頁",
  689. sideController: "在側邊顯示翻頁控制欄",
  690. sideControllerScroll: "滾燈開關",
  691. sideControllerAlways: "始終顯示",
  692. hideLoadingIcon: "隱藏加載動畫",
  693. hideBarArrow: "隱藏分隔條定位箭頭",
  694. duplicate: "檢測到永頁機重複安裝,請刪除其他腳本管理器中的永頁機!",
  695. forceStateIframe: "以 iframe 嵌入整頁",
  696. forceStateDynamic: "通過 iframe 加載動態內容後取出",
  697. forceStateDisable: "在此站禁用",
  698. autoScrollRate: "滾動速度(1~1000)",
  699. disableAutoScroll: "停止自動滾動",
  700. enableAutoScroll: "開啟自動滾動",
  701. toggleAutoScroll: "自動滾動開關",
  702. ruleRequest: "適配請求",
  703. page: "Page ",
  704. prevPage: "上一頁",
  705. nextPage: "下一頁",
  706. errorRulesMustBeArray: "規則必須為陣列形式!",
  707. errorJson: "JSON 格式有錯,請重新檢查!",
  708. editSuccess: "編輯成功",
  709. errorWrongUrl: "URL 錯誤, 請重新檢查!",
  710. errorAlreadyExists: "已經存在!",
  711. settingsSaved: "設置已保存,刷新後生效",
  712. iframe: "強制拼接",
  713. dynamic: "動態加載",
  714. reloadPage: "編輯完成,是否立即刷新頁面?",
  715. copied: "已復制",
  716. noValidContent: "沒有檢測到有效内容,可能需要人機校驗,點擊查看",
  717. outOfDate: "脚本已過時,請及時更新到最新版本!",
  718. hideBarTips: "隱藏分頁隔條,沉浸式體驗",
  719. setConfigPage: "將當前頁面設為默認配置頁",
  720. wedata2github: "將 wedata 地址更改為 github 倉庫內的鏡像地址",
  721. addOtherProp: "添加規則屬性",
  722. addNextSelector: "添加選擇器內容為 nextLink",
  723. addPageSelector: "添加選擇器內容為 pageElement",
  724. propName: "輸入規則屬性名",
  725. propValue: "輸入規則屬性值",
  726. customFirst: "為本地自定義規則忽略緩存",
  727. rulesExample: "自定義規則詳解",
  728. lastPage: "已到達最後一頁",
  729. lastPageTips: "到達最後一頁時進行提示"
  730. }
  731. },
  732. {
  733. name: "日本語",
  734. match: ["ja"],
  735. lang: {
  736. enableDebug: "デバッグモード",
  737. updateNotification: "ルール更新後の通知",
  738. disable: "一時的に無効",
  739. disableSite: "無効状態の切り替え",
  740. disableSiteTips: "このサイトで既に無効になっています",
  741. enableSiteTips: "このサイトで既に有効になっています",
  742. enable: "ページめくりを有効にする",
  743. toTop: "トップに戻る",
  744. toBottom: "ページの下部に移動",
  745. current: "現在のページ",
  746. forceIframe: "強制ステッチ",
  747. cancelForceIframe: "強制ステッチをキャンセル",
  748. configure: "設定ページを開く",
  749. firstUpdate: "ここをクリックしてルールを初期化します",
  750. update: "更新ルール",
  751. click2update: "今すぐルールを更新してください",
  752. loadNow: "今すぐページをめくる",
  753. loadConfirm: "数ページめくりたいですか?(0は途切れない)",
  754. noNext: "次のページが見つかりません、新しいルールを作成してください",
  755. passSec: "#t#秒前に更新",
  756. passMin: "#t#分前に更新",
  757. passHour: "#t#時間前に更新",
  758. passDay: "#t#日前に更新",
  759. cantDel: "組み込みルールを削除できません",
  760. confirmDel: "このルールを削除してもよろしいですか?",
  761. updateSucc: "更新に成功しました",
  762. beginUpdate: "更新中、お待ちください",
  763. customUrls: "インポートルールのURL、1行に1つ",
  764. customRules: "【東方永頁機】の形式でカスタムルールを入力してください <a href='#t#'>✍️寄稿ルール</a>",
  765. save: "設定を保存",
  766. loadingText: "少女祈祷中...",
  767. opacity: "不透明値",
  768. opacityPlaceholder: "0: 隠す",
  769. hideBar: "ページ区切り文字を非表示にします",
  770. hideBarButNoStop: "非表示にするが停止しない",
  771. dbClick2Stop: "空白部分をダブルクリックしてページめくりを一時停止します",
  772. sortTitle: "並べ替えは、次のルールの更新後に有効になります",
  773. autoRun: "自動的に有効",
  774. autoLoadNum: "指定したページ数を自動的に読み込みます",
  775. turnRate: "ページの端からページの高さの【X】倍になったらページをめくる",
  776. inputPageNum: "ジャンプするページ番号を入力",
  777. enableHistory: "ページめくり後の履歴を書く",
  778. enableHistoryAfterInsert: "スプライシングの直後に履歴レコードを書き込みます。それ以外の場合は、閲覧後に書き込みます",
  779. contentVisibility: "contentVisibility を自動的に切り替えてレンダリング パフォーマンスを向上させる",
  780. initRun: "Webページを開いた直後にページをめくる",
  781. preload: "事前に次のページを読む",
  782. click2ImportRule: "以下をクリックして、ルールベースを追加します:",
  783. forceAllBody: "フルページ埋め込み?",
  784. openInNewTab: "スプライスされたページのコンテンツを新しいページで開きます",
  785. importSucc: "インポート完了",
  786. import: "インポート",
  787. editCurrent: "現在のルールの編集",
  788. editBlacklist: "ブラックリストのURLを編集し、1行ずつ、サポート? *ワイルドカード",
  789. upBtnImg: "トップアイコンに戻る",
  790. downBtnImg: "フッターアイコンに移動",
  791. sideControllerIcon: "サイドバー アイコン",
  792. loadingTextTitle: "テキストをロード",
  793. dbClick2StopCtrl: "Ctrlキー",
  794. dbClick2StopAlt: "Altキー",
  795. dbClick2StopShift: "Shiftキー",
  796. dbClick2StopMeta: "Metaキー",
  797. dbClick2StopKey: "Shortcutキー",
  798. pageElementCss: "ページ本文フレームの STYLE",
  799. customCss: "カスタム css",
  800. firstAlert: "ルールベースをインポートしていないため、インポートする適切なルールベースを選択してください",
  801. picker: "Pagetualページ要素ピッカー",
  802. closePicker: "Pagetualピッカーを閉じる",
  803. pickerPlaceholder: "わからない場合は空のままにしてください",
  804. pickerCheck: "セレクターをチェックしてコピー",
  805. switchSelector: "クリックして要素を切り替えます",
  806. gotoEdit: "現在のセレクターでルールを編集する",
  807. manualMode: "スプライシングを無効にします。手動で右の矢印キーを使用してページをめくります",
  808. clickMode: "スティッチングを無効にします。ページの最後までスクロールすると、次のページが自動的にクリックされます",
  809. pageBarMenu: "ページバーの中央をクリックしてメニューをポップアップ表示",
  810. nextSwitch: "次のページに切り替え",
  811. arrowToScroll: "左矢印キーで前へ、右矢印キーで次へ",
  812. sideController: "サイドバーにページング コントロール バーを表示する",
  813. sideControllerScroll: "スクロール スイッチ",
  814. sideControllerAlways: "常に表示",
  815. hideLoadingIcon: "読み込み中のアニメーションを隠す",
  816. hideBarArrow: "分割線の位置矢印を隠す",
  817. duplicate: "Pagetual の重複インストールが検出されました。他のスクリプト マネージャで永続的なページ マシンを削除してください!",
  818. forceStateIframe: "iframe にページ全体を埋め込む",
  819. forceStateDynamic: "iframe 経由で動的コンテンツを読み込む",
  820. forceStateDisable: "このステーションでのページめくりを無効にする",
  821. autoScrollRate: "スクロール速度 (1~1000)",
  822. disableAutoScroll: "自動スクロールを停止します",
  823. EnableAutoScroll: "自動スクロールを有効にする",
  824. toggleAutoScroll: "自動スクロールの切り替え",
  825. ruleRequest: "ルール要求",
  826. page: "Page ",
  827. prevPage: "Prev page",
  828. nextPage: "Next page",
  829. errorRulesMustBeArray: "Rules must be a Array!",
  830. errorJson: "JSON error, check again!",
  831. editSuccess: "Edit successfully",
  832. errorWrongUrl: "Wrong url, check again!",
  833. errorAlreadyExists: "Already exists!",
  834. settingsSaved: "The settings are saved, refresh to view",
  835. iframe: "Iframe",
  836. dynamic: "Dynamic",
  837. reloadPage: "Edit completed, reload page now?",
  838. copied: "Copied",
  839. noValidContent: "有効なコンテンツが検出されませんでした。クリックして表示",
  840. outOfDate: "スクリプトが古くなっています。最新バージョンに更新してください。",
  841. hideBarTips: "ページネーション バーを非表示にします。没入型エクスペリエンス",
  842. setConfigPage: "現在のページをデフォルト設定ページとして設定",
  843. wedata2github: "wedata アドレスを github ウェアハウスのミラー アドレスに変更",
  844. addOtherProp: "ルールプロパティを追加",
  845. addNextSelector: "セレクターのコンテンツを nextLink として追加",
  846. addPageSelector: "セレクタ コンテンツを pageElement として追加",
  847. propName: "ルールのプロパティ名を入力してください",
  848. propValue: "ルールのプロパティ値を入力してください",
  849. customFirst: "ローカルカスタムルールのキャッシュを無視する",
  850. rulesExample: "カスタムルールの詳しい説明",
  851. lastPage: "最後のページに到達しました",
  852. lastPageTips: "最後のページに到達した時にヒントを表示する"
  853. }
  854. },
  855. {
  856. name: "Русский",
  857. match: ["ru", "ru-RU"],
  858. lang: {
  859. enableDebug: "Включить отладку",
  860. updateNotification: "Уведомление после обновления правила",
  861. disable: "Выключить",
  862. disableSite: "Включить/выключить на сайте",
  863. disableSiteTips: "Выключено для этого сайта",
  864. enableSiteTips: "Включено для этого сайта",
  865. enable: "Включить",
  866. toTop: "Наверх",
  867. toBottom: "Вниз",
  868. current: "Текущая страница",
  869. forceIframe: "Подгрузить ещё страницу",
  870. cancelForceIframe: "Отменить подгрузку",
  871. configure: "Настройки",
  872. firstUpdate: "Нажмите здесь, чтобы инициализировать правила",
  873. update: "Обновить правила",
  874. click2update: "Нажмите, чтобы обновить правила",
  875. loadNow: "Загрузить следующую страницу",
  876. loadConfirm: "Сколько страниц вы хотите загрузить? (0 означает бесконечность)",
  877. noNext: "Ссылка на следующую страницу не найдена. Пожалуйста, создайте новое правило",
  878. passSec: "Обновлено #t# секунд назад",
  879. passMin: "Обновлено #t# минут назад",
  880. passHour: "Обновлено #t# часов назад",
  881. passDay: "Обновлено #t# дней назад",
  882. cantDel: "Нельзя удалить правила по умолчанию",
  883. confirmDel: "Вы уверены, что хотите удалить эту ссылку?",
  884. updateSucc: "Правила обновлены",
  885. beginUpdate: "Обновление. Пожалуйста, немного подождите",
  886. customUrls: "Ссылки с правилами для импорта. Одна ссылка на строку",
  887. customRules: "Введите пользовательские правила в формате Pagetual. <a href='#t#'>✍️Улучшить встроенные правила</a>",
  888. save: "Сохранить настройки",
  889. loadingText: "Следующая страница подгружается…",
  890. opacity: "Прозрачность",
  891. opacityPlaceholder: "0 - скрыть",
  892. hideBar: "Скрыть разделитель страниц",
  893. hideBarButNoStop: "Скрыть, но не останавливать",
  894. dbClick2Stop: "Двойной клик на странице для выключения",
  895. sortTitle: "Правило сортировки применится после следующего обновления правил",
  896. autoRun: "Автозапуск (режим черного списка)",
  897. autoLoadNum: "Количество страниц для предзагрузки",
  898. turnRate: "Подгрузить страницу, когда она будет в 【X】 раз больше высоты страницы от конца страницы",
  899. inputPageNum: "Введите номер страницы для перехода",
  900. enableHistory: "Записать историю после переключения страниц",
  901. enableHistoryAfterInsert: "Записать запись истории сразу после вставки, иначе записать после просмотра",
  902. contentVisibility: "Автоматически переключать contentVisibility для повышения производительности рендеринга",
  903. initRun: "Подгружать страницы сразу после открытия",
  904. preload: "Предзагрузка следующей страницы",
  905. click2ImportRule: "Нажмите, чтобы импортировать базовые правила: ",
  906. forceAllBody: "Присоединить страницу целиком?",
  907. openInNewTab: "Открыть дополнительные ссылки в новой вкладке",
  908. importSucc: "Импорт завершен",
  909. import: "Импорт",
  910. editCurrent: "Изменить правило для текущего сайта",
  911. editBlacklist: "Изменить черный список. Одна ссылка на строку. Поддерживаются метасимволы: ? и *",
  912. upBtnImg: "Иконка перехода к началу",
  913. downBtnImg: "Иконка перехода к концу",
  914. sideControllerIcon: "Значок боковой панели",
  915. loadingTextTitle: "Текст во время загрузки",
  916. dbClick2StopCtrl: "Ctrl",
  917. dbClick2StopAlt: "Alt",
  918. dbClick2StopShift: "Shift",
  919. dbClick2StopMeta: "Meta",
  920. dbClick2StopKey: "Клавиша",
  921. pageElementCss: "Пользовательский стиль для основных элементов страницы",
  922. customCss: "Полный пользовательский CSS",
  923. firstAlert: "Вы не импортировали базовое правило. Пожалуйста, выберите соответствующее правило для импорта",
  924. picker: "Pagetual: выбор элемента страницы",
  925. closePicker: "Закрыть окно Pagetual",
  926. pickerPlaceholder: "Если не знаете, что тут писать — оставьте поле пустым",
  927. pickerCheck: "Проверить и скопировать селектор",
  928. switchSelector: "Нажмите для выбора элемента",
  929. gotoEdit: "Перейти к редактированию правила с текущим селектором",
  930. manualMode: "Отключить автоматическую загрузку страниц. Загружать вручную с помощью стрелки вправо (или вызова события 'pagetual.next')",
  931. clickMode: "Отключить \"сшивание\" страниц. При прокрутке до конца автоматически переходить на следующую страницу",
  932. pageBarMenu: "Открывать меню кликом на середину панели страниц",
  933. nextSwitch: "Переключить ссылку на следующую страницу",
  934. arrowToScroll: "Листать страницы клавишами со стрелками влево и вправо",
  935. sideController: "Показать справа панель перемещения по вкладке",
  936. sideControllerScroll: "Переключатель прокрутки",
  937. sideControllerAlways: "Всегда показывать",
  938. hideLoadingIcon: "Скрыть анимацию загрузки",
  939. hideBarArrow: "Скрыть кнопки перемещения на разделителе",
  940. duplicate: "Похоже, Pagetual установлен несколько раз. Пожалуйста, удалите Pagetual из других менеджеров скриптов!",
  941. forceStateIframe: "Вставить полную страницу как iframe",
  942. forceStateDynamic: "Загружать динамический контент через iframe",
  943. forceStateDisable: "Отключить перелистывание страниц на этой станции",
  944. autoScrollRate: "Скорость прокрутки (1~1000)",
  945. disableAutoScroll: "Остановить автоматическую прокрутку",
  946. enableAutoScroll: "Включить автопрокрутку",
  947. toggleAutoScroll: "Переключить автопрокрутку",
  948. ruleRequest: "Запрос правил",
  949. page: "Страница ",
  950. prevPage: "Предыдущая страница",
  951. nextPage: "Следующая страница",
  952. errorRulesMustBeArray: "Правила должны быть массивом!",
  953. errorJson: "Ошибка разбора JSON. Пожалуйста, исправьте его",
  954. editSuccess: "Редактирование успешно",
  955. errorWrongUrl: "Ссылка некорректна. Пожалуйста, исправьте её",
  956. errorAlreadyExists: "Уже существует!",
  957. settingsSaved: "Настройки сохранены. Обновите страницы",
  958. iframe: "iframe",
  959. dynamic: "Динамически",
  960. reloadPage: "Редактирование завершено. Обновить страницу?",
  961. copied: "Скопировано",
  962. noValidContent: "Действительный контент не обнаружен, нажмите для просмотра",
  963. outOfDate: "Скрипт устарел, своевременно обновляйте до последней версии!",
  964. hideBarTips: "Скрыть панель разбиения на страницы, иммерсивный опыт",
  965. setConfigPage: "Установить текущую страницу в качестве страницы конфигурации по умолчанию",
  966. wedata2github: "Изменить адрес wedata на зеркальный адрес на складе github",
  967. addOtherProp: "Добавить свойство правила",
  968. addNextSelector: "Добавить содержимое селектора как nextLink",
  969. addPageSelector: "Добавить содержимое селектора как pageElement",
  970. propName: "Введите имя свойства правила",
  971. propValue: "Введите значение свойства правила",
  972. customFirst: "Игнорировать кеш для локальных пользовательских правил",
  973. rulesExample: "Подробное объяснение настраиваемых правил",
  974. lastPage: "Достигнута последняя страница",
  975. lastPageTips: "Показывать подсказки при достижении последней страницы"
  976. }
  977. }
  978. ];
  979. var langList = {};
  980. langData.forEach(lang => {
  981. langList[lang.match[0]] = lang.name;
  982. });
  983. var i18nData = langData[0].lang;
  984. function setLang(la) {
  985. for (let i = 0; i < langData.length; i++) {
  986. let lang = langData[i];
  987. if (lang && lang.match.indexOf(la) !== -1) {
  988. i18nData = lang.lang;
  989. break;
  990. }
  991. }
  992. }
  993. setLang(lang);
  994. var enableDebug = true;
  995. var _GM_xmlhttpRequest, _GM_registerMenuCommand, _GM_notification, _GM_addStyle, _GM_openInTab, _GM_info, _GM_setClipboard;
  996. function i18n(name, param) {
  997. return i18nData[name] ? i18nData[name].replace("#t#", param) : name;
  998. }
  999.  
  1000. function debug(str, title) {
  1001. if (enableDebug) {
  1002. console.log(
  1003. `%cPagetual v.${_GM_info.script.version}】 ${title ? title : 'debug'}:`,
  1004. 'color: yellow;font-size: large;font-weight: bold;background-color: darkblue;',
  1005. str
  1006. );
  1007. }
  1008. }
  1009.  
  1010. if (typeof GM_xmlhttpRequest !== 'undefined') {
  1011. _GM_xmlhttpRequest = GM_xmlhttpRequest;
  1012. } else if (typeof GM !== 'undefined' && typeof GM.xmlHttpRequest !== 'undefined') {
  1013. _GM_xmlhttpRequest = GM.xmlHttpRequest;
  1014. } else {
  1015. _GM_xmlhttpRequest = (f) => {fetch(f.url, {method: f.method || 'GET', body: f.data, headers: f.headers}).then(response => response.text()).then(data => {f.onload && f.onload({response: data})}).catch(f.onerror && f.onerror())};
  1016. }
  1017. if (typeof GM_registerMenuCommand !== 'undefined') {
  1018. _GM_registerMenuCommand = GM_registerMenuCommand;
  1019. } else if (typeof GM !== 'undefined' && typeof GM.registerMenuCommand !== 'undefined') {
  1020. _GM_registerMenuCommand = GM.registerMenuCommand;
  1021. } else {
  1022. _GM_registerMenuCommand = (s, f) => {debug(s); debug(f);};
  1023. }
  1024. if (typeof GM_info !== 'undefined') {
  1025. _GM_info = GM_info;
  1026. } else if (typeof GM !== 'undefined' && typeof GM.info !== 'undefined') {
  1027. _GM_info = GM.info;
  1028. } else {
  1029. _GM_info = {script: {}};
  1030. }
  1031. if (typeof GM_notification !== 'undefined') {
  1032. _GM_notification = GM_notification;
  1033. } else if (typeof GM !== 'undefined' && typeof GM.notification !== 'undefined') {
  1034. _GM_notification = GM.notification;
  1035. } else {
  1036. _GM_notification = (s) => {showTips(String(s.text || s));};
  1037. }
  1038. if (typeof GM_openInTab !== 'undefined') {
  1039. _GM_openInTab = GM_openInTab;
  1040. } else if (typeof GM !== 'undefined' && typeof GM.openInTab !== 'undefined') {
  1041. _GM_openInTab = GM.openInTab;
  1042. } else {
  1043. _GM_openInTab = (s,t) => {window.open(s); debug(t);};
  1044. }
  1045. if (typeof GM_addStyle !== 'undefined') {
  1046. _GM_addStyle = GM_addStyle;
  1047. } else if (typeof GM !== 'undefined' && typeof GM.addStyle !== 'undefined') {
  1048. _GM_addStyle = GM.addStyle;
  1049. } else {
  1050. _GM_addStyle = cssStr => {
  1051. let styleEle = document.createElement("style");
  1052. styleEle.innerHTML = cssStr;
  1053. document.head.appendChild(styleEle);
  1054. return styleEle;
  1055. };
  1056. }
  1057. if (typeof GM_setClipboard !== 'undefined') {
  1058. _GM_setClipboard = GM_setClipboard;
  1059. } else if (typeof GM !== 'undefined' && typeof GM.setClipboard !== 'undefined') {
  1060. _GM_setClipboard = GM.setClipboard;
  1061. } else {
  1062. _GM_setClipboard = (s, i) => {debug(s); debug(i);};
  1063. }
  1064. const _unsafeWindow = (typeof unsafeWindow === 'undefined') ? window : unsafeWindow;//兼容 ios userscripts 的寫法
  1065. const storage = {
  1066. supportGM: typeof GM_getValue === 'function' && typeof GM_getValue('a', 'b') !== 'undefined',
  1067. supportGMPromise: typeof GM !== 'undefined' && typeof GM.getValue === 'function' && typeof GM.getValue('a', 'b') !== 'undefined' && typeof GM.getValue('a', 'b').then === 'function',
  1068. supportCrossSave: function() {
  1069. return this.supportGM || this.supportGMPromise;
  1070. },
  1071. mxAppStorage: (function() {
  1072. try {
  1073. return window.external.mxGetRuntime().storage;
  1074. } catch(e) {
  1075. }
  1076. })(),
  1077. operaUJSStorage: (function() {
  1078. try {
  1079. return window.opera.scriptStorage;
  1080. } catch(e) {
  1081. }
  1082. })(),
  1083. setItem: function(key, value) {
  1084. if (this.supportGMPromise) {
  1085. GM.setValue(key, value);
  1086. if (value === "" && typeof GM !== 'undefined' && typeof GM.deleteValue !== 'undefined') {
  1087. GM.deleteValue(key);
  1088. }
  1089. } else if (this.supportGM) {
  1090. GM_setValue(key, value);
  1091. if (value === "" && typeof GM_deleteValue !== 'undefined') {
  1092. GM_deleteValue(key);
  1093. }
  1094. } else if (this.operaUJSStorage) {
  1095. this.operaUJSStorage.setItem(key, value);
  1096. } else if (this.mxAppStorage) {
  1097. this.mxAppStorage.setConfig(key, value);
  1098. } else if (window.localStorage) {
  1099. window.localStorage.setItem(key, value);
  1100. }
  1101. },
  1102. getItem: function(key, cb) {
  1103. var value;
  1104. if (this.supportGMPromise) {
  1105. value = GM.getValue(key).then(v => {cb(v);});
  1106. return;
  1107. } else if (this.supportGM) {
  1108. value = GM_getValue(key);
  1109. } else if (this.operaUJSStorage) {
  1110. value = this.operaUJSStorage.getItem(key);
  1111. } else if (this.mxAppStorage) {
  1112. value = this.mxAppStorage.getConfig(key);
  1113. } else if (window.localStorage) {
  1114. value = window.localStorage.getItem(key);
  1115. }
  1116. cb(value);
  1117. }
  1118. };
  1119. async function getData(key) {
  1120. return new Promise((resolve) => {
  1121. storage.getItem(key, value => {
  1122. resolve(value);
  1123. });
  1124. });
  1125. }
  1126. async function getListData(list, key) {
  1127. return new Promise((resolve) => {
  1128. storage.getItem(list, listData => {
  1129. let value;
  1130. if (listData) {
  1131. for(var i = 0; i < listData.length; i++) {
  1132. let data = listData[i];
  1133. if (data.k === key) {
  1134. value = data.v;
  1135. break;
  1136. }
  1137. }
  1138. }
  1139. resolve(value);
  1140. });
  1141. });
  1142. }
  1143. function setListData(list, key, value, length) {
  1144. storage.getItem(list, listData => {
  1145. if (!listData) {
  1146. listData = [];
  1147. }
  1148. listData = listData.filter(data => data && data.k !== key);
  1149. if (value !== "") {
  1150. listData.unshift({k: key, v: value});
  1151. if (listData.length > (length || 100)) {
  1152. listData.pop();
  1153. }
  1154. }
  1155. storage.setItem(list, listData);
  1156. });
  1157. }
  1158. const isMobile = ('ontouchstart' in document.documentElement);
  1159. const configPage = [`https://pagetual.hoothin.com/${lang === 'zh-CN' ? 'cn/' : ''}rule.html`,
  1160. "https://github.com/hoothin/UserScripts/tree/master/Pagetual",
  1161. "https://hoothin.github.io/UserScripts/Pagetual/"];
  1162. const firstRunPage = "https://pagetual.hoothin.com/firstRun";
  1163. const guidePage = /^https?:\/\/.*pagetual.*rule\.html/i;
  1164. const ruleImportUrlReg = /greasyfork\.org\/.*scripts\/438684(\-[^\/]*)?(\/discussions|\/?$|\/feedback)|github\.com\/hoothin\/UserScripts\/(tree\/master\/Pagetual|issues)|^https:\/\/pagetual\.hoothin\.com\/.*firstRun\.html/i;
  1165. const allOfBody = "body>*";
  1166. const mainSel = ["article,.article","[role=main],main,.main,#main","#results"];
  1167. const nextTextReg1 = new RegExp("\u005e\u7ffb\u003f\u005b\u4e0b\u540e\u5f8c\u6b21\u005d\u005b\u4e00\u30fc\u0031\u005d\u003f\u005b\u9875\u9801\u5f20\u5f35\u005d\u007c\u005e\u006e\u0065\u0078\u0074\u005b\u005c\u0073\u005f\u002d\u005d\u003f\u0070\u0061\u0067\u0065\u005c\u0073\u002a\u005b\u203a\u003e\u2192\u00bb\u005d\u003f\u0024\u007c\u6b21\u306e\u30da\u30fc\u30b8\u007c\u005e\u6b21\u3078\u003f\u0024\u007c\u0412\u043f\u0435\u0440\u0435\u0434", "i");
  1168. const nextTextReg2 = new RegExp("\u005e\u0028\u005b\u4e0b\u540e\u5f8c\u6b21\u005d\u005b\u4e00\u30fc\u0031\u005d\u003f\u005b\u7ae0\u8bdd\u8a71\u8282\u7bc0\u5e45\u005d\u007c\u006e\u0065\u0078\u0074\u002e\u003f\u0063\u0068\u0061\u0070\u0074\u0065\u0072\u007c\u00bb\u007c\u003e\u003e\u0029\u0028\u005b\u003a\uff1a\u005c\u002d\u005f\u2014\u005c\u0073\u005c\u002e\u3002\u003e\u0023\u00b7\u005c\u005b\u3010\u3001\uff08\u005c\u0028\u002f\u002c\uff0c\uff1b\u003b\u2192\u005d\u007c\u0024\u0029", "i");
  1169. const lazyImgAttr = ["data-lazy-src", "data-lazy", "data-isrc", "data-url", "data-orig-file", "zoomfile", "file", "original", "load-src", "imgsrc", "real_src", "src2", "origin-src", "data-lazyload", "data-lazyload-src", "data-lazy-load-src", "data-ks-lazyload", "data-ks-lazyload-custom", "data-src", "data-defer-src", "data-actualsrc", "data-cover", "data-original", "data-thumb", "data-imageurl", "data-placeholder", "lazysrc"];
  1170. var rulesData = {uninited: true, firstRun: true, sideController: !isMobile}, ruleUrls, updateDate, clickedSth = false, loadNowNum = 5, autoScrollRate = 50;
  1171. var isPause = false, manualPause = false, isHideBar = false, isLoading = false, curPage = 1, forceState = 0, autoScroll = 0, autoScrollInterval, bottomGap = 1000, autoLoadNum = -1, nextIndex = 0, stopScroll = false, clickMode = false, openInNewTab = 0, charset = "UTF-8", charsetValid = true, urlWillChange = false;
  1172. var tryTimes = 0, showedLastPageTips = false, rate = 1, author = '';
  1173.  
  1174. function getBody(doc) {
  1175. return doc.body || doc.querySelector('body') || doc;
  1176. }
  1177.  
  1178. function getElementByXpath(xpath, doc, contextNode) {
  1179. if (doc && doc.ownerDocument) doc = doc.ownerDocument;
  1180. doc = (doc && doc.evaluate) ? doc : document;
  1181. contextNode = contextNode || doc;
  1182. try {
  1183. let result = doc.evaluate(xpath, contextNode, null, XPathResult.ANY_UNORDERED_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. cur = body.querySelector(".paginator td strong");
  2727. if (cur) {
  2728. while (cur && !compareNodeName(cur, ["td"])) {
  2729. cur = cur.parentNode;
  2730. }
  2731. next = cur && cur.nextElementSibling;
  2732. if (next) next = next.querySelector("a");
  2733. }
  2734. }
  2735. if (!next) {
  2736. await sleep(1);
  2737. let pageDivs = body.querySelectorAll("[class*=pagination],[class*=Pagination]");
  2738. if (pageDivs && pageDivs.length) {
  2739. for (let i = pageDivs.length - 1; i >= 0; i--) {
  2740. let p = pageDivs[i];
  2741. if (/(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)/i.test(p.title || p.value || '')) {
  2742. next = p.querySelector("a,button,[type='button']") || p;
  2743. break;
  2744. } else if (/^(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)$/i.test((p.innerText || '').trim())) {
  2745. next = p.querySelector("a,button,[type='button']") || p;
  2746. break;
  2747. }
  2748. }
  2749. if (next && !this.linkHasHref(next)) {
  2750. if (!jsNext) jsNext = next;
  2751. next = null;
  2752. }
  2753. }
  2754. }
  2755. if (!next) {
  2756. let isApp = !!body.querySelector("main#app");
  2757. let aTags = body.querySelectorAll("a,button,[type='button'],.btn-action");
  2758. for (i = aTags.length - 1; i >= 0; i--) {
  2759. if (next1) break;
  2760. if (i % 100 === 0) {
  2761. await sleep(1);
  2762. }
  2763. let aTag = aTags[i];
  2764. let title = aTag.title || "";
  2765. let value = aTag.value || "";
  2766. let innerText = aTag.innerText || "";
  2767. if (innerText === "" || (title !== "" && title.length < innerText.length)) {
  2768. innerText = title;
  2769. }
  2770. if (innerText === "" || (value !== "" && value.length < innerText.length)) {
  2771. innerText = value;
  2772. }
  2773. if (innerText !== "") {
  2774. if (innerText === "§") continue;
  2775. innerText = innerText.trim();
  2776. if (innerText.length > 80) continue;
  2777. }
  2778. if (!this.verifyElement(aTag)) continue;
  2779. if (aTag.dataset && aTag.dataset.preview) continue;
  2780. let availableHref = aTag.href && aTag.href.length < 250 && !/^(javascript:|#)/.test(aTag.href);
  2781. if (availableHref && /next\-?(page)?$|\/video\/|\/vod\/play\//i.test(aTag.href)) continue;
  2782. if (compareNodeName(aTag.parentNode, ["blockquote"])) continue;
  2783. if (aTag.previousElementSibling && /\b(play|volume)\b/.test(aTag.previousElementSibling.className)) continue;
  2784. if (aTag.nextElementSibling && /\b(play|volume)\b/.test(aTag.nextElementSibling.className)) continue;
  2785. let isJs = !this.linkHasHref(aTag);
  2786. if (exist && isJs && !aTag.offsetParent) continue;
  2787. if (innerText) {
  2788. innerText = innerText.split(/\n/)[0].replace(/ /g, '');
  2789. if (isJs && /^(»|>>|>|›|→|❯)$/.test(innerText)) continue;
  2790. if (innerText && innerText.length <= 25) {
  2791. if (!next1) {
  2792. if (nextTextReg1.test(innerText)) {
  2793. if (isJs) {
  2794. if (!nextJs1) nextJs1 = aTag;
  2795. } else {
  2796. next1 = aTag;
  2797. }
  2798. }
  2799. }
  2800. if (!next4) {
  2801. if (!next2) {
  2802. if (nextTextReg2.test(innerText) || /nextpage|pager\-older/i.test(aTag.className) || /^(»|>>)$/.test(innerText)) {
  2803. if (isJs) {
  2804. if (!nextJs2) nextJs2 = aTag;
  2805. } else {
  2806. next2 = aTag;
  2807. }
  2808. }
  2809. }
  2810. if (!isApp && !next3 && !isJs) {
  2811. if (/^(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)$/i.test(aTag.textContent) && aTag.parentNode.hasAttribute && !aTag.parentNode.hasAttribute("jsaction")) {
  2812. next3 = aTag;
  2813. }
  2814. }
  2815. }
  2816. }
  2817. }
  2818. if (isJs) continue;
  2819. if (!next4) {
  2820. let prevEle = aTag.previousElementSibling;
  2821. if (prevEle && compareNodeName(prevEle, ["b", "span", "strong"])) {
  2822. if (/^\d+$/.test(aTag.innerText.trim()) && /^\d+$/.test(prevEle.innerText.trim()) && parseInt(aTag.innerText) === parseInt(prevEle.innerText) + 1) {
  2823. next4 = aTag;
  2824. }
  2825. }
  2826. }
  2827. if (urlWillChange) continue;
  2828. if (!next4 && availableHref) {
  2829. let aHref = aTag.href.indexOf("http") === 0 ? aTag.href : this.canonicalUri(aTag.href);
  2830. if (aHref.indexOf(location.hostname) === -1) continue;
  2831. let _aHref = aHref.replace("?&", "?").replace("index.php?", "?");
  2832. if (preStr || afterStr) {
  2833. let _aHrefTrim = _aHref;
  2834. if (preStr) _aHrefTrim = _aHrefTrim.replace(preStr, "");
  2835. if (afterStr) _aHrefTrim = _aHrefTrim.replace(afterStr, "");
  2836. if (_aHrefTrim == pageNum + 1) {
  2837. next4 = aTag;
  2838. }
  2839. } else if (this.curUrl !== aHref) {
  2840. _aHref = _aHref.replace(/\.s?html?$/i, "").toLowerCase();
  2841. if (_aHref.indexOf(_url) !== -1) {
  2842. let pageTwoMatch = _aHref.replace(_url, "").match(pageTwoReg);
  2843. if (pageTwoMatch) {
  2844. afterStr = pageTwoMatch[2];
  2845. next4 = aTag;
  2846. }
  2847. }
  2848. }
  2849. if (next4 && !/page/.test(next4.href)) {
  2850. let curHref = next4.getAttribute("href");
  2851. let curPageReg = new RegExp("(.*)" + (pageNum + 1) + afterStr.replace(/([\.\?])/g, '\\$1'));
  2852. let otherPageHref = curHref.replace(curPageReg, `$1${pageNum}${afterStr}`);
  2853. let otherPageEle = body.querySelector(`a[href='${otherPageHref}']`);
  2854. if (!otherPageEle) {
  2855. otherPageHref = curHref.replace(curPageReg, `$1${pageNum + 2}${afterStr}`);
  2856. otherPageEle = body.querySelector(`a[href='${otherPageHref}']`);
  2857. }
  2858. if (otherPageEle) {
  2859. let parent = otherPageEle.parentNode;
  2860. if (parent && parent.parentNode) {
  2861. parent = parent.parentNode;
  2862. if (parent.parentNode) {
  2863. parent = parent.parentNode;
  2864. }
  2865. }
  2866. if (parent && parent.contains(next4) && !/^\d+$/.test(next4.innerText.trim())) {
  2867. next4 = null;
  2868. }
  2869. }
  2870. }
  2871. }
  2872. }
  2873. if (next2 && doubtTextReg.test(next2.innerText)) {
  2874. next2 = this.verifyNext(next2, doc, false);
  2875. }
  2876. if (nextJs2 && doubtTextReg.test(nextJs2.innerText)) {
  2877. nextJs2 = this.verifyNext(nextJs2, doc, true);
  2878. }
  2879. if (next3) {
  2880. next3 = this.verifyNext(next3, doc, false);
  2881. }
  2882. }
  2883. if (!next) next = next1 || next4 || next3 || next2;
  2884. if (!next && location.pathname + location.search !== "/") {
  2885. next = jsNext || nextJs1 || nextJs2;
  2886. if (next && next.parentNode.className && next.parentNode.className.indexOf && next.parentNode.className.indexOf('tab') !== -1) next = null;
  2887. }
  2888. if (next && next.classList && (next.classList.contains("results-more") || next.classList.contains("no"))) next = null;
  2889. if (next && next.hasAttribute && next.hasAttribute("disabled")) next = null;
  2890. if (next && next.parentNode.href && compareNodeName(next.parentNode, ["a"])) next = next.parentNode;
  2891. return {next:next, canSave:canSave};
  2892. }
  2893.  
  2894. verifyNext(next, doc, isJs) {
  2895. if (!next) return null;
  2896. if (!isJs) {
  2897. let href = next.getAttribute("href");
  2898. if (href && !/\d/.test(next.getAttribute("href"))) {
  2899. return null;
  2900. }
  2901. }
  2902. if (next.previousElementSibling && compareNodeName(next.previousElementSibling, ["br"])) return null;
  2903. let eles = [];
  2904. if (next.innerText && next.innerText.indexOf("\n") === -1) {
  2905. eles = getAllElements(`//${next.nodeName}[text()='${next.innerText}']`, doc);
  2906. }
  2907. if (eles.length >= 2 && eles[0].href !== eles[1].href) {
  2908. next = null;
  2909. } else if (doc === document) {
  2910. let left = getElementLeft(next);
  2911. if (left < 20 || (document.documentElement.scrollWidth > 500 && left < 250)) {
  2912. next = null;
  2913. } else {
  2914. let top = getElementTop(next);
  2915. if (top < 20 || (left < window.innerWidth / 3 && top < window.innerHeight / 3)) {
  2916. next = null;
  2917. } else {
  2918. let bottom = top + next.offsetHeight || 0;
  2919. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  2920. if (scrollH - bottom < 10) next = null;
  2921. }
  2922. }
  2923. }
  2924. return next;
  2925. }
  2926.  
  2927. canonicalUri(src) {
  2928. if (!src) {
  2929. return "";
  2930. }
  2931. if (src.charAt(0) === "#") return this.curUrl + src;
  2932. if (src.charAt(0) === "?") return this.curUrl.replace(/^([^\?#]+).*/, "$1" + src);
  2933. let origin = location.protocol + '//' + location.host;
  2934. let url = this.basePath || origin;
  2935. url = url.replace(/(\?|#).*/, "");
  2936. if (/https?:\/\/[^\/]+$/.test(url)) url = url + '/';
  2937. if (url.indexOf("http") !== 0) url = origin + url;
  2938. var root_page = /^[^\?#]*\//.exec(url)[0],
  2939. root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  2940. absolute_regex = /^\w+\:\/\//;
  2941. this.updateUrl = false;
  2942. while (src.indexOf("../") === 0) {
  2943. src = src.substr(3);
  2944. root_page = root_page.replace(/\/[^\/]+\/$/, "/");
  2945. this.updateUrl = true;
  2946. }
  2947. src = src.replace(/\.\//, "");
  2948. if (/^\/\/\/?/.test(src)) {
  2949. src = location.protocol + src;
  2950. }
  2951. return (absolute_regex.test(src) ? src : ((src.charAt(0) === "/" ? root_domain : root_page) + src));
  2952. }
  2953.  
  2954. getLinkByPage(url, pageNum) {
  2955. if (!url) return null;
  2956. if (this.curSiteRule.pageNum) {
  2957. let result = this.curSiteRule.pageNum;
  2958. let strMatch = result.match(/\{.*?}/);
  2959. if (!strMatch) return null;
  2960. let urlReg = new RegExp("(" + result.replace(strMatch[0], ")\\d+(") + ")", "i");
  2961. let code = strMatch[0].replace(/^{/, "").replace(/}$/, "").replace(/\$p/g, pageNum);
  2962. if (code === pageNum) {
  2963. result = url.replace(urlReg, "$1" + code + "$2");
  2964. } else {
  2965. try {
  2966. code = Function('"use strict";return ' + code)();
  2967. if (code && code % 1 == 0) {
  2968. result = url.replace(urlReg, "$1" + code + "$2");
  2969. } else return null;
  2970. } catch(e) {
  2971. debug(e);
  2972. }
  2973. }
  2974. if (result != url) {
  2975. return result;
  2976. }
  2977. }
  2978. return url.replace(/([&\/\?](p=|page[=\/_-]?))\d+/i, "$1" + pageNum).replace(/([_-])\d+\./i, "$1" + pageNum + ".");
  2979. }
  2980.  
  2981. getPageNumFromUrl(url, defaultPage) {
  2982. if (!url) return defaultPage;
  2983. if (this.curSiteRule.pageNum) {
  2984. let result = this.curSiteRule.pageNum;
  2985. let strMatch = result.match(/\{.*?}/);
  2986. if (!strMatch) return defaultPage;
  2987. let urlReg = new RegExp(".*" + result.replace(strMatch[0], "(\\d+)") + ".*", "i");
  2988. let curShowNum = url.replace(urlReg, "$1");
  2989. if (curShowNum !== url) {
  2990. let code = strMatch[0].replace(/^{/, "").replace(/}$/, "");
  2991. if (code === "$p") {
  2992. return curShowNum;
  2993. } else {
  2994. try {
  2995. let page1 = parseInt(Function('"use strict";return ' + code.replace("$p", "0"))());
  2996. let page2 = parseInt(Function('"use strict";return ' + code.replace("$p", "1"))());
  2997. let numGap = page2 - page1;
  2998. let _page = (parseInt(curShowNum) - page1) / numGap;
  2999. if (_page && _page % 1 === 0) return _page;
  3000. else {
  3001. this.curSiteRule.pageNum = null;
  3002. return defaultPage;
  3003. }
  3004. } catch(e) {
  3005. debug(e);
  3006. }
  3007. }
  3008. } else {
  3009. return defaultPage;
  3010. }
  3011. }
  3012. let pageNum = url.replace(/.*[&\/\?](p=|page[=\/_-]?)(\d+).*/i, "$2");
  3013. return pageNum === url ? defaultPage : (pageNum.length > 4 ? defaultPage : pageNum);
  3014. }
  3015.  
  3016. async getNextLink(doc, exist) {
  3017. let nextLink = null, page, href;
  3018. let getNextLinkByForm = (form, submitBtn, n) => {
  3019. let params = [];
  3020. let formData = new FormData(form);
  3021. if (submitBtn && submitBtn.getAttribute) {
  3022. let btnValue, btnName;
  3023. btnName = submitBtn.getAttribute("name");
  3024. btnValue = submitBtn.getAttribute("value");
  3025. if (btnName && btnValue) params = [btnName + "=" + encodeURIComponent(btnValue)];
  3026. }
  3027. for (let [key, value] of formData) {
  3028. if (n && /^(p|page)$/i.test(key)) {
  3029. params.push(key + '=' + n);
  3030. } else {
  3031. params.push(key + '=' + encodeURIComponent(value));
  3032. }
  3033. }
  3034. params = params.join('&');
  3035. return form.action + (form.action.indexOf('?') === -1 ? '?' : '&') + params + (form.method === 'post' ? '#p{' + params + '}' : '');
  3036. };
  3037. if (this.curSiteRule.pageElementByJs) {
  3038. this.nextLinkHref = "#";
  3039. return true;
  3040. } else if (this.curSiteRule.nextLinkByJs) {
  3041. try {
  3042. let over = _url => {};
  3043. let targetUrl = await ((typeof this.curSiteRule.nextLinkByJs === 'function') ? this.curSiteRule.nextLinkByJs : new AsyncFunction("doc", '"use strict";' + this.curSiteRule.nextLinkByJs))(doc);
  3044. if (targetUrl) nextLink = {href: targetUrl};
  3045. } catch(e) {
  3046. debug(e);
  3047. }
  3048. } else if (this.curSiteRule.nextLinkByUrl) {
  3049. let targetUrl = this.curUrl.replace(new RegExp(this.curSiteRule.nextLinkByUrl[0], "i"), this.curSiteRule.nextLinkByUrl[1]);
  3050. if (targetUrl !== this.curUrl) {
  3051. let includeSel = this.curSiteRule.nextLinkByUrl[2];
  3052. let excludeSel = this.curSiteRule.nextLinkByUrl[3];
  3053. if (includeSel) {
  3054. includeSel = includeSel.trim();
  3055. if (!getElement(includeSel, doc)) {
  3056. this.nextLinkHref=false;
  3057. return null;
  3058. }
  3059. }
  3060. if (excludeSel) {
  3061. excludeSel = excludeSel.trim();
  3062. if (getElement(excludeSel, doc)) {
  3063. this.nextLinkHref=false;
  3064. return null;
  3065. }
  3066. }
  3067. let reps = targetUrl.match(/{.*?}/g);
  3068. if (reps) {
  3069. reps.forEach(rep => {
  3070. let code = rep.replace("{", "").replace("}", "").replace(/\(\)/g, "0");
  3071. let result = code.match(/^(\d*)\+1$/);
  3072. if (result) {
  3073. result = parseInt(result[1] || 1) + 1;
  3074. } else {
  3075. try {
  3076. result = Function('"use strict";return ' + code)();
  3077. } catch(e) {
  3078. debug(e);
  3079. }
  3080. }
  3081. targetUrl = targetUrl.replace(rep, result);
  3082. });
  3083. }
  3084. }
  3085. nextLink = {href: targetUrl};
  3086. } else if (typeof this.curSiteRule.nextLink !== 'undefined') {
  3087. let nextLinkSel = this.curSiteRule.nextLink;
  3088. if (nextLinkSel != 0) {
  3089. if (Array && Array.isArray && Array.isArray(nextLinkSel)) {
  3090. nextLink = getElement(nextLinkSel[nextIndex], doc, null, true);
  3091. if (!nextLink && curPage === 1 && nextIndex !== 0) {
  3092. nextIndex = 0;
  3093. nextLink = getElement(nextLinkSel[nextIndex], doc, null, true);
  3094. }
  3095. } else nextLink = getElement(nextLinkSel, doc, null, true);
  3096. }
  3097. if (nextLink && (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2)) {
  3098. let form = doc.querySelector('#search-form');
  3099. if (!nextLink.href && nextLink.hasAttribute && nextLink.hasAttribute("onclick") && form) {
  3100. if (/^\d+$/.test(nextLink.innerText)) {
  3101. nextLink.href = getNextLinkByForm(form, nextLink, nextLink.innerText);
  3102. }
  3103. } else if (compareNodeName(nextLink, ["input"]) || nextLink.type === "submit") {
  3104. form = nextLink.parentNode;
  3105. while (form) {
  3106. if (compareNodeName(form, ["form"])) break;
  3107. else form = form.parentNode;
  3108. }
  3109. if (form) {
  3110. nextLink.href = getNextLinkByForm(form, nextLink);
  3111. }
  3112. }
  3113. if (nextLink.href && this.curSiteRule.action != 0) {
  3114. nextLink.href = nextLink.href.replace(/#p{.*/, "");
  3115. }
  3116. }
  3117. } else {
  3118. page = await this.getPage(doc, exist);
  3119. nextLink = page.next;
  3120. if (nextLink) {
  3121. if (compareNodeName(nextLink, ["input"]) || nextLink.type === "submit") {
  3122. if (!/next/i.test(nextLink.getAttribute("onclick"))) {
  3123. let form = nextLink.parentNode;
  3124. while (form) {
  3125. if (compareNodeName(form, ["form"])) break;
  3126. else form = form.parentNode;
  3127. }
  3128. if (form) {
  3129. nextLink.href = getNextLinkByForm(form, nextLink);
  3130. }
  3131. }
  3132. }
  3133. let parent = nextLink;
  3134. while (parent && !compareNodeName(parent, ["body"])) {
  3135. if (parent.hasAttribute && parent.hasAttribute("disabled")) {
  3136. this.nextLinkHref = false;
  3137. return null;
  3138. }
  3139. if (parent.className && parent.classList) {
  3140. if (parent.classList.contains("noClick") || parent.classList.contains("no-pages") || parent.classList.contains("disabled")) {
  3141. this.nextLinkHref = false;
  3142. return null;
  3143. }
  3144. }
  3145. if (parent.style && parent.style.display === "none") {
  3146. this.nextLinkHref = false;
  3147. return null;
  3148. }
  3149. parent = parent.parentNode;
  3150. }
  3151. if (doc === document) {
  3152. if (!this.linkHasHref(nextLink)) {
  3153. if ((clickedSth && this.curSiteRule.smart) || !isVisible(nextLink, _unsafeWindow)) {
  3154. this.nextLinkHref = false;
  3155. return null;
  3156. }
  3157. let video = document.querySelector("video,iframe[id*=play],[id*=play]>iframe,iframe[src*=player],iframe[src*=m3u8]");
  3158. if (video) {
  3159. if (video.offsetParent && video.name !== 'pagetual-iframe') {
  3160. let scrollWidth = video.scrollWidth || video.offsetWidth;
  3161. let scrollHeight = video.scrollHeight || video.offsetHeight;
  3162. if (compareNodeName(video, ["iframe"])) {
  3163. } else if (scrollWidth > 100 && scrollHeight > 100) {
  3164. let winWidth = window.innerWidth || document.documentElement.clientWidth;
  3165. let winHeight = window.innerHeight || document.documentElement.clientHeight;
  3166. if (scrollWidth > winWidth>>1 && scrollHeight > winHeight>>1) {
  3167. debug("Disable when large media found");
  3168. } else {
  3169. video = null;
  3170. }
  3171. } else {
  3172. video = null;
  3173. }
  3174. } else {
  3175. video = null;
  3176. }
  3177. }
  3178. if (video) {
  3179. isPause = true;
  3180. this.clearAddedElements();
  3181. this.nextLinkHref = false;
  3182. return null;
  3183. }
  3184. }
  3185.  
  3186. let nextLinkCs = _unsafeWindow.getComputedStyle(nextLink);
  3187. if (nextLinkCs.cursor === "not-allowed") {
  3188. this.nextLinkHref = false;
  3189. return null;
  3190. }
  3191. this.initNext = nextLink;
  3192. }
  3193. let form = doc.querySelector('#search-form');
  3194. if (!nextLink.href && nextLink.hasAttribute("onclick") && form) {
  3195. if (form && /^\d+$/.test(nextLink.innerText)) {
  3196. href = getNextLinkByForm(form, nextLink, nextLink.innerText);
  3197. }
  3198. }
  3199. }
  3200. }
  3201. if (nextLink) {
  3202. if (!this.checkStopSign(nextLink, doc)) {
  3203. if (curPage > 1) {
  3204. if (rulesData.lastPageTips) {
  3205. showTips(i18n("lastPage"), "", 800);
  3206. }
  3207. _unsafeWindow.postMessage({
  3208. action: "lastPage",
  3209. command: 'pagetual'
  3210. }, '*');
  3211. }
  3212. return null;
  3213. }
  3214. if (this.curSiteRule.action == 3) {
  3215. if (doc == document) debug(nextLink, 'Next link');
  3216. this.nextLinkHref = '#';
  3217. } else {
  3218. let needUrl = (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2);
  3219. if (!href) href = nextLink.href;
  3220. if (href && nextLink.getAttribute) {
  3221. let _href = nextLink.getAttribute("href");
  3222. if (_href) {
  3223. let realHref = _href.replace(location.href, "");
  3224. if (realHref.charAt(0) === "#" || realHref === "?"){
  3225. href = "#";
  3226. } else {
  3227. href = _href;
  3228. }
  3229. } else if (_href === "") {
  3230. href = _href;
  3231. }
  3232. }
  3233.  
  3234. if (needUrl && (href === "" || href === null)) {
  3235. this.nextLinkHref = false;
  3236. } else if (needUrl && /^(javascript:|#)/.test(href)) {
  3237. this.nextLinkHref = false;
  3238. } else {
  3239. this.nextLinkHref = (href && !/^(javascript:|#)/.test(href)) ? this.canonicalUri(href) : "#";
  3240. let tempUrl = this.nextLinkHref;
  3241. 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 + "#"))) {
  3242. this.nextLinkHref = false;
  3243. } else if (doc === document) {
  3244. debug(nextLink, 'Next link');
  3245. }
  3246. }
  3247. }
  3248. } else {
  3249. this.nextLinkHref = false;
  3250. }
  3251. this.nextLinkEle = nextLink;
  3252. this.preload();
  3253. return nextLink;
  3254. }
  3255.  
  3256. compareUrl(url1, url2) {
  3257. if (url1 === url2) return true;
  3258. if (!url1 || !url2) return false;
  3259. let url1Arr = url1.split("?");
  3260. let url2Arr = url2.split("?");
  3261. if (url1Arr[0] != url2Arr[0]) return false;
  3262. if (!url1Arr[1] || !url2Arr[1]) return false;
  3263. url1Arr = url1Arr[1].split("&").sort().join("&");
  3264. url2Arr = url2Arr[1].split("&").sort().join("&");
  3265. return url1Arr === url2Arr;
  3266. }
  3267.  
  3268. filterEles(doc, eles) {
  3269. let filter = this.curSiteRule.filter;
  3270. if (!filter || !eles || eles.length === 0) return;
  3271. if (eles.length === 1) {
  3272. eles = eles[0].children;
  3273. if (eles.length === 1) {
  3274. eles = eles[0].children;
  3275. }
  3276. }
  3277. if (typeof filter === "string") {
  3278. if (/^\d+$/.test(filter)) {
  3279. filter = {count: parseInt(filter)};
  3280. } else filter = {words: filter};
  3281. }
  3282. [].forEach.call(eles, ele => {
  3283. if (!ele.parentNode) return;
  3284. let canKeep = (() => {
  3285. let innerText = (ele.innerText && ele.innerText.trim()) || "";
  3286. if (filter.count) {
  3287. if (innerText.length < filter.count) return false;
  3288. }
  3289. if (filter.words) {
  3290. let wordsRegExp = new RegExp(filter.words, "i");
  3291. if (innerText && wordsRegExp.test(innerText)) return false;
  3292. }
  3293. if (filter.link) {
  3294. let linkRegExp = new RegExp(filter.link, "i");
  3295. if (compareNodeName(ele, ["a"]) && linkRegExp.test(ele.href)) return false;
  3296. let aChildren = ele.querySelectorAll("a");
  3297. for (let i = 0; i < aChildren.length; i++) {
  3298. let child = aChildren[i];
  3299. if (linkRegExp.test(child.href)) return false;
  3300. }
  3301. }
  3302. if (filter.selector) {
  3303. if (getElement(filter.selector, doc, ele)) return false;
  3304. }
  3305. return true;
  3306. })();
  3307. if (!canKeep) {
  3308. ele.parentNode.removeChild(ele);
  3309. }
  3310. });
  3311. }
  3312.  
  3313. checkStopSign(nextLink, doc) {
  3314. if (this.curSiteRule.stopSign) {
  3315. let typeArray = Array && Array.isArray && Array.isArray(this.curSiteRule.stopSign);
  3316. let typeObject = !typeArray && (this.curSiteRule.stopSign.include || this.curSiteRule.stopSign.exclude || this.curSiteRule.stopSign.pageNum);
  3317. if (typeArray || typeObject) {
  3318. let includeSel, excludeSel, curSign, maxSign;
  3319. if (typeArray) {
  3320. includeSel = this.curSiteRule.stopSign[0];
  3321. excludeSel = this.curSiteRule.stopSign[1];
  3322. curSign = this.curSiteRule.stopSign[2];
  3323. maxSign = this.curSiteRule.stopSign[3];
  3324. if (Array && Array.isArray && Array.isArray(includeSel) && !curSign) {
  3325. curSign = includeSel;
  3326. includeSel = false;
  3327. }
  3328. if (excludeSel && Array && Array.isArray && Array.isArray(excludeSel) && !maxSign) {
  3329. maxSign = excludeSel;
  3330. excludeSel = false;
  3331. }
  3332. } else {
  3333. includeSel = this.curSiteRule.stopSign.include;
  3334. excludeSel = this.curSiteRule.stopSign.exclude;
  3335. curSign = this.curSiteRule.stopSign.pageNum;
  3336. }
  3337. if (includeSel) {
  3338. includeSel = includeSel.trim();
  3339. if (!getElement(includeSel, doc)) {
  3340. isPause = true;
  3341. this.nextLinkHref = false;
  3342. return false;
  3343. }
  3344. }
  3345. if (excludeSel) {
  3346. excludeSel = excludeSel.trim();
  3347. if (getElement(excludeSel, doc)) {
  3348. isPause = true;
  3349. this.nextLinkHref = false;
  3350. return false;
  3351. }
  3352. }
  3353. if (curSign) {
  3354. if (!maxSign) maxSign = curSign.slice(2);
  3355. let currentEle = getElement(curSign[0], doc);
  3356. let maxEle = getElement(maxSign[0], doc);
  3357. if (currentEle && maxEle) {
  3358. let currentSignNum, maxSignNum;
  3359. if (/\(.*\)/.test(curSign[1])) {
  3360. currentSignNum = currentEle.innerText.match(new RegExp(curSign[1]));
  3361. if (currentSignNum) currentSignNum = currentSignNum[1];
  3362. } else if (currentEle.getAttribute) {
  3363. currentSignNum = currentEle.getAttribute(curSign[1]);
  3364. }
  3365. if (/\(.*\)/.test(maxSign[1])) {
  3366. maxSignNum = maxEle.innerText.match(new RegExp(maxSign[1]));
  3367. if (maxSignNum) maxSignNum = maxSignNum[1];
  3368. } else if (maxEle.getAttribute) {
  3369. maxSignNum = maxEle.getAttribute(maxSign[1]);
  3370. }
  3371. if (currentSignNum && maxSignNum && currentSignNum == maxSignNum) {
  3372. isPause = true;
  3373. this.nextLinkHref = false;
  3374. return false;
  3375. }
  3376. }
  3377. }
  3378. } else {
  3379. try {
  3380. let stopSign = ((typeof this.curSiteRule.stopSign === 'function') ? this.curSiteRule.stopSign : Function("doc", "nextLink", '"use strict";' + this.curSiteRule.stopSign))(doc, nextLink);
  3381. if (stopSign) {
  3382. isPause = true;
  3383. this.nextLinkHref = false;
  3384. return false;
  3385. }
  3386. } catch(e) {
  3387. debug(e);
  3388. }
  3389. }
  3390. }
  3391. return true;
  3392. }
  3393.  
  3394. preloadImageHandler() {
  3395. if (this.preloadingImage || !this.unCheckedImgs.length) return;
  3396. this.preloadingImage = true;
  3397. setTimeout(() => {
  3398. this.preloadingImage = false;
  3399. this.preloadImageHandler();
  3400. }, 10);
  3401. let iSrc = this.unCheckedImgs.shift();
  3402. let img = document.createElement('img');
  3403. img.src = iSrc;
  3404. this.preloadDiv.appendChild(img);
  3405. }
  3406.  
  3407. preload() {
  3408. if (!rulesData.preload) return;
  3409. if (this.curSiteRule.preload === 0) return;
  3410. if (!this.nextLinkHref || this.nextLinkHref == "#") return;
  3411. if (this.readyStateUnComplete) return;
  3412. if (document.readyState !== 'complete') {
  3413. this.readyStateUnComplete = true;
  3414. let self = this;
  3415. window.addEventListener("load", e => {
  3416. self.readyStateUnComplete = false;
  3417. self.preload();
  3418. });
  3419. return;
  3420. }
  3421. let self = this, url = this.nextLinkHref;
  3422. let postParams = url.match(/#p{(.*)}$/);
  3423. if (postParams) {
  3424. postParams = postParams[1];
  3425. url = url.replace(/#p{.*/, "");
  3426. }
  3427. _GM_xmlhttpRequest({
  3428. url: url,
  3429. method: postParams ? 'POST' : 'GET',
  3430. data: postParams,
  3431. overrideMimeType: 'text/html;charset=' + charset,
  3432. headers: {
  3433. 'Referer': location.href,
  3434. 'User-Agent': navigator.userAgent,
  3435. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + charset,
  3436. },
  3437. timeout: 10000,
  3438. onload: function(res) {
  3439. var doc = null;
  3440. try {
  3441. doc = document.implementation.createHTMLDocument('');
  3442. doc.documentElement.innerHTML = createHTML(res.response);
  3443. var body = getBody(doc);
  3444. if (!self.preloadDiv) {
  3445. self.preloadDiv = document.createElement('div');
  3446. self.preloadDiv.id = "pagetual-preload";
  3447. self.preloadDiv.style.cssText = 'display:none!important;';
  3448. getBody(document).appendChild(self.preloadDiv);
  3449. self.checkedImgs = {};
  3450. self.unCheckedImgs = [];
  3451. }
  3452. let code = self.curSiteRule.preloadImages;
  3453. if (code) {
  3454. let imgSrcArr = new Function("doc", '"use strict";' + code)(doc);
  3455. if (imgSrcArr && imgSrcArr.length) {
  3456. imgSrcArr.forEach(imgSrc => {
  3457. if (imgSrc && !self.checkedImgs[imgSrc]) {
  3458. self.checkedImgs[imgSrc] = true;
  3459. self.unCheckedImgs.push(imgSrc);
  3460. }
  3461. });
  3462. }
  3463. self.preloadImageHandler();
  3464. } else if (code !== 0 && code !== false) {
  3465. if (body && body.firstChild) {
  3466. self.lazyImgAction(body.children, doc);
  3467. }
  3468. [].forEach.call(doc.images, i => {
  3469. let iSrc = i.src;
  3470. if (iSrc && !self.checkedImgs[iSrc]) {
  3471. self.checkedImgs[iSrc] = true;
  3472. self.unCheckedImgs.push(iSrc);
  3473. }
  3474. });
  3475. self.preloadImageHandler();
  3476. }
  3477. }
  3478. catch(e) {
  3479. debug(e);
  3480. return;
  3481. }
  3482. }
  3483. });
  3484. }
  3485.  
  3486. getInsert(refresh) {
  3487. if (refresh) {
  3488. this.insert = null;
  3489. }
  3490. if (this.insert && this.insert.parentNode && document.documentElement.contains(this.insert)) {
  3491. return this.insert;
  3492. }
  3493. if (this.curSiteRule.insert) {
  3494. let insertSel = this.curSiteRule.insert;
  3495. if (Array && Array.isArray && Array.isArray(insertSel)) {
  3496. insertSel = insertSel[nextIndex < insertSel.length ? nextIndex : 0];
  3497. }
  3498. this.insert = getElement(insertSel, document, null, true);
  3499. } else {
  3500. this.docPageElement = null;
  3501. let pageElement = this.getPageElement(document, _unsafeWindow);
  3502. if (this.curSiteRule.smart && this.nextLinkHref == "#" && this.curSiteRule.pageElement === 'body') {
  3503. debug("Stop as jsNext & whole body");
  3504. isPause = true;
  3505. return null;
  3506. }
  3507. if (pageElement && pageElement.length > 0) {
  3508. let pEIndex = pageElement.length - 1;
  3509. let pELast = pageElement[pEIndex];
  3510. while(pELast && compareNodeName(pELast, ["link", "meta", "style", "script"])) {
  3511. pEIndex--;
  3512. pELast = pageElement[pEIndex];
  3513. }
  3514. this.insert = pELast.nextSibling ? pELast.nextSibling : pELast.parentNode.appendChild(document.createTextNode(' '));
  3515. }
  3516. }
  3517. return this.insert;
  3518. }
  3519.  
  3520. pageInit(doc, eles) {
  3521. let code = this.curSiteRule.pageInit;
  3522. if (code) {
  3523. let initFunc = ((typeof code == 'function') ? code : Function("doc", "eles", '"use strict";' + code));
  3524. let checkInit = (resolve) => {
  3525. try {
  3526. if (initFunc(doc, eles) === false) {
  3527. setTimeout(() => {
  3528. checkInit(resolve);
  3529. }, 100);
  3530. } else {
  3531. resolve(true);
  3532. }
  3533. } catch(e) {
  3534. resolve(false);
  3535. debug(e);
  3536. }
  3537. };
  3538. return new Promise((resolve) => {
  3539. checkInit(function(e) {
  3540. resolve(e)
  3541. });
  3542. })
  3543. }
  3544. }
  3545.  
  3546. pageAction(doc, eles) {
  3547. let code = this.curSiteRule.pageAction;
  3548. if (code) {
  3549. try {
  3550. ((typeof code == 'function') ? code : Function("doc", "eles", '"use strict";' + code))(doc, eles);
  3551. } catch(e) {
  3552. debug(e);
  3553. }
  3554. }
  3555. this.openInNewTab(eles);
  3556. this.replaceElement(doc);
  3557. }
  3558.  
  3559. openInNewTab(eles) {
  3560. if (openInNewTab) {
  3561. [].forEach.call(eles, ele => {
  3562. if (compareNodeName(ele, ["a"]) && ele.href && !/^(mailto:|javascript:)|#/.test(ele.href)) {
  3563. ele.setAttribute('target', openInNewTab == 1 ? '_blank' : '_self');
  3564. } else {
  3565. [].forEach.call(ele.querySelectorAll('a[href]:not([href^="mailto:"]):not([href^="javascript:"]):not([href^="#"])'), a => {
  3566. if (openInNewTab == 1) {
  3567. a.setAttribute('target', '_blank');
  3568. if (a.getAttribute('onclick') == 'atarget(this)') {
  3569. a.removeAttribute('onclick');
  3570. }
  3571. } else a.setAttribute('target', '_self');
  3572. });
  3573. }
  3574. });
  3575. }
  3576. }
  3577.  
  3578. lazyImgAction(eles, doc) {
  3579. if (!eles || eles.length == 0) return;
  3580. let lazyImgSrc = this.curSiteRule.lazyImgSrc;
  3581. if (lazyImgSrc === 0 || lazyImgSrc === '0') return;
  3582. let imgLazyAttrs = [];
  3583. 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"];
  3584. let removeProps = [];
  3585. let setLazyImg = img => {
  3586. let realSrc;
  3587. imgLazyAttrs.forEach(attr => {
  3588. realSrc = img.getAttribute(lazyImgSrc[0]);
  3589. if (realSrc) {
  3590. removeProps.forEach(prop => {
  3591. img.removeAttribute(prop.trim());
  3592. });
  3593. img.src = realSrc;
  3594. return;
  3595. }
  3596. })
  3597. if (!realSrc) {
  3598. let lazyAttr = "";
  3599. if (img.getAttribute("_src") && !img.src) {
  3600. lazyAttr = "_src";
  3601. realSrc = img.getAttribute(lazyAttr);
  3602. } else {
  3603. for (let i in lazyImgAttr) {
  3604. lazyAttr = lazyImgAttr[i];
  3605. let attrValue = img.getAttribute(lazyAttr);
  3606. if (attrValue) {
  3607. realSrc = attrValue;
  3608. break;
  3609. }
  3610. }
  3611. }
  3612. if (!realSrc && img._lazyrias && img._lazyrias.srcset) {
  3613. realSrc = img._lazyrias.srcset[img._lazyrias.srcset.length - 1];
  3614. lazyAttr = "_lazyrias";
  3615. }
  3616. if (!realSrc && img.srcset) {
  3617. lazyAttr = "srcset";
  3618. var srcs = img.srcset.split(/[xw],/i), largeSize = 0;
  3619. srcs.forEach(srci => {
  3620. let srcInfo = srci.trim().split(" "), curSize = parseInt(srcInfo[1]);
  3621. if (srcInfo[1] && curSize > largeSize) {
  3622. largeSize = curSize;
  3623. realSrc = srcInfo[0];
  3624. }
  3625. });
  3626. }
  3627. if (realSrc) {
  3628. img.src = realSrc;
  3629. img.removeAttribute("srcset");
  3630. img.removeAttribute(lazyAttr);
  3631. if (img.classList && img.classList.contains && img.classList.contains("lazy")) {
  3632. img.classList.remove("lazy");
  3633. }
  3634. if (img.style.display == "none") {
  3635. img.style.display = "";
  3636. }
  3637. if (img.style.visibility == "hidden") {
  3638. img.style.visibility = "";
  3639. }
  3640. if (img.style.opacity == 0) {
  3641. img.style.opacity = "";
  3642. }
  3643. }
  3644. }
  3645. };
  3646. if (lazyImgSrc) {
  3647. if (!Array.isArray(lazyImgSrc)) {
  3648. lazyAttrs = lazyImgSrc.split(",");
  3649. } else {
  3650. lazyAttrs = lazyImgSrc[0].split(",");
  3651. removeProps = lazyImgSrc[1].split(",");
  3652. }
  3653. }
  3654. lazyAttrs.forEach(attr => {
  3655. let attrArr = attr.split("|");
  3656. if (attrArr.length !== 2) {
  3657. imgLazyAttrs.push(attr.trim());
  3658. } else {
  3659. let selector = attrArr[0].trim();
  3660. let lazyAttr = attrArr[1].trim();
  3661. if (selector == "img") {
  3662. imgLazyAttrs.push(lazyAttr);
  3663. } else {
  3664. selector += "[" + lazyAttr + "]";
  3665. [].forEach.call(doc.querySelectorAll(selector), ele => {
  3666. ele.style.setProperty("background-image", "url(" + ele.getAttribute(lazyAttr) + ")", "important");
  3667. removeProps.forEach(prop => {
  3668. ele.removeAttribute(prop.trim());
  3669. });
  3670. });
  3671. }
  3672. }
  3673. });
  3674. [].forEach.call(doc.querySelectorAll("img,picture>source"), img => {
  3675. setLazyImg(img);
  3676. });
  3677. }
  3678.  
  3679. canListenUrlChange() {
  3680. if (this.curSiteRule) {
  3681. if (this.curSiteRule.listenUrlChange === true) return true;
  3682. if (this.curSiteRule.listenUrlChange === false) return false;
  3683. if (this.docElementValid()) {
  3684. return false;
  3685. }
  3686. }
  3687. return true;
  3688. }
  3689.  
  3690. docElementValid() {
  3691. return (this.docPageElement && document.documentElement.contains(this.docPageElement[0]));
  3692. }
  3693.  
  3694. urlChanged() {
  3695. urlChanged = true;
  3696. this.clearAddedElements();
  3697. }
  3698.  
  3699. initPage(callback) {
  3700. let self = this;
  3701. if (self.initing) return;
  3702. self.initing = true;
  3703. setTimeout(() => {
  3704. self.initing = false;
  3705. }, 100);
  3706. curPage = 1;
  3707. urlChanged = false;
  3708. tryTimes = 0;
  3709. this.clearAddedElements();
  3710. this.insert = null;
  3711. this.visibilityItems = [];
  3712. this.visibleIndex = -1;
  3713. this.pageDoc = document;
  3714. this.nextLinkHref = null;
  3715. this.curUrl = location.href;
  3716. this.oldUrl = "";
  3717. this.initUrl = location.href;
  3718. this.historyUrl = "";
  3719. this.possibleCheck = 0;
  3720. let base = document.querySelector("base");
  3721. this.basePath = (base && base.href) || location.href;
  3722. this.getRule(async () => {
  3723. if (self.curSiteRule.sideController === true || (self.curSiteRule.sideController !== false && rulesData.sideController)) {
  3724. isPause = manualPause;
  3725. }
  3726. if (typeof(self.curSiteRule.rate) !== "undefined") {
  3727. rate = self.curSiteRule.rate;
  3728. }
  3729. if (self.curSiteRule.enable == 0) {
  3730. debug("Stop as rule disable");
  3731. isPause = true;
  3732. _GM_registerMenuCommand(i18n("enable"), () => {
  3733. showTips(i18n("enableSiteTips"));
  3734. if(!self.customRules) {
  3735. self.customRules = [];
  3736. }
  3737. for (let i in self.customRules) {
  3738. if (self.customRules[i].url == self.curSiteRule.url) {
  3739. self.customRules.splice(i, 1);
  3740. break;
  3741. }
  3742. }
  3743. self.curSiteRule.enable = 1;
  3744. self.customRules.unshift(self.curSiteRule);
  3745. storage.setItem("customRules", self.customRules);
  3746. location.reload();
  3747. });
  3748. return;
  3749. }
  3750. if (rulesData.sideControllerAlways) {
  3751. sideController.setup();
  3752. }
  3753. //若是再亂匹配就不緩存wedata,或者只在找完本地規則之後再考慮wedata的緩存
  3754. if (self.curSiteRule.smart) {
  3755. delete self.curSiteRule.pageElement;
  3756. if (!self.possibleRule) {
  3757. self.smartRules = self.smartRules.filter(item => {return item && item.url != self.curSiteRule.url});
  3758. self.smartRules.unshift(self.curSiteRule);
  3759. if (self.smartRules.length > 100) {
  3760. self.smartRules.pop();
  3761. }
  3762. storage.setItem("smartRules", self.smartRules);
  3763. }
  3764. } else if (self.curSiteRule && self.curSiteRule.url.length > 13) {
  3765. self.addToHpRules();
  3766. }
  3767. let css = self.curSiteRule.css || rulesData.customCss;
  3768. if (css) {
  3769. let cssArr = css.split("inIframe:");
  3770. if (cssArr && cssArr.length) {
  3771. _GM_addStyle(cssArr[0]);
  3772. }
  3773. }
  3774. if (/sidesearch=(1|true)$/.test(self.curUrl)) {
  3775. openInNewTab = 0;
  3776. } else if (typeof self.curSiteRule.openInNewTab !== 'undefined') {
  3777. openInNewTab = self.curSiteRule.openInNewTab ? 1 : 2;
  3778. }
  3779. let autoClick = self.curSiteRule.autoClick;
  3780. if (autoClick) {
  3781. let autoClickBtn;
  3782. autoClickBtn = getElement(autoClick, document, null, true);
  3783. if (autoClickBtn) {
  3784. emuClick(autoClickBtn);
  3785. }
  3786. }
  3787. let code = self.curSiteRule.init;
  3788. if (code) {
  3789. try {
  3790. 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)});
  3791. } catch(e) {
  3792. debug(e);
  3793. }
  3794. }
  3795. await self.getNextLink(document, true);
  3796. if (self.curSiteRule.pageNum && self.nextLinkHref && self.nextLinkHref != "#") {
  3797. let num1st = self.getPageNumFromUrl(location.href, 1);
  3798. let num2nd = self.getPageNumFromUrl(self.nextLinkHref, 1);
  3799. if (num2nd != num1st + 1) {
  3800. self.curSiteRule.pageNum = null;
  3801. }
  3802. }
  3803. if (self.curSiteRule.smart && self.nextLinkHref == false && self.possibleRule) {
  3804. let urlReg = new RegExp(self.possibleRule.url, "i");
  3805. function checkPossible () {
  3806. if (self.possibleCheck++ < 3) {
  3807. setTimeout(() => {
  3808. if (self.curSiteRule.smart) {
  3809. var href = location.href.slice(0, 500);
  3810. if (urlReg.test(href) && self.ruleMatch(self.possibleRule)) {
  3811. self.initPage(() => {});
  3812. } else checkPossible();
  3813. }
  3814. }, 3000);
  3815. }
  3816. }
  3817. checkPossible();
  3818. }
  3819. self.refreshByClick();
  3820. if (emuIframe && emuIframe.parentNode) {
  3821. emuIframe.parentNode.removeChild(emuIframe);
  3822. emuIframe = null;
  3823. }
  3824.  
  3825. let pageElementCss = self.curSiteRule.pageElementCss || rulesData.pageElementCss;
  3826. if (pageElementCss && pageElementCss !== '0') {
  3827. self.getPageElement(document, _unsafeWindow);
  3828. }
  3829. callback();
  3830. let initRun = typeof self.curSiteRule.initRun == 'undefined' ? rulesData.initRun : self.curSiteRule.initRun;
  3831. if (self.nextLinkHref) {
  3832. sideController.setup();
  3833. if (initRun && initRun != false) {
  3834. setTimeout(() => {
  3835. nextPage();
  3836. }, 300);
  3837. }
  3838. }
  3839. });
  3840. }
  3841.  
  3842. async hookUrlSetEle(ele, doc) {
  3843. let self = this;
  3844. return new Promise((resolve) => {
  3845. let catchUrl = e => {
  3846. ele.dataset.url = self.catchedUrl;
  3847. ele.setAttribute('onclick', 'window.open(this.dataset.url)');
  3848. window.removeEventListener('pagetual_openUrl', catchUrl);
  3849. resolve();
  3850. };
  3851. window.addEventListener('pagetual_openUrl', catchUrl);
  3852. emuClick(ele, doc);
  3853. });
  3854. }
  3855.  
  3856. async hookUrl(doc) {
  3857. let sel = this.curSiteRule.hookUrl;
  3858. if (!sel) return;
  3859. let self = this;
  3860. if (!this.initHook) {
  3861. this.initHook = true;
  3862. Object.defineProperty(doc.defaultView, 'open', {
  3863. get: function () {
  3864. return (s) => {
  3865. self.catchedUrl = s;
  3866. var e = new CustomEvent('pagetual_openUrl');
  3867. window.dispatchEvent(e);
  3868. }
  3869. }
  3870. });
  3871. }
  3872. let eles = getAllElements(sel, doc);
  3873. for (let i = 0; i < eles.length; i++) {
  3874. await sleep(1);
  3875. let ele = eles[i];
  3876. if (!ele.dataset.url) {
  3877. await this.hookUrlSetEle(ele, doc);
  3878. }
  3879. }
  3880. }
  3881.  
  3882. beginLoading() {
  3883. isLoading = true;
  3884. if (targetY >= 0) {
  3885. window.scrollTo({ top: targetY, behavior: 'instant'});
  3886. targetY = -1;
  3887. }
  3888. let lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3889. ruleParser.insertElement(loadingDiv);
  3890. if (forceState == 2) {
  3891. getBody(document).appendChild(loadingDiv);
  3892. } else {
  3893. let parent = loadingDiv.parentNode;
  3894. if (compareNodeName(parent, ["tbody"])) {
  3895. parent = parent.parentNode;
  3896. }
  3897. if (compareNodeName(parent, ["table"])) {
  3898. parent.parentNode.appendChild(loadingDiv);
  3899. }
  3900. }
  3901. getBody(document).scrollTop = lastScrollTop;
  3902. document.documentElement.scrollTop = lastScrollTop;
  3903. }
  3904.  
  3905. insertElement(ele) {
  3906. if (!this.insert || !this.insert.parentNode) {
  3907. this.getInsert();
  3908. }
  3909. if (this.insert && this.insert.parentNode) {
  3910. let self = this;
  3911. if (ele.nodeName == "#document-fragment") {
  3912. [].forEach.call(ele.children, el => {
  3913. self.addedElePool.push(el);
  3914. });
  3915. } else {
  3916. this.addedElePool.push(ele);
  3917. }
  3918. if (this.curSiteRule.insertPos == 2 || this.curSiteRule.insertPos == "in") {
  3919. this.insert.appendChild(ele);
  3920. } else {
  3921. this.insert.parentNode.insertBefore(ele, this.insert);
  3922. }
  3923. }
  3924. }
  3925.  
  3926. noValidContent(url) {
  3927. if (!this.curSiteRule.nextLinkByUrl) showTips(i18n("noValidContent"), url);
  3928. }
  3929.  
  3930. async insertPage(doc, eles, url, callback, tried) {
  3931. this.oldUrl = this.curUrl;
  3932. let oldTitle = document.title;
  3933. try {
  3934. let oldTitle = this.pageDoc.title;
  3935. } catch (e) {}
  3936. this.pageDoc = doc;
  3937. this.curUrl = url;
  3938. isLoading = true;
  3939. let nextLink = await this.getNextLink(doc);
  3940. this.nextTitle = "";
  3941. if (this.curSiteRule.pageBarText) {
  3942. if (this.curSiteRule.pageBarText == 1 || this.curSiteRule.pageBarText == true) {
  3943. this.nextTitle = doc.title;
  3944. } else {
  3945. try {
  3946. this.nextTitle = ((typeof this.curSiteRule.pageBarText == 'function') ? this.curSiteRule.pageBarText : Function("doc",'"use strict";' + this.curSiteRule.pageBarText))(doc);
  3947. } catch(e) {
  3948. debug(e);
  3949. }
  3950. }
  3951. }
  3952. if (curPage == 1 && !tried && !nextLink && this.curSiteRule.smart && this.curSiteRule.pageElement && this.curSiteRule.action != 0) {
  3953. this.curSiteRule.action = 1;
  3954. this.curUrl = location.href;
  3955. isLoading = false;
  3956. return false;
  3957. }
  3958.  
  3959. if (targetY >= 0) {
  3960. window.scrollTo({ top: targetY, behavior: 'instant'});
  3961. targetY = -1;
  3962. }
  3963. let lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3964. this.getInsert();
  3965. await this.pageInit(doc, eles);
  3966. var self = this, newEles = [];
  3967. if (!eles || eles.length == 0 || !self.insert || !self.insert.parentNode) {
  3968. if (callback) callback(eles);
  3969. loadPageOver();
  3970. } else {
  3971. if (callback) callback(eles);
  3972. loadPageOver();
  3973. const collection = document.createDocumentFragment();
  3974. [].forEach.call(eles, ele => {
  3975. let newEle = ele.cloneNode(true);
  3976. let oldCanvass = ele.querySelectorAll("canvas");
  3977. let newCanvass = newEle.querySelectorAll("canvas");
  3978. if (self.updateUrl) {
  3979. [].forEach.call(newEle.querySelectorAll("img"), img => {
  3980. if (img.getAttribute("src")) img.src = self.canonicalUri(img.getAttribute("src"));
  3981. });
  3982. [].forEach.call(newEle.querySelectorAll("a"), a => {
  3983. if (a.getAttribute("href")) a.href = self.canonicalUri(a.getAttribute("href"));
  3984. });
  3985. }
  3986. for (let i = 0; i < oldCanvass.length; i++) {
  3987. let oldCanvas = oldCanvass[i];
  3988. let newCanvas = newCanvass[i];
  3989. newCanvas.getContext('2d').drawImage(oldCanvas, 0, 0);
  3990. }
  3991. if (!compareNodeName(newEle, ["style", "script"])) self.visibilityItems.push(newEle);
  3992. collection.appendChild(newEle)
  3993. newEles.push(newEle);
  3994. });
  3995. self.insertElement(collection);
  3996. }
  3997. getBody(document).scrollTop = lastScrollTop;
  3998. document.documentElement.scrollTop = lastScrollTop;
  3999. this.pageAction(doc, newEles);
  4000. let enableHistory = this.curSiteRule.history;
  4001. let enableHistoryAfterInsert = false;
  4002. if (enableHistory == 1) {
  4003. enableHistory = true;
  4004. } else if (enableHistory == 2) {
  4005. enableHistory = true;
  4006. enableHistoryAfterInsert = true;
  4007. } else if (enableHistory == 0) {
  4008. enableHistory = false;
  4009. } else {
  4010. enableHistory = rulesData.enableHistory;
  4011. enableHistoryAfterInsert = rulesData.enableHistoryAfterInsert;
  4012. }
  4013. if (enableHistory) {
  4014. this.historyUrl = enableHistoryAfterInsert ? this.curUrl : this.oldUrl;
  4015. if(this.historyUrl != location.href) {
  4016. let isJs = this.hrefIsJs(this.historyUrl);
  4017. if (!isJs) {
  4018. let historyTitle = enableHistoryAfterInsert ? doc.title : oldTitle;
  4019. _unsafeWindow.history.replaceState(undefined, historyTitle, this.historyUrl);
  4020. document.title = historyTitle;
  4021. }
  4022. }
  4023. }
  4024. isLoading = false;
  4025. _unsafeWindow.postMessage({
  4026. action: "insert",
  4027. command: 'pagetual'
  4028. }, '*');
  4029. return true;
  4030. }
  4031. }
  4032. var ruleParser = new RuleParser();
  4033.  
  4034. class SideController {
  4035. //static controller;
  4036. constructor() {
  4037. this.inited = false;
  4038. }
  4039.  
  4040. /*static getInstance() {
  4041. if (!SideController.controller) {
  4042. SideController.controller = new SideController();
  4043. }
  4044. return SideController.controller;
  4045. }*/
  4046.  
  4047. setup() {
  4048. if (ruleParser.curSiteRule.sideController === false) return;
  4049. if (!rulesData.sideController && !ruleParser.curSiteRule.sideController) return;
  4050. this.addToStage();
  4051. }
  4052.  
  4053. init() {
  4054. if (this.inited) return;
  4055. this.inited = true;
  4056. let self = this;
  4057. this.cssText = `
  4058. #pagetual-sideController {
  4059. position: fixed;
  4060. top: calc(50% - 83px);
  4061. left: calc(99% - 40px);
  4062. width: 40px;
  4063. border-radius: 20px;
  4064. box-shadow: rgb(0 0 0) 0px 0px 10px;
  4065. text-align: center;
  4066. background: #ffffffd0!important;
  4067. user-select: none;
  4068. z-index: 2147483646!important;
  4069. padding: 0!important;
  4070. opacity: 0.35;
  4071. transition: opacity .5s ease, background .5s, box-shadow .5s;
  4072. }
  4073. #pagetual-sideController * {
  4074. font-weight: bold;
  4075. font-family: arial;
  4076. font-style: normal;
  4077. font-size: 20px!important;
  4078. color: black!important;
  4079. line-height: normal;
  4080. float: none;
  4081. text-align: center;
  4082. }
  4083. #pagetual-sideController.stop {
  4084. -webkit-filter: invert(100%);
  4085. filter: invert(100%);
  4086. }
  4087. .pagetual-sideController-btn {
  4088. padding: 5px 0;
  4089. cursor: pointer;
  4090. transition: transform .15s ease-in-out, opacity .3s ease;
  4091. }
  4092. #pagetual-sideController .pagetual-sideController-btn:hover {
  4093. transform: scale(1.5);
  4094. color: red!important;
  4095. }
  4096. #pagetual-sideController #pagetual-sideController-move > svg {
  4097. transition: transform .3s ease;
  4098. }
  4099. #pagetual-sideController #pagetual-sideController-move > svg:hover {
  4100. transform: scale(1.2);
  4101. }
  4102. #pagetual-sideController.minSize #pagetual-sideController-move > svg {
  4103. background: white;
  4104. opacity: 0;
  4105. }
  4106. #pagetual-sideController #pagetual-sideController-move > img,
  4107. #pagetual-sideController #pagetual-sideController-move > span {
  4108. width: 35px;
  4109. height: 35px;
  4110. cursor: pointer;
  4111. }
  4112. #pagetual-sideController.minSize #pagetual-sideController-move > img,
  4113. #pagetual-sideController.minSize #pagetual-sideController-move > span {
  4114. border-radius: 50px;
  4115. text-shadow: rgb(255 255 255) 0px 0px 10px;
  4116. }
  4117. #pagetual-sideController #pagetual-sideController-pagenum {
  4118. font-size: 15px!important;
  4119. line-height: 30px;
  4120. text-align: center;
  4121. position: absolute;
  4122. right: calc(50% - 15px);
  4123. top: calc(50% - 15px);
  4124. border: 1px solid #00000099;
  4125. display: inline-block;
  4126. width: 30px;
  4127. height: 30px;
  4128. box-sizing: border-box;
  4129. border-radius: 50%;
  4130. background: white;
  4131. opacity: 0;
  4132. transition: opacity .5s ease;
  4133. pointer-events: none;
  4134. }
  4135. #pagetual-sideController.minSize #pagetual-sideController-pagenum {
  4136. opacity: 0.8;
  4137. }
  4138. #pagetual-sideController:hover {
  4139. opacity: 1;
  4140. }
  4141. #pagetual-sideController>.extra {
  4142. bottom: 170px;
  4143. left: 0px;
  4144. width: 40px;
  4145. position: absolute;
  4146. }
  4147. #pagetual-sideController>.extra>svg {
  4148. width: 40px;
  4149. height: 30px;
  4150. opacity: 0.1;
  4151. cursor: pointer;
  4152. margin: 0 0 5px 0;
  4153. transition: opacity .3s ease;
  4154. }
  4155. #pagetual-sideController.minSize>.extra>svg {
  4156. opacity: 0;
  4157. }
  4158. #pagetual-sideController>.extra>svg:hover {
  4159. opacity: 1;
  4160. }
  4161. #pagetual-sideController.minSize {
  4162. box-shadow: rgb(0 0 0 / 0%) 0px 0px 0px;
  4163. background: #00000000!important;
  4164. pointer-events: none;
  4165. }
  4166. #pagetual-sideController.minSize #pagetual-sideController-move {
  4167. pointer-events: all;
  4168. }
  4169. #pagetual-sideController.minSize .pagetual-sideController-btn {
  4170. opacity: 0;
  4171. }
  4172. `;
  4173. let frame = document.createElement("div");
  4174. frame.id = "pagetual-sideController";
  4175. frame.innerHTML = createHTML(`
  4176. <div class="extra">
  4177. <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>
  4178. <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>
  4179. </div>
  4180. <div id="pagetual-sideController-top" class="pagetual-sideController-btn">⊼</div>
  4181. <div>
  4182. <div id="pagetual-sideController-pre" class="pagetual-sideController-btn">∧</div>
  4183. <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>
  4184. <div id="pagetual-sideController-next" class="pagetual-sideController-btn">∨</div>
  4185. </div>
  4186. <div id="pagetual-sideController-bottom" class="pagetual-sideController-btn">⊻</div>
  4187. `);
  4188. frame.classList.add("stop");
  4189. let top = frame.querySelector("#pagetual-sideController-top");
  4190. let pre = frame.querySelector("#pagetual-sideController-pre");
  4191. let move = frame.querySelector("#pagetual-sideController-move");
  4192. let next = frame.querySelector("#pagetual-sideController-next");
  4193. let bottom = frame.querySelector("#pagetual-sideController-bottom");
  4194. let pagenum = frame.querySelector("#pagetual-sideController-pagenum");
  4195. let scroll = frame.querySelector("#scroll");
  4196. let loadNow = frame.querySelector("#loadNow");
  4197. if (rulesData.sideControllerScroll === false) {
  4198. scroll.style.display = "none";
  4199. }
  4200. if (rulesData.sideControllerLoadNow === false) {
  4201. loadNow.style.display = "none";
  4202. }
  4203. if (sideControllerIcon) move.innerHTML = sideControllerIcon;
  4204.  
  4205. frame.addEventListener("dblclick", e => {
  4206. e.preventDefault();
  4207. e.stopPropagation();
  4208. });
  4209.  
  4210. frame.addEventListener("mouseenter", e => {
  4211. clearTimeout(self.hideTimer);
  4212. frame.classList.remove("minSize");
  4213. });
  4214.  
  4215. frame.addEventListener("mouseleave", e => {
  4216. clearTimeout(self.hideTimer);
  4217. self.hideTimer = setTimeout(() => {
  4218. frame.classList.add("minSize");
  4219. }, 800);
  4220. });
  4221.  
  4222. document.body.addEventListener('touchstart', e => {
  4223. if (e.target === frame || frame.contains(e.target)) {
  4224. frame.classList.remove("minSize");
  4225. } else {
  4226. frame.classList.add("minSize");
  4227. }
  4228. });
  4229.  
  4230. scroll.addEventListener("click", e => {
  4231. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  4232. autoScroll = parseInt(autoScroll) || 0;
  4233. if (autoScroll < 0) autoScroll = 0;
  4234. if (autoScroll && autoScroll != autoScrollRate) {
  4235. autoScrollRate = autoScroll;
  4236. storage.setItem("autoScrollRate", autoScrollRate);
  4237. }
  4238. setListData("autoScroll", location.host + location.pathname, autoScroll);
  4239. startAutoScroll();
  4240. }, true);
  4241.  
  4242. loadNow.addEventListener("click", e => {
  4243. if (autoLoadNum != -1) {
  4244. autoLoadNum = -1;
  4245. return;
  4246. }
  4247. let loadNum = window.prompt(i18n("loadConfirm"), loadNowNum);
  4248. if (loadNum === "" || loadNum === null) return;
  4249. loadNum = Math.abs(parseInt(loadNum)) || 0;
  4250. if (loadNowNum != loadNum) {
  4251. loadNowNum = loadNum;
  4252. storage.setItem("loadNowNum", loadNowNum);
  4253. }
  4254. autoLoadNum = loadNum;
  4255. nextPage();
  4256. }, true);
  4257.  
  4258. pre.addEventListener("click", e => {
  4259. let prePageBar = getPageBar().preBar;
  4260. if (prePageBar) {
  4261. scrollToPageBar(prePageBar);
  4262. } else {
  4263. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  4264. targetY = scrollTop - (window.innerHeight || document.documentElement.clientHeight);
  4265. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4266. }
  4267. }, true);
  4268.  
  4269. next.addEventListener("click", e => {
  4270. let pageBarObj = getPageBar();
  4271. let nextPageBar = pageBarObj.nextBar;
  4272. if (nextPageBar) {
  4273. scrollToPageBar(nextPageBar);
  4274. } else {
  4275. if (pageBarObj.preBar) {
  4276. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  4277. targetY = scrollH || 9999999;
  4278. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4279. } else {
  4280. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  4281. targetY = scrollTop + (window.innerHeight || document.documentElement.clientHeight);
  4282. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4283. }
  4284. }
  4285. }, true);
  4286.  
  4287. top.addEventListener("click", e => {
  4288. getBody(document).scrollTop=0;
  4289. document.documentElement.scrollTop=0;
  4290. e.preventDefault();
  4291. e.stopPropagation();
  4292. }, true);
  4293.  
  4294. bottom.addEventListener("click", e => {
  4295. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  4296. changeStop(true, true);
  4297. }
  4298. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  4299. getBody(document).scrollTop = scrollH || 9999999;
  4300. document.documentElement.scrollTop = scrollH || 9999999;
  4301. e.preventDefault();
  4302. e.stopPropagation();
  4303. }, true);
  4304.  
  4305. let initX, initY, moving = false;
  4306. let removeTimer;
  4307. move.addEventListener("click", e => {
  4308. if (!moving) {
  4309. changeStop(!isPause, true);
  4310. }
  4311. }, true);
  4312. move.addEventListener("dblclick", e => {
  4313. clearTimeout(removeTimer);
  4314. document.removeEventListener("mousemove", mouseMoveHandler, true);
  4315. document.removeEventListener("mouseup", mouseUpHandler, true);
  4316. changeStop(!isPause, true);
  4317. if (isPause) {
  4318. ruleParser.hideAddedElements();
  4319. } else {
  4320. ruleParser.showAddedElements();
  4321. }
  4322. }, true);
  4323.  
  4324. move.oncontextmenu = e => {
  4325. e.preventDefault();
  4326. picker.start();
  4327. };
  4328.  
  4329. let clientX = e => {
  4330. if (e.type.indexOf('mouse') === 0) {
  4331. return e.clientX;
  4332. } else {
  4333. return e.changedTouches[0].clientX;
  4334. }
  4335. };
  4336.  
  4337. let clientY = e => {
  4338. if (e.type.indexOf('mouse') === 0) {
  4339. return e.clientY;
  4340. } else {
  4341. return e.changedTouches[0].clientY;
  4342. }
  4343. };
  4344.  
  4345. let mouseMoveHandler = e => {
  4346. if (moving) {
  4347. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  4348. let windowWidth = window.innerWidth || document.documentElement.clientWidth;
  4349. initX = (clientX(e) - 10 + 40) / windowWidth * 100;
  4350. initY = (clientY(e) - 83 + 83) / windowHeight * 100;
  4351. this.frame.style.top = `calc(${initY}% - 83px)`;
  4352. this.frame.style.left = `calc(${initX}% - 40px)`;
  4353. } else if (Math.abs(clientX(e) - initX) + Math.abs(clientY(e) - initY) > 20) {
  4354. moving = true;
  4355. clearTimeout(removeTimer);
  4356. }
  4357. };
  4358. let mouseUpHandler = e => {
  4359. clearTimeout(removeTimer);
  4360. document.removeEventListener("mousemove", mouseMoveHandler, true);
  4361. document.removeEventListener("mouseup", mouseUpHandler, true);
  4362. document.removeEventListener("touchmove", mouseMoveHandler, true);
  4363. document.removeEventListener("touchend", mouseUpHandler, true);
  4364. if (moving) {
  4365. rulesData.sideControllerPos = {x: parseInt(initX), y: parseInt(initY)};
  4366. storage.setItem("rulesData", rulesData);
  4367. }
  4368. };
  4369. let mouseDownHandler = e => {
  4370. initX = clientX(e);
  4371. initY = clientY(e);
  4372. moving = false;
  4373. clearTimeout(removeTimer);
  4374. removeTimer = setTimeout(() => {
  4375. if (e.type === "touchstart") {
  4376. picker.start();
  4377. } else {
  4378. self.remove();
  4379. }
  4380. }, 1500);
  4381. document.addEventListener("mousemove", mouseMoveHandler, true);
  4382. document.addEventListener("mouseup", mouseUpHandler, true);
  4383. document.addEventListener("touchmove", mouseMoveHandler, true);
  4384. document.addEventListener("touchend", mouseUpHandler, true);
  4385. e.stopPropagation();
  4386. e.preventDefault();
  4387. };
  4388.  
  4389. move.addEventListener("mousedown", mouseDownHandler, true);
  4390. move.addEventListener("touchstart", mouseDownHandler, { passive: false, capture: true });
  4391.  
  4392. this.frame = frame;
  4393. this.pagenum = pagenum;
  4394. if (rulesData.sideControllerPos) {
  4395. this.frame.style.top = `calc(${rulesData.sideControllerPos.y}% - 83px)`;
  4396. this.frame.style.left = `calc(${rulesData.sideControllerPos.x}% - 40px)`;
  4397. }
  4398. }
  4399.  
  4400. addToStage() {
  4401. this.init();
  4402. if (!this.styleEle || !this.styleEle.parentNode) {
  4403. this.styleEle = _GM_addStyle(this.cssText);
  4404. }
  4405. if (!isPause) {
  4406. this.frame.classList.remove("stop");
  4407. }
  4408. this.pagenum.innerHTML = createHTML(curPage);
  4409. this.frame.title = i18n("page") + curPage;
  4410. if (this.frame.parentNode) return;
  4411. getBody(document).appendChild(this.frame);
  4412. clearTimeout(this.hideTimer);
  4413. this.frame.classList.add("minSize");
  4414. }
  4415.  
  4416. remove() {
  4417. if (this.frame && this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  4418. }
  4419. }
  4420. const sideController = new SideController();
  4421.  
  4422. class NextSwitch {
  4423. //static nextSwitch;
  4424. constructor() {
  4425. this.inited = false;
  4426. }
  4427.  
  4428. /*static getInstance() {
  4429. if (!NextSwitch.nextSwitch) {
  4430. NextSwitch.nextSwitch = new NextSwitch();
  4431. }
  4432. return NextSwitch.nextSwitch;
  4433. }*/
  4434.  
  4435. init() {
  4436. if (this.inited) return;
  4437. this.inited = true;
  4438. let self = this;
  4439. this.cssText = `
  4440. #pagetual-nextSwitch {
  4441. position: fixed;
  4442. top: 10px;
  4443. left: calc(50% - 160px);
  4444. background: aliceblue;
  4445. padding: 10px;
  4446. border-radius: 5px;
  4447. text-align: center;
  4448. opacity: 0.95;
  4449. color: #161616;
  4450. z-index: 2147483647;
  4451. font-size: 16px;
  4452. box-shadow: rgb(0 0 0) 0px 0px 10px;
  4453. }
  4454. #pagetual-nextSwitch>.title {
  4455. margin: -5px 45px 10px 45px;
  4456. font-size: 20px;
  4457. font-weight: bold;
  4458. border-bottom: 1px solid black;
  4459. user-select: none;
  4460. color: orangered;
  4461. }
  4462. #pagetual-nextSwitch>.group {
  4463. display: flex;
  4464. flex-direction: column;
  4465. }
  4466. #pagetual-nextSwitch>.group>span {
  4467. color: #161616;
  4468. cursor: pointer;
  4469. margin: 3px;
  4470. font-size: larger;
  4471. }
  4472. #pagetual-nextSwitch>.group>span:hover {
  4473. color: red;
  4474. }
  4475. #pagetual-nextSwitch>.group>span.current {
  4476. border: 2px dotted red;
  4477. border-radius: 10px;
  4478. }
  4479. #pagetual-nextSwitch>.closeSwitch {
  4480. position: absolute;
  4481. top: 3px;
  4482. right: 10px;
  4483. background: none;
  4484. border: none;
  4485. vertical-align: top;
  4486. transition: transform .15s ease-in-out;
  4487. float: right;
  4488. cursor: pointer;
  4489. }
  4490. #pagetual-nextSwitch svg {
  4491. width: 30px;
  4492. height: 30px;
  4493. vertical-align: middle;
  4494. fill: #161616;
  4495. overflow: hidden;
  4496. }
  4497. #pagetual-nextSwitch button:hover {
  4498. transform: scale(1.2);
  4499. }
  4500. `;
  4501. let frame = document.createElement("div");
  4502. frame.id = "pagetual-nextSwitch";
  4503. frame.innerHTML = createHTML(`
  4504. <div class="title">${i18n("nextSwitch")}</div>
  4505. <button type="button" class="closeSwitch">
  4506. <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2754">
  4507. <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">
  4508. </path>
  4509. </svg>
  4510. </button>
  4511. <div class="group"></div>
  4512. `);
  4513. let group = frame.querySelector(".group");
  4514. let closeBtn = frame.querySelector(".closeSwitch");
  4515. closeBtn.addEventListener("click", e => {
  4516. self.close();
  4517. }, true);
  4518. this.frame = frame;
  4519. let currentSpan;
  4520. ruleParser.curSiteRule.nextLink.forEach((link, i) => {
  4521. let span = document.createElement("span");
  4522. let target = getElement(link, document);
  4523. let index = "<b>" + (i + 1) + "</b>: ";
  4524. if (target) {
  4525. let targetInner = target.innerText.trim();
  4526. span.innerHTML = index + (targetInner || link);
  4527. } else {
  4528. span.innerHTML = index + "Not Found";
  4529. }
  4530. span.title = link;
  4531. span.addEventListener("click", e => {
  4532. if (currentSpan) currentSpan.classList.remove("current");
  4533. span.classList.add("current");
  4534. currentSpan = span;
  4535. nextIndex = i;
  4536. setListData("nextSwitch", location.host, nextIndex === 0 ? "" : nextIndex);
  4537. ruleParser.curUrl += "#pagetual";
  4538. ruleParser.oldUrl = ruleParser.curUrl;
  4539. autoLoadNum = -1;
  4540. if (!ruleParser.nextLinkHref) {
  4541. isLoading = false;
  4542. }
  4543. ruleParser.getNextLink(ruleParser.pageDoc || document);
  4544. self.close();
  4545. }, true);
  4546. if (i == nextIndex) {
  4547. span.classList.add("current");
  4548. currentSpan = span;
  4549. }
  4550. group.appendChild(span);
  4551. });
  4552. }
  4553.  
  4554. start() {
  4555. this.init();
  4556. if (!this.styleEle || !this.styleEle.parentNode) {
  4557. this.styleEle = _GM_addStyle(this.cssText);
  4558. }
  4559. document.documentElement.appendChild(this.frame);
  4560. }
  4561.  
  4562. close() {
  4563. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  4564. }
  4565. }
  4566. const nextSwitch = new NextSwitch();
  4567.  
  4568. class Picker {
  4569. //static picker;
  4570. constructor() {
  4571. this.inited = false;
  4572. }
  4573.  
  4574. /*static getInstance() {
  4575. if (!Picker.picker) {
  4576. Picker.picker = new Picker();
  4577. }
  4578. return Picker.picker;
  4579. }*/
  4580.  
  4581. init() {
  4582. if (this.inited) return;
  4583. this.inited = true;
  4584. let self = this;
  4585. this.signList = [];
  4586. this.cssText = `
  4587. body.pagetual-picker,
  4588. body.pagetual-picker *:hover,
  4589. body.pagetual-picker a:hover {
  4590. cursor: crosshair !important;
  4591. }
  4592. #pagetual-picker {
  4593. position: fixed;
  4594. top: 10px;
  4595. left: calc(50% - 178px);
  4596. background: aliceblue;
  4597. padding: 10px;
  4598. border-radius: 5px;
  4599. text-align: center;
  4600. opacity: 0.95;
  4601. color: #161616;
  4602. z-index: 2147483646;
  4603. font-size: 16px;
  4604. overflow: hidden;
  4605. box-shadow: rgb(0 0 0) 0px 0px 10px;
  4606. }
  4607. #pagetual-picker * {
  4608. margin: 0;
  4609. padding: 0;
  4610. font-family: Times New Roman;
  4611. overflow: initial;
  4612. user-select: none;
  4613. line-height: unset;
  4614. min-width: unset;
  4615. min-height: unset;
  4616. }
  4617. #pagetual-picker>.title {
  4618. margin: -5px 45px 10px 45px;
  4619. font-size: 20px;
  4620. font-weight: bold;
  4621. cursor: pointer;
  4622. border-bottom: 1px solid black;
  4623. user-select: none;
  4624. color: orangered;
  4625. height: initial;
  4626. width: initial;
  4627. position: initial;
  4628. transition: transform .3s ease;
  4629. }
  4630. #pagetual-picker>.title:hover {
  4631. transform: scale(1.1);
  4632. }
  4633. #pagetual-picker button {
  4634. background: none;
  4635. border: none;
  4636. vertical-align: top;
  4637. transition: transform .15s ease-in-out;
  4638. float: right;
  4639. cursor: pointer;
  4640. overflow: hidden;
  4641. background-color: unset!important;
  4642. }
  4643. #pagetual-picker button:hover {
  4644. transform: scale(1.2);
  4645. }
  4646. #pagetual-picker>.closePicker {
  4647. position: absolute;
  4648. top: 3px;
  4649. right: 10px;
  4650. }
  4651. #pagetual-picker>.logoIcon {
  4652. position: absolute;
  4653. top: 3px;
  4654. left: 10px;
  4655. }
  4656. #pagetual-picker>.logoIcon.showSign>svg>path {
  4657. fill: gray!important;
  4658. }
  4659. #pagetual-picker textarea{
  4660. display: inline-block;
  4661. width: calc(100% - 65px);
  4662. height: 20px;
  4663. min-width: 250px;
  4664. max-width: calc(65vw - 50px);
  4665. min-height: unset;
  4666. max-height: unset;
  4667. padding: 6px 12px;
  4668. font-size: 16px;
  4669. font-weight: 400;
  4670. line-height: 1.5;
  4671. color: #495057;
  4672. background-color: #fff;
  4673. background-clip: padding-box;
  4674. border: 1px solid #ced4da;
  4675. border-radius: 4px;
  4676. transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
  4677. box-sizing: content-box;
  4678. margin-right: 5px;
  4679. resize: both;
  4680. box-shadow: 0 1px 5px 1px #ddd;
  4681. overflow-wrap: anywhere;
  4682. }
  4683. #pagetual-picker textarea:focus {
  4684. color: black;
  4685. background-color: #fff;
  4686. border-color: #80bdff;
  4687. outline: 0;
  4688. box-shadow: 0 0 0 3.2px rgb(0 123 255 / 25%);
  4689. }
  4690. #pagetual-picker [type=checkbox],
  4691. #pagetual-picker [type=radio] {
  4692. line-height: 20px;
  4693. height: 25px;
  4694. width: 25px;
  4695. margin-left: 5px;
  4696. vertical-align: middle;
  4697. appearance: auto;
  4698. display: inline-block;
  4699. position: initial;
  4700. }
  4701. #pagetual-picker [type=checkbox]:after,
  4702. #pagetual-picker [type=radio]:after,
  4703. #pagetual-picker [type=checkbox]:before,
  4704. #pagetual-picker [type=radio]:before {
  4705. border: none;
  4706. background: none;
  4707. }
  4708. #pagetual-picker label {
  4709. font-size: 18px;
  4710. line-height: 25px;
  4711. vertical-align: middle;
  4712. display: inline-block;
  4713. color: black;
  4714. position: initial;
  4715. cursor: pointer;
  4716. }
  4717. #pagetual-picker .bottom {
  4718. text-align: left;
  4719. margin: 10px 0;
  4720. width: 100%;
  4721. }
  4722. #pagetual-picker .bottom>button {
  4723. float: right;
  4724. }
  4725. #pagetual-picker svg {
  4726. width: 30px;
  4727. height: 30px;
  4728. vertical-align: middle;
  4729. fill: #161616;
  4730. overflow: hidden;
  4731. }
  4732. #pagetual-picker svg * {
  4733. pointer-events: none;
  4734. }
  4735. #pagetual-picker .allpath {
  4736. font-size: 18px;
  4737. margin: 10px auto;
  4738. max-width: 330px;
  4739. word-break: break-all;
  4740. cursor: context-menu;
  4741. overflow: hidden;
  4742. max-height: 42px;
  4743. -moz-transition:max-height 1s ease-in;
  4744. -webkit-transition:max-height 1s ease-in;
  4745. transition:max-height 1s ease-in;
  4746. color: black;
  4747. }
  4748. #pagetual-picker .allpath:hover {
  4749. max-height: calc(100vh - 130px);
  4750. overflow: auto;
  4751. }
  4752. #pagetual-picker .allpath>span.path {
  4753. cursor: pointer;
  4754. }
  4755. #pagetual-picker .allpath>span.path:hover {
  4756. opacity: 0.6;
  4757. }
  4758. #pagetual-picker .allpath>span.path:hover,
  4759. #pagetual-picker .allpath>span.path.checked {
  4760. color: orangered;
  4761. }
  4762. #pagetual-picker .moreConfig {
  4763. display: flex;
  4764. justify-content: space-between;
  4765. border-top: 1px solid;
  4766. padding-top: 10px;
  4767. width: 100%;
  4768. }
  4769. #pagetual-picker .command {
  4770. width: 100%;
  4771. color: black!important;
  4772. text-align: center;
  4773. font-size: large;
  4774. margin-top: 10px;
  4775. box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.12);
  4776. border-radius: 5px;
  4777. }
  4778. #pagetual-picker .command:hover {
  4779. color: orangered;
  4780. }
  4781. #pagetual-picker #showDetail {
  4782. float: initial;
  4783. margin-top: 10px;
  4784. }
  4785. #pagetual-picker.showDetail #showDetail {
  4786. float: right;
  4787. }
  4788. #pagetual-picker #showDetail>svg {
  4789. -moz-transition:transform 0.3s ease;
  4790. -webkit-transition:transform 0.3s ease;
  4791. transition:transform 0.3 ease;
  4792. }
  4793. #pagetual-picker.showDetail #showDetail>svg {
  4794. transform: rotate(180deg);
  4795. }
  4796. #pagetual-picker .tempRule {
  4797. display: none;
  4798. margin-top: 10px;
  4799. height: 300px;
  4800. min-height: 150px;
  4801. }
  4802. #pagetual-picker.showDetail .tempRule {
  4803. display: inline-block;
  4804. word-break: break-all;
  4805. }
  4806. #pagetual-picker #saveDetail {
  4807. display: none;
  4808. position: absolute;
  4809. bottom: 10px;
  4810. right: 8px;
  4811. }
  4812. #pagetual-picker.showDetail #saveDetail {
  4813. display: inline-block;
  4814. }
  4815. #pagetual-picker #saveDetail svg {
  4816. width: 35px;
  4817. height: 35px;
  4818. }
  4819. #pagetual-picker .addProp {
  4820. display: none;
  4821. flex-direction: column;
  4822. position: absolute;
  4823. bottom: 45px;
  4824. right: 12px;
  4825. }
  4826. #pagetual-picker.showDetail .addProp {
  4827. display: flex;
  4828. }
  4829. #pagetual-picker .addProp>button {
  4830. font-size: 30px;
  4831. font-family: Arial,sans-serif;
  4832. line-height: 35px;
  4833. color: #161616;
  4834. }
  4835. #pagetual-picker #edit{
  4836. -webkit-animation: jumpAnimation .6s 5;
  4837. animation: jumpAnimation .6s 5;
  4838. }
  4839. @keyframes jumpAnimation {
  4840. 0% {
  4841. transform: scale(1) translateY(0);
  4842. animation-timing-function: ease-out;
  4843. }
  4844. 50% {
  4845. transform: scale(1.2) translateY(-5px);
  4846. animation-timing-function: ease-in;
  4847. }
  4848. 100% {
  4849. transform: scale(1) translateY(0);
  4850. animation-timing-function: ease-out;
  4851. }
  4852. }
  4853. @-webkit-keyframes jumpAnimation {
  4854. 0% {
  4855. -webkit-transform: scale(1) translateY(0);
  4856. animation-timing-function: ease-out;
  4857. }
  4858. 50% {
  4859. -webkit-transform: scale(1.2) translateY(-5px);
  4860. animation-timing-function: ease-in;
  4861. }
  4862. 100% {
  4863. -webkit-transform: scale(1) translateY(0);
  4864. animation-timing-function: ease-out;
  4865. }
  4866. }
  4867. `;
  4868. this.mainSignDiv = this.createSignDiv();
  4869. this.allSignDiv = [];
  4870. let frame = document.createElement("div");
  4871. frame.id = "pagetual-picker";
  4872. frame.innerHTML = createHTML(`
  4873. <button title="Pagetual" type="button" class="logoIcon">
  4874. <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>
  4875. </button>
  4876. <div class="title" title="${i18n("configure")}">${i18n("picker")}</div>
  4877. <button title="${i18n("closePicker")}" type="button" class="closePicker">
  4878. <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>
  4879. </button>
  4880. <div class="allpath" title="${i18n("switchSelector")}"></div>
  4881. <div>
  4882. <textarea class="selector" spellcheck="false" name="selector" placeholder="${i18n("pickerPlaceholder")}"></textarea>
  4883. <button id="check" title="${i18n("pickerCheck")}" type="button">
  4884. <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>
  4885. </button>
  4886. </div>
  4887. <div class="bottom">
  4888. <input name="xpath" id="checkbox_id" type="checkbox" />
  4889. <label for="checkbox_id">XPath</label>
  4890. <button id="edit" title="${i18n("gotoEdit")}" type="button">
  4891. <svg viewBox="0 0 1024 1024" style="color: orangered;fill: orangered;" version="1.1" xmlns="http://www.w3.org/2000/svg">
  4892. <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">
  4893. </path>
  4894. </svg>
  4895. </button>
  4896. </div>
  4897. <div class="moreConfig">
  4898. <div title="${i18n('forceStateIframe')}">
  4899. <input name="forceState" id="forceStateIframe" type="radio" />
  4900. <label for="forceStateIframe">${i18n('iframe')}</label>
  4901. </div>
  4902. <div title="${i18n('forceStateDynamic')}">
  4903. <input name="forceState" id="forceStateDynamic" type="radio" />
  4904. <label for="forceStateDynamic">${i18n('dynamic')}</label>
  4905. </div>
  4906. <div title="${i18n('forceStateDisable')}">
  4907. <input name="forceState" id="forceStateDisable" type="radio" />
  4908. <label for="forceStateDisable">${i18n('disable')}</label>
  4909. </div>
  4910. </div>
  4911. <button id="nextSwitch" class="command" title="${i18n("nextSwitch")}" type="button">${i18n("nextSwitch")}</button>
  4912. <button id="loadNow" class="command" title="${i18n("loadNow")}" type="button">${i18n("loadNow")}</button>
  4913. <button id="autoScroll" class="command" title="${i18n("toggleAutoScroll")}" type="button"></button>
  4914. <button id="ruleRequest" class="command" title="${i18n("ruleRequest")}" type="button">${i18n("ruleRequest")}</button>
  4915. <div>
  4916. <textarea class="tempRule" spellcheck="false" placeholder="{Rule object}" title="Rule for current site"></textarea>
  4917. <button id="showDetail" title="" type="button">
  4918. <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>
  4919. </button>
  4920. <div class="addProp">
  4921. <button id="addOtherProp" title="${i18n("addOtherProp")}" type="button">+</button>
  4922. <button id="addNextSelector" title="${i18n("addNextSelector")}" type="button">></button>
  4923. <button id="addPageSelector" title="${i18n("addPageSelector")}" type="button">❏</button>
  4924. </div>
  4925. <button id="saveDetail" title="${i18n("save")}" type="button">
  4926. <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>
  4927. </button>
  4928. </div>
  4929. `);
  4930. let forceStateIframe = frame.querySelector("#forceStateIframe");//forceState 1 禁用 2 强嵌 3 动态
  4931. let forceStateDynamic = frame.querySelector("#forceStateDynamic");
  4932. let forceStateDisable = frame.querySelector("#forceStateDisable");
  4933. let clickRadio = e => {
  4934. let radio = e.currentTarget.querySelector('input');
  4935. if (radio.checked) {
  4936. forceState = "";
  4937. } else {
  4938. switch (radio.id) {
  4939. case "forceStateIframe":
  4940. forceState = 2;
  4941. break;
  4942. case "forceStateDynamic":
  4943. forceState = 3;
  4944. break;
  4945. case "forceStateDisable":
  4946. forceState = 1;
  4947. break;
  4948. default:
  4949. return;
  4950. }
  4951. }
  4952. setListData("forceState", location.host, forceState);
  4953. self.close();
  4954. setTimeout(() => {
  4955. location.reload();
  4956. }, 500);
  4957. };
  4958. forceStateIframe.parentNode.addEventListener("mousedown", clickRadio);
  4959. forceStateDynamic.parentNode.addEventListener("mousedown", clickRadio);
  4960. forceStateDisable.parentNode.addEventListener("mousedown", clickRadio);
  4961. if (forceState == 1) forceStateDisable.checked = true;
  4962. else if (forceState == 2) forceStateIframe.checked = true;
  4963. else if (forceState == 3) forceStateDynamic.checked = true;
  4964. let closeBtn = frame.querySelector(".closePicker");
  4965. let logoBtn = frame.querySelector(".logoIcon");
  4966. let title = frame.querySelector(".title");
  4967. let allpath = frame.querySelector(".allpath");
  4968. let selectorInput = frame.querySelector(".selector");
  4969. let xpath = frame.querySelector("#checkbox_id");
  4970. let checkBtn = frame.querySelector("#check");
  4971. let editBtn = frame.querySelector("#edit");
  4972. let nextSwitchBtn = frame.querySelector("#nextSwitch");
  4973. let autoScrollBtn = frame.querySelector("#autoScroll");
  4974. let loadNow = frame.querySelector("#loadNow");
  4975. let tempRule = frame.querySelector(".tempRule");
  4976. let showDetailBtn = frame.querySelector("#showDetail");
  4977. let saveDetailBtn = frame.querySelector("#saveDetail");
  4978. let addOtherProp = frame.querySelector("#addOtherProp");
  4979. let addNextSelector = frame.querySelector("#addNextSelector");
  4980. let addPageSelector = frame.querySelector("#addPageSelector");
  4981. let ruleRequestBtn = frame.querySelector("#ruleRequest");
  4982. ruleRequestBtn.addEventListener("click", e => {
  4983. _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});
  4984. }, true);
  4985. autoScrollBtn.addEventListener("click", e => {
  4986. self.close();
  4987. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  4988. autoScroll = parseInt(autoScroll) || 0;
  4989. if (autoScroll < 0) autoScroll = 0;
  4990. if (autoScroll && autoScroll != autoScrollRate) {
  4991. autoScrollRate = autoScroll;
  4992. storage.setItem("autoScrollRate", autoScrollRate);
  4993. }
  4994. setListData("autoScroll", location.host + location.pathname, autoScroll);
  4995. startAutoScroll();
  4996. }, true);
  4997. addOtherProp.addEventListener("click", e => {
  4998. let propName = prompt(i18n("propName"), "author");
  4999. if (!propName) return;
  5000. let propValue = prompt(i18n("propValue"));
  5001. if (!propValue) return;
  5002. if (propValue === "true") propValue = true;
  5003. else if (propValue === "false") propValue = false;
  5004. else if (/^\d+$/.test(propValue)) propValue = parseInt(propValue);
  5005. if (propName === "author" && propValue) {
  5006. author = propValue;
  5007. storage.setItem("author", propValue);
  5008. }
  5009. let editTemp = self.getTempRule();
  5010. if (!editTemp) return;
  5011. editTemp[propName] = propValue;
  5012. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  5013. }, true);
  5014. addNextSelector.addEventListener("click", e => {
  5015. let editTemp = self.getTempRule();
  5016. if (!editTemp) return;
  5017. let selector = self.selectorInput.value;
  5018. if (selector) {
  5019. editTemp.nextLink = selector;
  5020. }
  5021. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  5022. }, true);
  5023. addPageSelector.addEventListener("click", e => {
  5024. let editTemp = self.getTempRule();
  5025. if (!editTemp) return;
  5026. let selector = self.selectorInput.value;
  5027. if (selector) {
  5028. editTemp.pageElement = selector;
  5029. }
  5030. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  5031. }, true);
  5032. showDetailBtn.addEventListener("click", e => {
  5033. frame.classList.toggle("showDetail");
  5034. }, true);
  5035. saveDetailBtn.addEventListener("click", e => {
  5036. let editTemp = self.getTempRule(true);
  5037. if (tempRule.value && !editTemp) {
  5038. return;
  5039. }
  5040. if(!ruleParser.customRules) {
  5041. ruleParser.customRules = [];
  5042. }
  5043. ruleParser.customRules = ruleParser.customRules.filter(item => {return item.url != editTemp.url || item.name != editTemp.name});
  5044. if (tempRule.value) {
  5045. ruleParser.customRules.unshift(editTemp);
  5046. ruleParser.curSiteRule = editTemp;
  5047. } else {
  5048. ruleParser.curSiteRule = {};
  5049. isPause = true;
  5050. }
  5051. storage.setItem("customRules", ruleParser.customRules);
  5052. if (ruleParser.hpRules && ruleParser.curSiteRule && !ruleParser.curSiteRule.smart) {
  5053. ruleParser.addToHpRules(true);
  5054. }
  5055. if (window.confirm(i18n("reloadPage"))) {
  5056. setTimeout(() => {location.reload()}, 100);
  5057. }
  5058. }, true);
  5059. nextSwitchBtn.addEventListener("click", e => {
  5060. self.close();
  5061. nextSwitch.start();
  5062. }, true);
  5063. loadNow.addEventListener("click", e => {
  5064. self.close();
  5065. let loadNum = window.prompt(i18n("loadConfirm"), "1");
  5066. if (loadNum === "" || loadNum === null) return;
  5067. autoLoadNum = Math.abs(parseInt(loadNum));
  5068. nextPage();
  5069. }, true);
  5070. closeBtn.addEventListener("click", e => {
  5071. self.close();
  5072. }, true);
  5073. this.showSign = true;
  5074. logoBtn.addEventListener("click", e => {
  5075. logoBtn.classList.toggle("showSign");
  5076. self.showSign = !self.showSign;
  5077. getBody(document).classList.toggle("pagetual-picker");
  5078. }, true);
  5079. let moving = false;
  5080. let initX = 0, initY = 0, initPos = {x: 0, y: 0};
  5081. let moveHanlder = e => {
  5082. if (moving) {
  5083. frame.style.left = e.clientX - initX + "px";
  5084. frame.style.top = e.clientY - initY + "px";
  5085. e.stopPropagation();
  5086. e.preventDefault();
  5087. } else if(Math.abs(e.clientX - initPos.x) + Math.abs(e.clientY - initPos.y) > 20) {
  5088. moving = true;
  5089. }
  5090. };
  5091. let upHanlder = e => {
  5092. if (moving) {
  5093. moving = false;
  5094. } else {
  5095. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  5096. }
  5097. document.removeEventListener("mousemove", moveHanlder, true);
  5098. title.removeEventListener("mouseup", upHanlder, true);
  5099. e.stopPropagation();
  5100. e.preventDefault();
  5101. };
  5102. title.addEventListener("mousedown", e => {
  5103. initPos = {x: e.clientX, y: e.clientY};
  5104. initX = e.clientX - parseInt(getComputedStyle(frame).left);
  5105. initY = e.clientY - parseInt(getComputedStyle(frame).top);
  5106. document.addEventListener("mousemove", moveHanlder, true);
  5107. title.addEventListener("mouseup", upHanlder, true);
  5108. });
  5109. frame.addEventListener("mouseenter", e => {
  5110. if (!self.showSign || moving) return;
  5111. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  5112. self.checkInputSelector(false);
  5113. });
  5114. frame.addEventListener("mouseleave", e => {
  5115. if (!self.showSign) {
  5116. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  5117. self.clearSigns();
  5118. return;
  5119. }
  5120. if (moving) return;
  5121. document.documentElement.appendChild(self.mainSignDiv);
  5122. self.clearSigns();
  5123. });
  5124. checkBtn.addEventListener("click", e => {
  5125. self.checkInputSelector();
  5126. if (this.selectorInput.value && self.foundEle) {
  5127. debug(self.foundEle);
  5128. self.foundEle[0].scrollIntoView({ behavior: "smooth" });
  5129. _GM_setClipboard(this.selectorInput.value);
  5130. showTips(i18n("copied"));
  5131. } else showTips("Null");
  5132. });
  5133. xpath.addEventListener("click", e => {
  5134. if (!selectorInput.value) {
  5135. self.setSelectorDiv("");
  5136. return;
  5137. }
  5138. let element = getElement(selectorInput.value, document);
  5139. let selector = self.getSelectorFromEle(element);
  5140. selectorInput.value = selector;
  5141. self.setSelectorDiv(selector);
  5142. });
  5143. editBtn.addEventListener("click", e => {
  5144. rulesData.editTemp = self.getTempRule();
  5145. storage.setItem("rulesData", rulesData);
  5146. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  5147. });
  5148. editBtn.oncontextmenu = e => {
  5149. e.preventDefault();
  5150. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  5151. };
  5152. this.frame = frame;
  5153. this.xpath = xpath;
  5154. this.allpath = allpath;
  5155. this.selectorInput = selectorInput;
  5156. this.nextSwitchBtn = nextSwitchBtn;
  5157. this.autoScrollBtn = autoScrollBtn;
  5158. this.loadNow = loadNow;
  5159. this.tempRule = tempRule;
  5160. this.logoBtn = logoBtn;
  5161. let setTitleTimer;
  5162. this.moveHandler = e => {
  5163. if (!self.showSign || e.target === document) return;
  5164. let target = self.getTarget(e.target);
  5165. self.adjustSignDiv(self.mainSignDiv, target);
  5166. clearTimeout(setTitleTimer);
  5167. setTitleTimer = setTimeout(() => {
  5168. if (self.inPicker && target.hasAttributes()) {
  5169. let title = target.nodeName.toLowerCase() + "\n";
  5170. for (const attr of target.attributes) {
  5171. title += `【${attr.name}】${attr.value ? " ➡️ " + attr.value : ""}\n`;
  5172. }
  5173. getBody(document).title = title;
  5174. }
  5175. }, 100);
  5176. };
  5177. this.clickHandler = e => {
  5178. if (!self.showSign) return;
  5179. if (self.inPicker) {
  5180. e.stopPropagation();
  5181. e.preventDefault();
  5182. }
  5183. let target = self.getTarget(e.target);
  5184. let selector = self.getSelectorFromEle(target);
  5185. selectorInput.value = selector;
  5186. self.setSelectorDiv(selector);
  5187. };
  5188. }
  5189.  
  5190. getTempRule(detail) {
  5191. if (this.tempRule.value) {
  5192. try {
  5193. this.editTemp = JSON.parse(this.tempRule.value);
  5194. } catch (e) {
  5195. this.editTemp = null;
  5196. if (detail) {
  5197. let pos = e && e.message && e.message.match(/position (\d+)/);
  5198. if (pos) {
  5199. pos = parseInt(pos[1]);
  5200. this.tempRule.value = this.tempRule.value.slice(0, pos) + "➡️" + this.tempRule.value.slice(pos);
  5201. }
  5202. showTips(i18n("errorJson"));
  5203. return null;
  5204. }
  5205. }
  5206. }
  5207. if (!this.editTemp) {
  5208. if (ruleParser.curSiteRule.url && !ruleParser.curSiteRule.smart) {
  5209. this.editTemp = ruleParser.curSiteRule;
  5210. } else {
  5211. this.editTemp = {
  5212. name: document.title,
  5213. url: "^" + (location.origin + location.pathname).replace(/[^\/]*$/, "").replace(/^https?/, "https?").replace(/\./g, "\\."),
  5214. example: location.href
  5215. };
  5216. if (author) this.editTemp.author = author;
  5217. }
  5218. delete this.editTemp.from;
  5219. delete this.editTemp.type;
  5220. delete this.editTemp.updatedAt;
  5221. }
  5222. if (this.selectorInput.value && (!this.frame.classList.contains("showDetail") || !this.editTemp || !this.editTemp.pageElement)) {
  5223. if (this.foundEle && this.foundEle.length === 1) {
  5224. let foundEleRect = this.foundEle[0].getBoundingClientRect();
  5225. if (foundEleRect.height < 100) {
  5226. showTips("Next Link", "", 500);
  5227. this.editTemp.nextLink = this.selectorInput.value;
  5228. return this.editTemp;
  5229. }
  5230. }
  5231. showTips("Page Element", "", 500);
  5232. this.editTemp.pageElement = this.selectorInput.value;
  5233. }
  5234. return this.editTemp;
  5235. }
  5236.  
  5237. getTarget(ele) {
  5238. while (ele.parentNode && (ele.offsetWidth === 0 || ele.offsetHeight === 0)) {
  5239. ele = ele.parentNode;
  5240. }
  5241. return ele;
  5242. }
  5243.  
  5244. close() {
  5245. this.clearSigns();
  5246. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  5247. if (this.mainSignDiv.parentNode) this.mainSignDiv.parentNode.removeChild(this.mainSignDiv);
  5248. getBody(document).classList.remove("pagetual-picker");
  5249. getBody(document).removeEventListener("mousemove", this.moveHandler, true);
  5250. getBody(document).removeEventListener("click", this.clickHandler, true);
  5251. getBody(document).title = "";
  5252. this.inPicker = false;
  5253. }
  5254.  
  5255. setImportant(ele, prop, value) {
  5256. ele.style.setProperty(prop, value, "important");
  5257. }
  5258.  
  5259. createSignDiv() {
  5260. let signDiv = document.createElement("div");
  5261. this.setImportant(signDiv, "position", "absolute");
  5262. this.setImportant(signDiv, "pointer-events", "none");
  5263. this.setImportant(signDiv, "z-index", "2147483645");
  5264. this.setImportant(signDiv, "background", "rgba(120, 170, 210, 0.6)");
  5265. this.setImportant(signDiv, "transition", "all 0.15s ease-out");
  5266. this.setImportant(signDiv, "box-shadow", "rgb(0 0 0) 0px 0px 3px 0px");
  5267. return signDiv;
  5268. }
  5269.  
  5270. adjustSignDiv(div, target) {
  5271. let rect = target.getBoundingClientRect();
  5272. this.setImportant(div, "width", rect.width + "px");
  5273. this.setImportant(div, "height", rect.height + "px");
  5274. this.setImportant(div, "left", rect.left + window.scrollX + "px");
  5275. this.setImportant(div, "top", rect.top + window.scrollY + "px");
  5276. }
  5277.  
  5278. getSelectorFromEle(ele) {
  5279. return this.xpath.checked ? createXPathFromElement(ele) : geneSelector(ele, true);
  5280. }
  5281.  
  5282. fillTempRuleTextarea() {
  5283. if (!this.frame.classList.contains("showDetail") || !this.editTemp || !this.editTemp.pageElement) this.tempRule.value = JSON.stringify(this.getTempRule(), null, 4);
  5284. }
  5285.  
  5286. setSelectorDiv(selector) {
  5287. let self = this;
  5288. this.allpath.innerHTML = createHTML("");
  5289. if (selector) {
  5290. if (this.xpath.checked) {
  5291. let span = document.createElement("span");
  5292. span.innerText = selector;
  5293. span.addEventListener("click", e => {
  5294. self.selectorInput.value = selector;
  5295. self.checkInputSelector();
  5296. }, true);
  5297. this.allpath.appendChild(span);
  5298. } else {
  5299. selector.split(">").forEach((item, index) => self.geneSelectorItem(item, index));
  5300. }
  5301. }
  5302. this.checkInputSelector();
  5303. }
  5304.  
  5305. geneSelectorItem(item, index) {
  5306. let self = this;
  5307. item = item.trim();
  5308. if (!item) return;
  5309. if (index !== 0) {
  5310. let span = document.createElement("span");
  5311. span.innerText = " > ";
  5312. this.allpath.appendChild(span);
  5313. }
  5314. let span = document.createElement("span");
  5315. span.className = "path";
  5316. span.innerText = item;
  5317. span.addEventListener("click", e => {
  5318. let selector = "";
  5319. let target = e.target;
  5320. while (target) {
  5321. selector = target.innerText + selector;
  5322. target = target.previousElementSibling;
  5323. }
  5324. self.selectorInput.value = selector;
  5325. self.checkInputSelector();
  5326. if (self.checkedPath) {
  5327. self.checkedPath.classList.remove("checked");
  5328. }
  5329. span.classList.add("checked");
  5330. self.checkedPath = span;
  5331. }, true);
  5332. this.allpath.appendChild(span);
  5333. }
  5334.  
  5335. checkInputSelector(fill = true) {
  5336. let self = this;
  5337. this.clearSigns();
  5338. if (!this.selectorInput.value) return;
  5339. let eles = getAllElements(this.selectorInput.value, document);
  5340. this.foundEle = null;
  5341. if (eles && eles.length > 0) {
  5342. this.foundEle = eles;
  5343. eles.forEach(ele => {
  5344. let sign = self.createSignDiv();
  5345. document.documentElement.appendChild(sign);
  5346. self.adjustSignDiv(sign, ele);
  5347. self.signList.push(sign);
  5348. });
  5349. if (fill) this.fillTempRuleTextarea();
  5350. }
  5351. }
  5352.  
  5353. clearSigns() {
  5354. this.signList.forEach(sign => {
  5355. if (sign.parentNode) sign.parentNode.removeChild(sign);
  5356. });
  5357. this.signList = [];
  5358. }
  5359.  
  5360. start() {
  5361. this.init();
  5362. if (this.inPicker) return;
  5363. this.inPicker = true;
  5364. if (!this.styleEle || !this.styleEle.parentNode) {
  5365. this.styleEle = _GM_addStyle(this.cssText);
  5366. }
  5367. document.documentElement.appendChild(this.frame);
  5368. document.documentElement.appendChild(this.mainSignDiv);
  5369. getBody(document).classList.add("pagetual-picker");
  5370.  
  5371. this.logoBtn.classList.remove("showSign");
  5372. this.showSign = true;
  5373.  
  5374. getBody(document).addEventListener("mousemove", this.moveHandler, true);
  5375. getBody(document).addEventListener("click", this.clickHandler, true);
  5376. this.xpath.checked = isXPath(ruleParser.curSiteRule.pageElement);
  5377. this.tempRule.value = "";
  5378. this.editTemp = null;
  5379. this.frame.classList.remove("showDetail");
  5380.  
  5381. this.loadNow.style.display = ruleParser.nextLinkHref ? "block" : "none";
  5382. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  5383. this.nextSwitchBtn.style.display = "block";
  5384. } else {
  5385. this.nextSwitchBtn.style.display = "none";
  5386. }
  5387. this.autoScrollBtn.innerText = i18n(autoScroll ? "disableAutoScroll" : "enableAutoScroll");
  5388.  
  5389. let pageElementSel = ruleParser.curSiteRule.pageElement || "";
  5390. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  5391. pageElementSel = pageElementSel[nextIndex < pageElementSel.length ? nextIndex : 0];
  5392. }
  5393. this.setSelectorDiv(pageElementSel);
  5394. this.fillTempRuleTextarea();
  5395. }
  5396. }
  5397. const picker = new Picker();
  5398.  
  5399. var editor, editorChanged = false, customRulesInput;
  5400. function createEdit() {
  5401. var options = {
  5402. mode: 'code',
  5403. modes: ['code', 'tree'],
  5404. templates: [
  5405. {
  5406. text: 'New site',
  5407. title: 'Insert a new site',
  5408. className: 'jsoneditor-type-object',
  5409. field: 'SiteTemplate',
  5410. value: {
  5411. 'name': 'Site name',
  5412. 'url': 'Site url'
  5413. }
  5414. }
  5415. ],
  5416. schema: {
  5417. "title": "Sites data",
  5418. "description": "Object containing site config",
  5419. "type": "array",
  5420. "items": {
  5421. "type": 'object',
  5422. "properties": {
  5423. "name": {
  5424. "title": "Site Name",
  5425. "description": "The site's name.",
  5426. "examples": [
  5427. "Google"
  5428. ],
  5429. "type": "string"
  5430. },
  5431. "url": {
  5432. "title": "Site Url",
  5433. "description": "The Regexp of site's url.",
  5434. "examples": [
  5435. "^https:\/\/yande\\.re\/"
  5436. ],
  5437. "type": "string"
  5438. }
  5439. },
  5440. "required": ["name", "url"]
  5441. }
  5442. },
  5443. onChange: () => {
  5444. editorChanged = true;
  5445. }
  5446. };
  5447. setTimeout(() => {
  5448. var container = document.getElementById("jsoneditor");
  5449. container.style.height = '800px';
  5450. container.innerHTML = "";
  5451. try {
  5452. editor = new _unsafeWindow.JSONEditor(container, options);
  5453. editor.set(ruleParser.customRules);
  5454. } catch (e) {
  5455. editor = null;
  5456. container.style.display = 'none';
  5457. customRulesInput.style.display = "";
  5458. }
  5459. }, 500);
  5460. }
  5461.  
  5462. function checkGuidePage(href) {
  5463. if (guidePage.test(href)) {
  5464. if (typeof _unsafeWindow.JSONEditor !== 'undefined') {
  5465. createEdit();
  5466. } else {
  5467. let timeout = 30;
  5468. let checkEditorReady = setInterval(() => {
  5469. if (typeof _unsafeWindow.JSONEditor !== 'undefined') {
  5470. createEdit();
  5471. clearInterval(checkEditorReady);
  5472. } else if (timeout-- <= 0) {
  5473. editor = null;
  5474. customRulesInput.style.display = "";
  5475. clearInterval(checkEditorReady);
  5476. }
  5477. }, 100);
  5478. }
  5479. return true;
  5480. }
  5481. return false;
  5482. }
  5483.  
  5484. function startAutoScroll() {
  5485. clearInterval(autoScrollInterval);
  5486. if (autoScroll <= 0) return;
  5487. let scrollRange_o = 1;
  5488. if (autoScroll > 1000) {
  5489. scrollRange_o = parseInt(autoScroll / 1000);
  5490. }
  5491. let devicePixelRatio = window.devicePixelRatio;
  5492. let scrollRange = Math.ceil(scrollRange_o / devicePixelRatio);
  5493.  
  5494. let scrollTarget, body = getBody(document);
  5495. let checkOverflow = ele => {
  5496. return ele.scrollHeight !== ele.clientHeight && getComputedStyle(ele).overflowY !== "hidden";
  5497. };
  5498. if (document.documentElement.scrollTop || checkOverflow(document.documentElement)) {
  5499. scrollTarget = document.documentElement;
  5500. } else if (body.scrollTop || checkOverflow(body)) {
  5501. scrollTarget = body;
  5502. } else {
  5503. let tempEle;
  5504. let img = body.querySelector('img');
  5505. if (img) {
  5506. tempEle = img;
  5507. while (tempEle && !checkOverflow(tempEle)) {
  5508. tempEle = tempEle.parentNode;
  5509. }
  5510. }
  5511. if (!tempEle && document.activeElement) {
  5512. let tempEle = document.activeElement;
  5513. while (tempEle && !checkOverflow(tempEle)) {
  5514. tempEle = tempEle.parentNode;
  5515. }
  5516. }
  5517. if (tempEle) scrollTarget = tempEle;
  5518. }
  5519. scrollTarget = scrollTarget || document.documentElement;
  5520.  
  5521. autoScrollInterval = setInterval(() => {
  5522. if (isPause) return;
  5523. if (devicePixelRatio !== window.devicePixelRatio) {
  5524. devicePixelRatio = window.devicePixelRatio;
  5525. scrollRange = Math.ceil(scrollRange_o / devicePixelRatio);
  5526. }
  5527. scrollTarget.scrollTop += scrollRange;
  5528. }, parseInt(1000 / autoScroll));
  5529. }
  5530.  
  5531. var inUpdate = false;
  5532. var importHandler, configCon;
  5533. function initConfig(href) {
  5534. if (location.hostname === "github.com") {
  5535. 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) {
  5536. let issue_body = document.getElementById("issue_body");
  5537. if (!issue_body) return true;
  5538. issue_body.value = issue_body.value.replace("\n", "\n" + location.hash.slice(1) + "\n");
  5539. let starButton = document.createElement("a");
  5540. starButton.href = "https://github.com/hoothin/UserScripts#star";
  5541. starButton.className = "js-toggler-target rounded-left-2 btn-with-aria-count btn-sm btn";
  5542. 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>');
  5543. starButton.style.float = "right";
  5544. document.querySelector(".Layout-main>h2").appendChild(starButton);
  5545. return true;
  5546. } else if (location.href === "https://github.com/hoothin/UserScripts#star") {
  5547. let starButton = document.querySelector(".starring-container:not(.on)>.unstarred>form>button");
  5548. if (starButton) emuClick(starButton);
  5549. return true;
  5550. }
  5551. }
  5552. let isGuidePage = checkGuidePage(href);
  5553.  
  5554. var click2import, importUrlPres;
  5555.  
  5556. let inConfig = isGuidePage;
  5557. if (!inConfig) {
  5558. for (let i = 0; i < configPage.length; i++) {
  5559. if (configPage[i] == location.href) {
  5560. inConfig = true;
  5561. break;
  5562. }
  5563. }
  5564. }
  5565. if (!isGuidePage) {
  5566. if (href.indexOf("PagetualGuide") != -1 || location.hostname === "pagetual.hoothin.com") isGuidePage = true;
  5567. }
  5568. configCon = document.getElementById("configCon");
  5569. if (configCon) {
  5570. configCon.parentNode.removeChild(configCon);
  5571. }
  5572. if (ruleImportUrlReg.test(href) || inConfig) {
  5573. let importing = false;
  5574. if (!inUpdate && rulesData.uninited) {
  5575. setTimeout(() => {
  5576. if (!inUpdate && !importing) showTips(i18n("firstAlert"));
  5577. }, 3000);
  5578. showTips(i18n("firstAlert"));
  5579. }
  5580. let defaultOption = document.querySelector('#discussion_rating_4');
  5581. if (defaultOption) defaultOption.checked = true;
  5582. let createImportBtn = (pre) => {
  5583. let importBtn = document.createElement("button");
  5584. importBtn.id = "pagetualImport";
  5585. importBtn.innerText = i18n("import");
  5586. importBtn.style.marginTop = "100px";
  5587. importBtn.style.float = "right";
  5588. importBtn.style.position = "relative";
  5589. importBtn.style.display = "block";
  5590. importBtn.style.fontSize = "20px";
  5591. importBtn.addEventListener("click", e => {
  5592. let parentNode = importBtn.parentNode;
  5593. if (!parentNode) return;
  5594. parentNode.removeChild(importBtn);
  5595. try {
  5596. let rules = parentNode.innerText.trim();
  5597. let isContent = /['"]name['"]/i.test(rules);
  5598. if (isContent) {
  5599. let ruleList = JSON.parse(`[${rules}]`);
  5600. for (let i in ruleList) {
  5601. let hasRule = false;
  5602. let r = ruleList[i];
  5603. for (let j in ruleParser.customRules) {
  5604. if (ruleParser.customRules[j].name == r.name) {
  5605. ruleParser.customRules[j] = r;
  5606. hasRule = true;
  5607. break;
  5608. }
  5609. }
  5610. if (!hasRule) ruleParser.customRules.push(r);
  5611. ruleParser.hpRules.unshift(r);
  5612. }
  5613. storage.setItem("customRules", ruleParser.customRules);
  5614. storage.setItem("hpRules", ruleParser.hpRules);
  5615. storage.setItem("smartRules", []);
  5616. showTips(i18n("importSucc"));
  5617. } else {
  5618. rules = rules.split("\n");
  5619. let diff = false;
  5620. for (let c = 0; c < rules.length; c++) {
  5621. let urlArr = rules[c].split("|"), url, type = 1;
  5622. if (urlArr.length == 1) {
  5623. url = urlArr[0].trim();
  5624. if (!/^http/.test(url)) {
  5625. showTips(i18n("errorWrongUrl"));
  5626. return;
  5627. }
  5628. } else if (urlArr.length == 2) {
  5629. type = urlArr[0].trim();
  5630. url = urlArr[1].trim();
  5631. if (!/^http/.test(url)) {
  5632. showTips(i18n("errorWrongUrl"));
  5633. return;
  5634. }
  5635. } else {
  5636. break;
  5637. }
  5638. let maxId = 1, hasUrl = false;
  5639. if (!rulesData.urls) {
  5640. rulesData.urls = [];
  5641. maxId = 1;
  5642. } else {
  5643. rulesData.urls.forEach(u => {
  5644. if (maxId < u.id) {
  5645. maxId = u.id;
  5646. }
  5647. if (u.url == url) {
  5648. hasUrl = true;
  5649. }
  5650. });
  5651. if (hasUrl) break;
  5652. }
  5653. diff = true;
  5654. if (!rulesData.sort) rulesData.sort = [1];
  5655. rulesData.urls.push({id: maxId + 1, url: url, type: type});
  5656. rulesData.sort.unshift(maxId + 1);
  5657. }
  5658. if (!diff) {
  5659. showTips(i18n("errorAlreadyExists"));
  5660. setTimeout(() => {
  5661. showTips(i18n("beginUpdate"), "", 50000);
  5662. updateRules(() => {
  5663. showTips(i18n("updateSucc"));
  5664. location.reload();
  5665. }, (rule, err) => {
  5666. showTips(`Failed to update ${rule.url} rules!`);
  5667. debug(err);
  5668. });
  5669. }, 500);
  5670. return;
  5671. }
  5672. storage.setItem("rulesData", rulesData);
  5673.  
  5674. if (rulesData.urls) ruleUrls = ruleUrls.concat(rulesData.urls);
  5675. if (rulesData.sort) {
  5676. let urls = [];
  5677. rulesData.sort.forEach(id => {
  5678. for (let s = 0; s < ruleUrls.length; s++) {
  5679. if (id == ruleUrls[s].id) {
  5680. urls.push(ruleUrls[s]);
  5681. break;
  5682. }
  5683. }
  5684. });
  5685. ruleUrls = urls;
  5686. }
  5687. showTips(i18n("beginUpdate"), "", 30000);
  5688. updateRules(() => {
  5689. showTips(i18n("updateSucc"));
  5690. location.reload();
  5691. }, (rule, err) => {
  5692. showTips(`Failed to update ${rule.url} rules!`);
  5693. debug(err);
  5694. });
  5695. importing = true;
  5696. }
  5697. } catch (e) {
  5698. _GM_notification(e.toString());
  5699. }
  5700. });
  5701. if (pre) {
  5702. let clientHeight = 35 - pre.clientHeight;
  5703. if (clientHeight > -20) clientHeight = -20;
  5704. importBtn.style.marginTop = `${clientHeight}px`;
  5705. pre.appendChild(importBtn);
  5706. }
  5707. return importBtn;
  5708. };
  5709. [].forEach.call(document.querySelectorAll('pre[name=pagetual],pre[name=user-content-pagetual]'), pre => {
  5710. let importBtn = createImportBtn(pre);
  5711. pre.style.display = "";
  5712. });
  5713. click2import = document.querySelector("[name='user-content-click2import'],[name='click2import']");
  5714. if (click2import) click2import.innerText = i18n("click2ImportRule");
  5715. if (!importHandler) {
  5716. importHandler = e => {
  5717. if (compareNodeName(e.target, ["pre"])) {
  5718. let nameAttr = e.target.getAttribute("name");
  5719. if (nameAttr == "pagetual" || nameAttr == "user-content-pagetual") {
  5720. if (e.target.querySelector('#pagetualImport')) return;
  5721. let importBtn = createImportBtn(e.target);
  5722. }
  5723. }
  5724. };
  5725. }
  5726. document.removeEventListener("mouseover", importHandler);
  5727. document.addEventListener("mouseover", importHandler);
  5728.  
  5729. if (inConfig) {
  5730. if (!inUpdate && _GM_info.script && _GM_info.script.version && _GM_info.script.version !== '1.0.0') {
  5731. let versionEle = document.querySelector('.markdown-body>h1[id],article>h1');
  5732. let latestVer = versionEle && versionEle.innerText.match(/\d[\d\.]+/)[0];
  5733. if (latestVer && latestVer != _GM_info.script.version) {
  5734. showTips(i18n('outOfDate'), "", 3000);
  5735. }
  5736. }
  5737. _GM_addStyle(`
  5738. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  5739. cursor: pointer;
  5740. user-select: none;
  5741. display: inline-block;
  5742. margin-right: 5px;
  5743. -moz-transition:color 0.3s ease, transform 0.3s;
  5744. -webkit-transition:color 0.3s ease, transform 0.3s;
  5745. transition:color 0.3s ease, transform 0.3s;
  5746. }
  5747. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  5748. color:red;
  5749. transform: scale(1.5);
  5750. -webkit-transform: scale(1.5);
  5751. }
  5752. .updateDate{
  5753. cursor: pointer;
  5754. user-select: none;
  5755. -moz-transition:color 0.3s ease, transform 0.3s;
  5756. -webkit-transition:color 0.3s ease, transform 0.3s;
  5757. transition:color 0.3s ease, transform 0.3s;
  5758. transform-origin: left;
  5759. -webkit-transform-origin: left;
  5760. }
  5761. .updateDate:hover{
  5762. color:red;
  5763. transform: scale(1.1);
  5764. -webkit-transform: scale(1.1);
  5765. }
  5766. input[type=number]::-webkit-inner-spin-button,
  5767. input[type=number]::-webkit-outer-spin-button {
  5768. -webkit-appearance: none;
  5769. margin: 0;
  5770. }
  5771. input[type=number] {
  5772. -moz-appearance:textfield;
  5773. }
  5774. table td>h3 {
  5775. margin: 16px!important;
  5776. padding: 0!important;
  5777. }
  5778. table td>h4 {
  5779. padding: 0!important;
  5780. }
  5781. #saveBtn {
  5782. width: 60vw;
  5783. position: fixed;
  5784. z-index: 999;
  5785. bottom: 0;
  5786. left: 20vw;
  5787. font-size: xx-large;
  5788. opacity: 0.6;
  5789. cursor: pointer;
  5790. -moz-transition:all 0.3s ease;
  5791. -webkit-transition:all 0.3s ease;
  5792. transition:all 0.3s ease;
  5793. }
  5794. #configCon #saveBtn:hover {
  5795. opacity: 1;
  5796. margin-bottom: 0px;
  5797. }
  5798. #configCon #saveBtn {
  5799. margin-bottom: -30px;
  5800. }
  5801. #configCon.showSave #saveBtn {
  5802. margin-bottom: 0px;
  5803. }
  5804. `);
  5805. configCon = document.querySelector(".markdown-body,.theme-default-content");
  5806. if (!configCon) {
  5807. setTimeout(() => {
  5808. location.reload();
  5809. }, 1000);
  5810. return true;
  5811. }
  5812. let insertPos = configCon.querySelector("hr,#jsoneditor");
  5813. configCon = document.createElement("div");
  5814. configCon.id = "configCon";
  5815. insertPos.parentNode.insertBefore(configCon, insertPos);
  5816.  
  5817. importUrlPres = document.querySelectorAll("pre[name='user-content-pagetual'],pre[name='pagetual']");
  5818. if (importUrlPres) {
  5819. [].forEach.call(importUrlPres, importUrlPre => {
  5820. importUrlPre.style.overflow = "hidden";
  5821. importUrlPre.style.display = rulesData.uninited ? "block" : "none";
  5822. });
  5823. }
  5824. if (click2import) click2import.style.display = rulesData.uninited ? "block" : "none";
  5825. let otherconfig = document.querySelector("a[name='user-content-otherconfig'],a[name='otherconfig']");
  5826. if (otherconfig) otherconfig.parentNode.removeChild(otherconfig);
  5827. let rulesExample = document.querySelector("#user-content-rules-example+a,#rules-example>a");
  5828. if (rulesExample) {
  5829. rulesExample.innerText = i18n("rulesExample");
  5830. if (lang == "zh-CN") {
  5831. rulesExample.href = rulesExample.href.replace("en", "cn");
  5832. } else if (lang == "zh-TW" || lang == "zh-HK") {
  5833. rulesExample.href = rulesExample.href.replace("/en", "");
  5834. }
  5835. }
  5836.  
  5837. let newPos, lastPos = 0;
  5838. window.addEventListener('scroll', function(e) {
  5839. newPos = window.scrollY;
  5840. if (newPos > lastPos) {
  5841. configCon.classList.add("showSave");
  5842. } else {
  5843. configCon.classList.remove("showSave");
  5844. }
  5845. lastPos = newPos;
  5846. });
  5847. } else return isGuidePage;
  5848. } else return isGuidePage;
  5849. let ruleBarInsertPos = document.createTextNode(' ');
  5850. configCon.appendChild(ruleBarInsertPos);
  5851. class Rulebar {
  5852. init(ruleUrl) {
  5853. let id = ruleUrl.id;
  5854. this.ruleUrl = ruleUrl;
  5855. this.item = document.createElement("p");
  5856. this.item.dataset.id = id;
  5857. let url = document.createElement("a");
  5858. url.href = ruleUrl.url;
  5859. url.innerHTML = ruleUrl.url;
  5860. url.title = ruleUrl.url;
  5861. let up = document.createElement("span");
  5862. up.innerHTML = "↑ ";
  5863. up.title = i18n("sortTitle");
  5864. let down = document.createElement("span");
  5865. down.innerHTML = "↓ ";
  5866. down.title = i18n("sortTitle");
  5867. let del = document.createElement("span");
  5868. del.innerHTML = "× ";
  5869. up.onclick = e => {
  5870. this.moveUp();
  5871. };
  5872. down.onclick = e => {
  5873. this.moveDown();
  5874. };
  5875. del.onclick = e => {
  5876. this.del();
  5877. };
  5878. this.item.appendChild(up);
  5879. this.item.appendChild(down);
  5880. this.item.appendChild(del);
  5881. this.item.appendChild(url);
  5882. if (ruleParser.rules) {
  5883. url.style.maxWidth = "calc(100% - 150px)";
  5884. url.style.overflow = "hidden";
  5885. url.style.display = "inline-block";
  5886. url.style.textOverflow = "ellipsis";
  5887. url.style.verticalAlign = "bottom";
  5888. url.style.whiteSpace = "nowrap";
  5889. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == id ? 1 : 0), 0);
  5890. let idSpan = document.createElement("span");
  5891. idSpan.style.float = "right";
  5892. idSpan.innerHTML = `[rules: ${rulesLength}]`;
  5893. this.item.appendChild(idSpan);
  5894. this.idSpan = idSpan;
  5895. }
  5896. configCon.insertBefore(this.item, ruleBarInsertPos);
  5897. }
  5898. updateNum() {
  5899. if (ruleParser.rules) {
  5900. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == this.item.dataset.id ? 1 : 0), 0);
  5901. this.idSpan.innerHTML = `[rules: ${rulesLength}]`;
  5902. }
  5903. }
  5904. saveSort() {
  5905. let sort = [];
  5906. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i => {
  5907. sort.push(i.dataset.id);
  5908. });
  5909. rulesData.sort = sort;
  5910. let urls = [];
  5911. sort.forEach(id => {
  5912. for (let s = 0; s < ruleUrls.length; s++) {
  5913. if (id == ruleUrls[s].id) {
  5914. urls.push(ruleUrls[s]);
  5915. break;
  5916. }
  5917. }
  5918. });
  5919. ruleUrls = urls;
  5920. storage.setItem("rulesData", rulesData);
  5921. showTips(i18n("sortTitle"));
  5922. }
  5923. moveUp() {
  5924. let preE = this.item.previousElementSibling;
  5925. if (compareNodeName(preE, ["p"]) && preE.children.length > 1) {
  5926. this.item.parentNode.insertBefore(this.item, preE);
  5927. this.saveSort();
  5928. }
  5929. }
  5930. moveDown() {
  5931. let nextE = this.item.nextElementSibling;
  5932. if (compareNodeName(nextE, ["p"]) && nextE.children.length > 1) {
  5933. this.item.parentNode.insertBefore(nextE, this.item);
  5934. this.saveSort();
  5935. }
  5936. }
  5937. del() {
  5938. if (this.ruleUrl.id < 2) {
  5939. showTips(i18n("cantDel"));
  5940. } else if (window.confirm(i18n("confirmDel"))) {
  5941. for (let u = 0; u < rulesData.urls.length; u++) {
  5942. if (this.ruleUrl.id == rulesData.urls[u].id) {
  5943. rulesData.urls.splice(u, 1);
  5944. break;
  5945. }
  5946. }
  5947. for (let u = 0; u < ruleUrls.length; u++) {
  5948. if (this.ruleUrl.id == ruleUrls[u].id) {
  5949. ruleUrls.splice(u, 1);
  5950. break;
  5951. }
  5952. }
  5953. for (let u = 0; u < rulesData.sort.length; u++) {
  5954. if (this.ruleUrl.id == rulesData.sort[u]) {
  5955. rulesData.sort.splice(u, 1);
  5956. break;
  5957. }
  5958. }
  5959. rulesData.ruleVersion = 0;
  5960. storage.setItem("rulesData", rulesData);
  5961. ruleParser.rules = ruleParser.rules.filter(item => {return item.from != this.ruleUrl.id});
  5962. storage.setItem("rules", ruleParser.rules);
  5963. this.item.parentNode.removeChild(this.item);
  5964. //location.reload();
  5965. }
  5966. }
  5967. }
  5968. let langSelect = document.createElement("select");
  5969. langSelect.style.float = "right";
  5970. langSelect.style.position = "relative";
  5971. langSelect.style.zIndex = "1";
  5972. let option = document.createElement("option");
  5973. option.value = "";
  5974. option.innerText = "Language";
  5975. langSelect.appendChild(option);
  5976. for (let key in langList) {
  5977. let option = document.createElement("option");
  5978. option.value = key;
  5979. option.innerText = langList[key];
  5980. langSelect.appendChild(option);
  5981. }
  5982. langSelect.value = rulesData.lang || "";
  5983. configCon.appendChild(langSelect);
  5984.  
  5985. let updateP = document.createElement("p"), i = 0;
  5986. let now = new Date().getTime();
  5987.  
  5988.  
  5989. let pastDate = (new Date(updateDate)).toString(), passStr;
  5990. let passTime = (now - updateDate) / 1000;
  5991. if (isNaN(passTime)) {
  5992. passStr = i18n("firstUpdate");
  5993. } else {
  5994. if (passTime < 60) {
  5995. passStr = i18n("passSec", parseInt(passTime));
  5996. } else if (passTime < 60 * 60) {
  5997. passStr = i18n("passMin", parseInt(passTime / 60));
  5998. } else if (passTime < 60 * 60 * 24) {
  5999. passStr = i18n("passHour", parseInt(passTime / 3600));
  6000. } else {
  6001. passStr = i18n("passDay", parseInt(passTime / 86400));
  6002. }
  6003. passStr += " 🖱 " + i18n("click2update");
  6004. }
  6005.  
  6006. let rulebarList = [], updateFail = false;
  6007. updateP.className = "updateDate";
  6008. updateP.innerHTML = passStr;
  6009. updateP.title = i18n("update") + " - " + pastDate;
  6010. configCon.appendChild(updateP);
  6011. if (ruleUrls) {
  6012. ruleUrls.forEach(ruleUrl => {
  6013. let rulebar = new Rulebar();
  6014. rulebar.init(ruleUrl);
  6015. rulebarList.push(rulebar);
  6016. });
  6017. }
  6018. let customUrlsTitle = document.createElement("h2");
  6019. customUrlsTitle.innerHTML = i18n("customUrls");
  6020. configCon.appendChild(customUrlsTitle);
  6021. let customUrlsInput = document.createElement("textarea");
  6022. customUrlsInput.style.width = "100%";
  6023. customUrlsInput.style.position = "relative";
  6024. customUrlsInput.placeholder = "http://wedata.net/databases/AutoPagerize/items_all.json \nhttps://hoothin.github.io/UserScripts/Pagetual/pagetualRules.json";
  6025. customUrlsInput.spellcheck = false;
  6026. configCon.appendChild(customUrlsInput);
  6027.  
  6028. let btns = document.createElement("div");
  6029. btns.style.display = "flex";
  6030. configCon.appendChild(btns);
  6031. let upBtnImg = document.createElement("div");
  6032. upBtnImg.style.width = "33%";
  6033. let upBtnImgTitle = document.createElement("h2");
  6034. upBtnImgTitle.style.whiteSpace = "nowrap";
  6035. upBtnImgTitle.style.overflow = "auto";
  6036. upBtnImgTitle.innerHTML = i18n("upBtnImg");
  6037. upBtnImg.appendChild(upBtnImgTitle);
  6038. let upBtnImgInput = document.createElement("input");
  6039. upBtnImgInput.style.width = "100%";
  6040. upBtnImgInput.style.position = "relative";
  6041. upBtnImgInput.placeholder = "data:image/png;base64,UpBtn";
  6042. upBtnImgInput.value = rulesData.upBtnImg || '';
  6043. upBtnImgInput.spellcheck = false;
  6044. upBtnImg.appendChild(upBtnImgInput);
  6045. btns.appendChild(upBtnImg);
  6046.  
  6047. let downBtnImg = document.createElement("div");
  6048. downBtnImg.style.width = "33%";
  6049. let downBtnImgTitle = document.createElement("h2");
  6050. downBtnImgTitle.style.whiteSpace = "nowrap";
  6051. downBtnImgTitle.style.overflow = "auto";
  6052. downBtnImgTitle.innerHTML = i18n("downBtnImg");
  6053. downBtnImg.appendChild(downBtnImgTitle);
  6054. let downBtnImgInput = document.createElement("input");
  6055. downBtnImgInput.style.width = "100%";
  6056. downBtnImgInput.style.position = "relative";
  6057. downBtnImgInput.placeholder = "data:image/png;base64,DownBtn";
  6058. downBtnImgInput.value = rulesData.downBtnImg || '';
  6059. downBtnImgInput.spellcheck = false;
  6060. downBtnImg.appendChild(downBtnImgInput);
  6061. btns.appendChild(downBtnImg);
  6062.  
  6063. let sideControllerIconDiv = document.createElement("div");
  6064. sideControllerIconDiv.style.width = "33%";
  6065. let sideControllerIconTitle = document.createElement("h2");
  6066. sideControllerIconTitle.style.whiteSpace = "nowrap";
  6067. sideControllerIconTitle.style.overflow = "auto";
  6068. sideControllerIconTitle.innerHTML = i18n("sideControllerIcon");
  6069. sideControllerIconDiv.appendChild(sideControllerIconTitle);
  6070. let sideControllerIconInput = document.createElement("input");
  6071. sideControllerIconInput.style.width = "100%";
  6072. sideControllerIconInput.style.position = "relative";
  6073. sideControllerIconInput.placeholder = "📄";
  6074. sideControllerIconInput.value = rulesData.sideControllerIcon || '';
  6075. sideControllerIconInput.spellcheck = false;
  6076. sideControllerIconDiv.appendChild(sideControllerIconInput);
  6077. btns.appendChild(sideControllerIconDiv);
  6078.  
  6079. let otherBtns = document.createElement("div");
  6080. otherBtns.style.display = "flex";
  6081. configCon.appendChild(otherBtns);
  6082. let loadingText = document.createElement("div");
  6083. loadingText.style.width = "100%";
  6084. let loadingTextTitle = document.createElement("h2");
  6085. loadingTextTitle.style.whiteSpace = "nowrap";
  6086. loadingTextTitle.style.overflow = "auto";
  6087. loadingTextTitle.innerHTML = i18n("loadingTextTitle");
  6088. loadingText.appendChild(loadingTextTitle);
  6089. let loadingTextInput = document.createElement("input");
  6090. loadingTextInput.value = rulesData.loadingText || '';
  6091. loadingTextInput.placeholder = i18n("loadingText");
  6092. loadingTextInput.style.width = "100%";
  6093. loadingTextInput.style.position = "relative";
  6094. loadingTextInput.style.margin = "0";
  6095. loadingTextInput.spellcheck = false;
  6096. loadingText.appendChild(loadingTextInput);
  6097. otherBtns.appendChild(loadingText);
  6098.  
  6099. let opacity = document.createElement("div");
  6100. let opacityTitle = document.createElement("h2");
  6101. opacityTitle.style.whiteSpace = "nowrap";
  6102. opacityTitle.style.overflow = "visible";
  6103. opacityTitle.innerHTML = i18n("opacity");
  6104. opacity.appendChild(opacityTitle);
  6105. let opacityInput = document.createElement("input");
  6106. opacityInput.value = rulesData.opacity * 100;
  6107. opacityInput.type = "number";
  6108. opacityInput.min = 0;
  6109. opacityInput.max = 100;
  6110. opacityInput.style.width = "110px";
  6111. opacityInput.style.position = "relative";
  6112. opacityInput.style.margin = "0";
  6113. opacityInput.placeholder = i18n("opacityPlaceholder");
  6114. opacityInput.spellcheck = false;
  6115. opacityInput.oninput = e => {
  6116. if (opacityInput.value > 100) opacityInput.value = 100;
  6117. else if (opacityInput.value < 0) opacityInput.value = 0;
  6118. };
  6119. opacity.appendChild(opacityInput);
  6120. otherBtns.appendChild(opacity);
  6121.  
  6122. let pageElementCss = document.createElement("div");
  6123. pageElementCss.style.marginBottom = "30px";
  6124. let pageElementCssTitle = document.createElement("h2");
  6125. pageElementCssTitle.innerHTML = i18n("pageElementCss");
  6126. pageElementCss.appendChild(pageElementCssTitle);
  6127. let pageElementCssInput = document.createElement("input");
  6128. pageElementCssInput.value = rulesData.pageElementCss || '';
  6129. pageElementCssInput.style.width = "100%";
  6130. pageElementCssInput.style.position = "relative";
  6131. pageElementCssInput.style.margin = "0";
  6132. pageElementCssInput.placeholder = "font-size: xx-large;";
  6133. pageElementCssInput.spellcheck = false;
  6134. pageElementCss.appendChild(pageElementCssInput);
  6135. configCon.appendChild(pageElementCss);
  6136.  
  6137. let customCss = document.createElement("div");
  6138. customCss.style.marginBottom = "50px";
  6139. let customCssTitle = document.createElement("h2");
  6140. customCssTitle.innerHTML = i18n("customCss");
  6141. customCss.appendChild(customCssTitle);
  6142. let customCssInput = document.createElement("textarea");
  6143. customCssInput.value = rulesData.customCss || '';
  6144. customCssInput.style.width = "100%";
  6145. customCssInput.style.position = "relative";
  6146. customCssInput.style.margin = "0";
  6147. customCssInput.placeholder = ".pagetual {\n}";
  6148. customCssInput.spellcheck = false;
  6149. customCss.appendChild(customCssInput);
  6150. configCon.appendChild(customCss);
  6151.  
  6152. let configTable = document.createElement("table");
  6153. configTable.style.width = "100%";
  6154. let configTbody = document.createElement("tbody");
  6155. configTbody.style.width = "99%";
  6156. configTbody.style.display = "inline-table";
  6157. configTable.appendChild(configTbody);
  6158. configCon.appendChild(configTable);
  6159. function createCheckbox(innerText, val, tag, parentCheck, otherType, alwaysShow) {
  6160. if (typeof val == 'undefined') val = "";
  6161. let title = document.createElement(tag || "h3");
  6162. title.innerHTML = innerText;
  6163. title.style.overflowWrap = "normal";
  6164. let input = document.createElement("input");
  6165. if (otherType === 'key') {
  6166. input.type = 'text';
  6167. input.setAttribute('readOnly', 'readonly');
  6168. input.addEventListener("keydown", e => {
  6169. if (e.key === 'Escape' || e.key === 'Backspace') input.value = '';
  6170. else input.value = e.key;
  6171. e.stopPropagation();
  6172. e.preventDefault();
  6173. });
  6174. } else {
  6175. input.type = otherType || "checkbox";
  6176. }
  6177. input.style.width = "35px";
  6178. input.style.height = "20px";
  6179. input.style.float = "left";
  6180. input.style.margin = "0 2px";
  6181. input.value = val;
  6182. input.checked = val;
  6183. let td = document.createElement("td");
  6184. td.appendChild(input);
  6185. if (parentCheck) {
  6186. title.appendChild(input);
  6187. title.style.margin = "0";
  6188. td.appendChild(title);
  6189. let parent = parentCheck.parentNode.nextElementSibling;
  6190. let tr = parent.querySelector("tr");
  6191. if (!tr) {
  6192. tr = document.createElement("tr");
  6193. parent.appendChild(tr);
  6194. }
  6195. tr.appendChild(td);
  6196. if (!alwaysShow) {
  6197. if (!parentCheck.checked) {
  6198. td.style.display = "none";
  6199. }
  6200. parentCheck.addEventListener("click", e => {
  6201. td.style.display = parentCheck.checked ? "" : "none";
  6202. });
  6203. }
  6204. } else {
  6205. let tr = document.createElement("tr");
  6206. tr.appendChild(td);
  6207. td = document.createElement("td");
  6208. td.appendChild(title);
  6209. tr.appendChild(td);
  6210. configTable.children[0].appendChild(tr);
  6211. }
  6212. let xNodePos = innerText.indexOf('【X】');
  6213. if (xNodePos !== -1) {
  6214. input.style.float = "";
  6215. let xNode = title.firstChild.splitText(xNodePos);
  6216. xNode.splitText(3);
  6217. xNode.parentNode.replaceChild(input, xNode);
  6218. }
  6219. return input;
  6220. }
  6221.  
  6222. let setConfigPageInput = createCheckbox(i18n("setConfigPage"), false);
  6223. let enableWhiteListInput = createCheckbox(i18n("autoRun"), rulesData.enableWhiteList != true);
  6224. let sideControllerInput = createCheckbox(i18n("sideController"), rulesData.sideController);
  6225. let sideControllerAlwaysInput = createCheckbox(i18n("sideControllerAlways"), rulesData.sideControllerAlways, "h4", sideControllerInput);
  6226. let sideControllerScrollInput = createCheckbox(i18n("sideControllerScroll"), rulesData.sideControllerScroll !== false, "h4", sideControllerInput);
  6227. let sideControllerLoadNowInput = createCheckbox(i18n("loadNow"), rulesData.sideControllerLoadNow !== false, "h4", sideControllerInput);
  6228. let enableDebugInput = createCheckbox(i18n("enableDebug"), rulesData.enableDebug != false);
  6229. let enableHistoryInput = createCheckbox(i18n("enableHistory"), rulesData.enableHistory === true);
  6230. let enableHistoryAfterInsertInput = createCheckbox(i18n("enableHistoryAfterInsert"), rulesData.enableHistoryAfterInsert === true, "h4", enableHistoryInput);
  6231. let openInNewTabInput = createCheckbox(i18n("openInNewTab"), rulesData.openInNewTab != false);
  6232. let hidePageBarInput = createCheckbox(i18n("hideBarTips"), rulesData.opacity == 0);
  6233. let hidePageBarArrowInput = createCheckbox(i18n("hideBarArrow"), rulesData.hideBarArrow);
  6234. let hideLoadingIconInput = createCheckbox(i18n("hideLoadingIcon"), rulesData.hideLoadingIcon != false);
  6235. let initRunInput = createCheckbox(i18n("initRun"), rulesData.initRun != false);
  6236. let autoLoadNumInput = createCheckbox(i18n("autoLoadNum"), rulesData.autoLoadNum, "h4", initRunInput, "number");
  6237. let preloadInput = createCheckbox(i18n("preload"), rulesData.preload != false);
  6238. let rateInput = createCheckbox(i18n("turnRate"), rulesData.rate, "h4", preloadInput, "number", true);
  6239. let dbClick2StopInput = createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  6240. let manualModeInput = createCheckbox(i18n("manualMode"), rulesData.manualMode);
  6241. let clickModeInput = createCheckbox(i18n("clickMode"), rulesData.clickMode);
  6242. let pageBarMenuInput = createCheckbox(i18n("pageBarMenu"), rulesData.pageBarMenu != false);
  6243. let arrowToScrollInput = createCheckbox(i18n("arrowToScroll"), rulesData.arrowToScroll);
  6244. let contentVisibilityInput = createCheckbox(i18n("contentVisibility"), rulesData.contentVisibility);
  6245. let wedata2githubInput = createCheckbox(i18n("wedata2github"), rulesData.wedata2github);
  6246. let customFirstInput = createCheckbox(i18n("customFirst"), rulesData.customFirst);
  6247. let lastPageTipsInput = createCheckbox(i18n("lastPageTips"), rulesData.lastPageTips);
  6248. let updateNotificationInput = createCheckbox(i18n("updateNotification"), rulesData.updateNotification != false);
  6249.  
  6250. let hideBarInput = createCheckbox(i18n("hideBar"), rulesData.hideBar && !rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  6251. hideBarInput.name = 'hideBar';
  6252. let hideBarButNoStopInput = createCheckbox(i18n("hideBarButNoStop"), rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  6253. hideBarButNoStopInput.name = 'hideBar';
  6254. hideBarInput.addEventListener('mouseup', e => {
  6255. if (hideBarInput.checked) {
  6256. setTimeout(() => {hideBarInput.checked = false}, 0);
  6257. }
  6258. });
  6259. hideBarButNoStopInput.addEventListener('mouseup', e => {
  6260. if (hideBarButNoStopInput.checked) {
  6261. setTimeout(() => {hideBarButNoStopInput.checked = false}, 0);
  6262. }
  6263. });
  6264. hidePageBarInput.addEventListener('click', e => {
  6265. opacityInput.value = hidePageBarInput.checked ? 0 : 100;
  6266. });
  6267.  
  6268. let dbClick2StopCtrlInput = createCheckbox(i18n("dbClick2StopCtrl"), rulesData.dbClick2StopCtrl, "h4", dbClick2StopInput);
  6269. let dbClick2StopAltInput = createCheckbox(i18n("dbClick2StopAlt"), rulesData.dbClick2StopAlt, "h4", dbClick2StopInput);
  6270. let dbClick2StopShiftInput = createCheckbox(i18n("dbClick2StopShift"), rulesData.dbClick2StopShift, "h4", dbClick2StopInput);
  6271. let dbClick2StopMetaInput = createCheckbox(i18n("dbClick2StopMeta"), rulesData.dbClick2StopMeta, "h4", dbClick2StopInput);
  6272. let dbClick2StopKeyInput = createCheckbox(i18n("dbClick2StopKey"), rulesData.dbClick2StopKey, "h4", dbClick2StopInput, "key");
  6273.  
  6274. let otherConfigPage = (rulesData.configPage || configPage[0]) != location.href.replace(/#.*/, "");
  6275. if (!otherConfigPage) {
  6276. setConfigPageInput.parentNode.parentNode.style.display = "none";
  6277. }
  6278.  
  6279. updateP.onclick = e => {
  6280. updateFail = false;
  6281. //ruleParser.rules = [];
  6282. showTips(i18n("beginUpdate"), "", 30000);
  6283. updateRules(() => {
  6284. if (!updateFail) {
  6285. showTips(i18n("updateSucc"));
  6286. if (importUrlPres) {
  6287. [].forEach.call(importUrlPres, importUrlPre => {
  6288. importUrlPre.style.display = "none";
  6289. });
  6290. }
  6291. if (click2import) click2import.style.display = "none";
  6292. }
  6293. updateP.innerHTML = i18n("passSec", 0);
  6294. updateP.title = i18n("update");
  6295. rulebarList.forEach(rulebar => {
  6296. rulebar.updateNum();
  6297. });
  6298. }, (rule, err) => {
  6299. if (rule.id == 1) {
  6300. showTips(`Failed to update wedata rules! Try to switch to wedata mirror!`);
  6301. wedata2githubInput.scrollIntoView({ behavior: "smooth" });
  6302. } else {
  6303. showTips(`Failed to update ${rule.url} rules!`);
  6304. }
  6305. debug(err);
  6306. updateFail = true;
  6307. });
  6308. };
  6309. let customRulesTitle = document.createElement("h2");
  6310. 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');
  6311. configCon.appendChild(customRulesTitle);
  6312. customRulesInput = document.createElement("textarea");
  6313. customRulesInput.spellcheck = false;
  6314. configCon.appendChild(customRulesInput);
  6315. if (rulesData.editTemp) {
  6316. if (!ruleParser.customRules) {
  6317. ruleParser.customRules = [];
  6318. }
  6319. for (let i in ruleParser.customRules) {
  6320. if (ruleParser.customRules[i].url == rulesData.editTemp.url) {
  6321. ruleParser.customRules.splice(i, 1);
  6322. break;
  6323. }
  6324. }
  6325. ruleParser.customRules.unshift(rulesData.editTemp);
  6326. rulesData.editTemp = null;
  6327. storage.setItem("rulesData", rulesData);
  6328. customRulesInput.previousElementSibling.scrollIntoView();
  6329. }
  6330. customRulesInput.style.width = "100%";
  6331. customRulesInput.style.height = "800px";
  6332. 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]`;
  6333. let preCustom = getFormatJSON(ruleParser.customRules);
  6334. customRulesInput.value = preCustom;
  6335. if (isGuidePage) customRulesInput.style.display = "none";
  6336. let blacklistInput = document.createElement("textarea");
  6337. blacklistInput.style.width = "100%";
  6338. blacklistInput.style.height = "500px";
  6339. blacklistInput.style.display = "none";
  6340. blacklistInput.spellcheck = false;
  6341. 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";
  6342. blacklistInput.value = rulesData.blacklist ? rulesData.blacklist.join("\n") : "";
  6343. let blacklistBtn = document.createElement("button");
  6344. blacklistBtn.innerText = i18n("editBlacklist");
  6345. blacklistBtn.style.width = "100%";
  6346. blacklistBtn.onclick = e => {
  6347. blacklistInput.style.display = blacklistInput.style.display == "none" ? "" : "none";
  6348. };
  6349. configCon.appendChild(blacklistBtn);
  6350. configCon.appendChild(blacklistInput);
  6351. let saveBtn = document.createElement("button");
  6352. saveBtn.innerHTML = i18n("save");
  6353. saveBtn.id = "saveBtn";
  6354. configCon.appendChild(saveBtn);
  6355. saveBtn.onclick = e => {
  6356. try {
  6357. let customRules;
  6358. if (editor) {
  6359. if (editorChanged) {
  6360. editorChanged = false;
  6361. storage.setItem("hpRules", []);
  6362. storage.setItem("smartRules", []);
  6363. }
  6364. customRules = editor.get();
  6365. if (!customRules) {
  6366. customRules = "";
  6367. } else {
  6368. if (Array && Array.isArray && !Array.isArray(customRules)) {
  6369. showTips(i18n("errorRulesMustBeArray"));
  6370. return;
  6371. }
  6372. }
  6373. } else {
  6374. if (customRulesInput.value != preCustom) {
  6375. storage.setItem("hpRules", []);
  6376. storage.setItem("smartRules", []);
  6377. }
  6378. if (customRulesInput.value == "") {
  6379. customRules = "";
  6380. } else {
  6381. customRules = JSON.parse(customRulesInput.value);
  6382. if (Array && Array.isArray && !Array.isArray(customRules)) {
  6383. showTips(i18n("errorRulesMustBeArray"));
  6384. return;
  6385. }
  6386. customRulesInput.value = JSON.stringify(customRules, null, 4);
  6387. }
  6388. }
  6389. debug(customRules);
  6390. storage.setItem("customRules", customRules);
  6391. } catch(e) {
  6392. debug(e);
  6393. let pos = e && e.message && e.message.match(/position (\d+)/);
  6394. if (pos && !editor) {
  6395. pos = parseInt(pos[1]);
  6396. customRulesInput.value = customRulesInput.value.slice(0, pos) + "➡️" + customRulesInput.value.slice(pos);
  6397. }
  6398. showTips(i18n("errorJson"));
  6399. return;
  6400. }
  6401. rulesData.lang = langSelect.value || "";
  6402. if (setConfigPageInput.checked) rulesData.configPage = location.href;
  6403. rulesData.wedata2github = wedata2githubInput.checked;
  6404. let opacity = parseInt(opacityInput.value) || 0;
  6405. if (opacity > 100) opacity = 100;
  6406. else if (opacity < 0) opacity = 0;
  6407. rulesData.opacity = opacity / 100;
  6408. rulesData.blacklist = blacklistInput.value ? blacklistInput.value.trim().split("\n") : "";
  6409. rulesData.hideBar = hideBarInput.checked;
  6410. rulesData.hideBarButNoStop = hideBarButNoStopInput.checked;
  6411. rulesData.dbClick2Stop = dbClick2StopInput.checked;
  6412. rulesData.enableWhiteList = !enableWhiteListInput.checked;
  6413. rulesData.enableDebug = enableDebugInput.checked;
  6414. rulesData.updateNotification = updateNotificationInput.checked;
  6415. rulesData.enableHistory = enableHistoryInput.checked;
  6416. rulesData.enableHistoryAfterInsert = enableHistoryAfterInsertInput.checked;
  6417. rulesData.openInNewTab = openInNewTabInput.checked;
  6418. rulesData.hideLoadingIcon = hideLoadingIconInput.checked;
  6419. rulesData.hideBarArrow = hidePageBarArrowInput.checked;
  6420. rulesData.customFirst = customFirstInput.checked;
  6421. rulesData.lastPageTips = lastPageTipsInput.checked;
  6422. rulesData.initRun = initRunInput.checked;
  6423. rulesData.autoLoadNum = autoLoadNumInput.value !== "0" ? autoLoadNumInput.value : '';
  6424. rulesData.rate = parseFloat(rateInput.value) || 0;
  6425. rulesData.preload = preloadInput.checked;
  6426. rulesData.manualMode = manualModeInput.checked;
  6427. rulesData.clickMode = clickModeInput.checked;
  6428. rulesData.pageBarMenu = pageBarMenuInput.checked;
  6429. rulesData.arrowToScroll = arrowToScrollInput.checked;
  6430. rulesData.contentVisibility = contentVisibilityInput.checked;
  6431. if (rulesData.sideController != sideControllerInput.checked) {
  6432. rulesData.sideControllerPos = false;
  6433. }
  6434. rulesData.sideController = sideControllerInput.checked;
  6435. rulesData.sideControllerScroll = sideControllerScrollInput.checked;
  6436. rulesData.sideControllerLoadNow = sideControllerLoadNowInput.checked;
  6437. rulesData.sideControllerAlways = sideControllerAlwaysInput.checked;
  6438. rulesData.pageElementCss = pageElementCssInput.value;
  6439. rulesData.customCss = customCssInput.value;
  6440. rulesData.upBtnImg = upBtnImgInput.value;
  6441. rulesData.downBtnImg = downBtnImgInput.value;
  6442. rulesData.sideControllerIcon = sideControllerIconInput.value;
  6443. rulesData.loadingText = loadingTextInput.value;
  6444. rulesData.dbClick2StopCtrl = dbClick2StopCtrlInput.checked;
  6445. rulesData.dbClick2StopAlt = dbClick2StopAltInput.checked;
  6446. rulesData.dbClick2StopShift = dbClick2StopShiftInput.checked;
  6447. rulesData.dbClick2StopMeta = dbClick2StopMetaInput.checked;
  6448. rulesData.dbClick2StopKey = dbClick2StopKeyInput.value;
  6449. storage.setItem("rulesData", rulesData);
  6450. let customUrls = customUrlsInput.value.trim(), urlImported = false;
  6451. if (customUrls) {
  6452. customUrls = customUrls.split(/\n/);
  6453. for (let c = 0; c < customUrls.length; c++) {
  6454. let url;
  6455. if (/^0\s*\|/.test(customUrls[c])) {
  6456. url = customUrls[c].replace(/^0\s*\|\s*/, "").trim();
  6457. if (!/^http/.test(url)) {
  6458. showTips(i18n("errorWrongUrl"));
  6459. return;
  6460. }
  6461. } else {
  6462. url = customUrls[c].trim();
  6463. if (!/^http/.test(url)) {
  6464. showTips(i18n("errorWrongUrl"));
  6465. return;
  6466. }
  6467. }
  6468. let maxId = 1, hasUrl = false;
  6469. if (!rulesData.urls) {
  6470. rulesData.urls = [];
  6471. }
  6472. ruleUrls.forEach(u => {
  6473. if (maxId < u.id) {
  6474. maxId = u.id;
  6475. }
  6476. if (u.url == url) {
  6477. hasUrl = true;
  6478. }
  6479. });
  6480. if (hasUrl) break;
  6481. if (!rulesData.sort) rulesData.sort = [1];
  6482. let newRule = {id: maxId + 1, url: url};
  6483. ruleUrls.push(newRule);
  6484. rulesData.urls.push(newRule);
  6485. rulesData.sort.push(maxId + 1);
  6486. storage.setItem("rulesData", rulesData);
  6487. let rulebar = new Rulebar();
  6488. rulebar.init(newRule);
  6489. rulebarList.push(rulebar);
  6490. }
  6491. }
  6492. showTips(i18n("settingsSaved"));
  6493. };
  6494. return true;
  6495. }
  6496.  
  6497. function updateRules (success, fail, keepCache) {
  6498. if (!storage.supportCrossSave()) {
  6499. fail({url:''}, "Not support cross storage");
  6500. showTips("Current platform do not support cross storage!");
  6501. return;
  6502. }
  6503. if (inUpdate) return;
  6504. inUpdate = true;
  6505. let ruleIndex = ruleUrls.length - 1;
  6506. if (!keepCache) {
  6507. storage.setItem("hpRules", []);
  6508. storage.setItem("smartRules", []);
  6509. }
  6510. let allOk = true;
  6511. let preLength = ruleParser.rules.length;
  6512. let fetchVersion = -1;
  6513. async function needUpdate(url, id) {
  6514. if (!/^https:\/\/hoothin\.github\.io\/|\/hoothin\/UserScripts\/.*\/Pagetual\/pagetualRules\.json/i.test(url)) {
  6515. return true;
  6516. }
  6517. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == id ? 1 : 0), 0);
  6518. if (rulesLength === 0) return true;
  6519. if (fetchVersion >= 0) {
  6520. return fetchVersion > (rulesData.ruleVersion || 0);
  6521. }
  6522. fetchVersion = await new Promise(resolve => {
  6523. _GM_xmlhttpRequest({
  6524. url: url.replace(/\/\w+\.json/i, "/version"),
  6525. method: 'GET',
  6526. timeout: 20000,
  6527. headers: {
  6528. 'accept': 'application/json,text/html'
  6529. },
  6530. onload: function(res) {
  6531. let version = parseInt(res.response || res.responseText);
  6532. resolve(version || -1);
  6533. },
  6534. onerror: function(e) {
  6535. resolve(-1);
  6536. },
  6537. ontimeout: function(e) {
  6538. resolve(-1);
  6539. }
  6540. });
  6541. });
  6542. return fetchVersion > (rulesData.ruleVersion || 0);
  6543. }
  6544. async function addNextRule() {
  6545. if (ruleIndex < 0) {
  6546. let now = new Date().getTime();
  6547. storage.setItem("ruleLastUpdate", now);
  6548. storage.setItem("rules", ruleParser.rules);
  6549. let curLength = ruleParser.rules.length;
  6550. if (curLength !== preLength && rulesData.updateNotification) {
  6551. _GM_notification({
  6552. text: `Rules has updated( ${preLength} => ${curLength} )`,
  6553. title: "Pagetual rules updated",
  6554. onclick: (event) => {
  6555. event.preventDefault();
  6556. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  6557. }
  6558. });
  6559. }
  6560. inUpdate = false;
  6561. let rulesDataChanged = false;
  6562. if (fetchVersion >= 0 && rulesData.ruleVersion !== fetchVersion) {
  6563. rulesData.ruleVersion = fetchVersion;
  6564. rulesDataChanged = true;
  6565. }
  6566. if (rulesData.uninited && allOk && ruleUrls.length > 1) {
  6567. rulesData.uninited = false;
  6568. rulesDataChanged = true;
  6569. }
  6570. if (rulesDataChanged) {
  6571. storage.setItem("rulesData", rulesData);
  6572. }
  6573. success();
  6574. } else {
  6575. let rule = ruleUrls[ruleIndex--];
  6576. if (await needUpdate(rule.url, rule.id)) {
  6577. ruleParser.addRuleByUrl(rule.url, rule.id, (json, err) => {
  6578. if (!json) {
  6579. allOk = false;
  6580. fail(rule, err);
  6581. }
  6582. addNextRule();
  6583. });
  6584. } else {
  6585. addNextRule();
  6586. }
  6587. }
  6588. }
  6589. addNextRule();
  6590. }
  6591.  
  6592. function objIsArr(obj) {
  6593. return obj &&
  6594. typeof obj === 'object' &&
  6595. typeof obj.length === 'number' &&
  6596. !(obj.propertyIsEnumerable('length'));
  6597. }
  6598.  
  6599. function isVisible(el, win) {
  6600. if(!el || !el.offsetParent)return false;
  6601. var loopable = true,
  6602. visible = el.nodeName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  6603. while(loopable && visible) {
  6604. el = el.parentNode;
  6605.  
  6606. if(el && !compareNodeName(el, ["body"])) {
  6607. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  6608. }else {
  6609. loopable = false;
  6610. }
  6611. }
  6612. return visible;
  6613. }
  6614.  
  6615. function getElementTop(ele) {
  6616. if (!ele) return 0;
  6617. if (ele.getBoundingClientRect) {
  6618. return ele.getBoundingClientRect().top + document.documentElement.scrollTop;
  6619. }
  6620. var actualTop = ele.offsetTop;
  6621. var current = ele.offsetParent;
  6622. while (current) {
  6623. actualTop += current.offsetTop;
  6624. current = current.offsetParent;
  6625. }
  6626. return actualTop;
  6627. }
  6628.  
  6629. function getElementLeft(ele) {
  6630. if (!ele) return 0;
  6631. if (ele.getBoundingClientRect) {
  6632. return ele.getBoundingClientRect().left + document.documentElement.scrollLeft;
  6633. }
  6634. var actualLeft = ele.offsetLeft;
  6635. var current = ele.offsetParent;
  6636. while (current) {
  6637. actualLeft += current.offsetLeft;
  6638. current = current.offsetParent;
  6639. }
  6640. return actualLeft;
  6641. }
  6642.  
  6643. function getElementBottom(ele) {
  6644. return getElementTop(ele) + (ele.offsetHeight || ele.scrollHeight);
  6645. }
  6646.  
  6647. function getFormatJSON(obj){
  6648. if(!objIsArr(obj) || obj.length === 0)return "";
  6649. return JSON.stringify(obj, null, 4);
  6650. }
  6651.  
  6652. function globMatch(first, second) {
  6653. if (first === '*') {
  6654. return true;
  6655. }
  6656. if (first.length == 0 && second.length == 0){
  6657. return true;
  6658. }
  6659.  
  6660. if (first.length > 1 && first[0] == '*' &&
  6661. second.length == 0){
  6662. return false;
  6663. }
  6664.  
  6665. if ((first.length > 1 && first[0] == '?') ||
  6666. (first.length != 0 && second.length != 0 &&
  6667. first[0] == second[0])){
  6668. return globMatch(first.substring(1),
  6669. second.substring(1));
  6670. }
  6671.  
  6672. if (first.length > 0 && first[0] == '*'){
  6673. return globMatch(first.substring(1), second) ||
  6674. globMatch(first, second.substring(1));
  6675. }
  6676.  
  6677. return false;
  6678. }
  6679.  
  6680. let pageReady = false;
  6681. function initRules(callback) {
  6682. charset = (document.characterSet || document.charset || document.inputEncoding);
  6683. let equiv = document.querySelector('[http-equiv="Content-Type"]');
  6684. if (equiv && equiv.content) {
  6685. let innerCharSet = equiv.content.match(/charset\=([^;]+)/);
  6686. if (!innerCharSet) {
  6687. charsetValid = false;
  6688. } else if (innerCharSet[1].replace("-", "").toLowerCase() != charset.replace("-", "").toLowerCase()) {
  6689. charsetValid = false;
  6690. }
  6691. } else charsetValid = false;
  6692. storage.getItem("rulesData", data => {
  6693. /*0 wedata格式,1 pagetual格式*/
  6694. ruleUrls = [{
  6695. id: 1,
  6696. url: data && data.wedata2github ? 'https://hoothin.github.io/UserScripts/Pagetual/items_all.json' : 'http://wedata.net/databases/AutoPagerize/items_all.json',
  6697. type: 0,
  6698. }];
  6699. if (data) {
  6700. rulesData = data;
  6701. if (data.urls) ruleUrls = ruleUrls.concat(data.urls);
  6702. if (data.sort) {
  6703. let urls = [];
  6704. data.sort.forEach(id => {
  6705. for (let s = 0; s < ruleUrls.length; s++) {
  6706. if (id == ruleUrls[s].id) {
  6707. urls.push(ruleUrls[s]);
  6708. break;
  6709. }
  6710. }
  6711. });
  6712. ruleUrls = urls;
  6713. }
  6714. }
  6715. if (rulesData.lang) {
  6716. setLang(rulesData.lang);
  6717. }
  6718. if (rulesData.firstRun) {
  6719. rulesData.firstRun = false;
  6720. storage.setItem("rulesData", rulesData);
  6721. setTimeout(() => {
  6722. storage.getItem("rulesData", data => {
  6723. if (data.firstRun === false) {
  6724. _GM_openInTab(firstRunPage, {active: lang !== 'zh-CN'});
  6725. }
  6726. });
  6727. }, 100);
  6728. }
  6729. _GM_registerMenuCommand(i18n("configure"), () => {
  6730. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  6731. });
  6732. if (rulesData.blacklist && rulesData.blacklist.length > 0) {
  6733. let href = location.href.slice(0, 500);
  6734. let commentStart = false;
  6735. for (let i = 0; i < rulesData.blacklist.length; i++) {
  6736. let curGlob = rulesData.blacklist[i];
  6737. if (!curGlob) continue;
  6738. if (curGlob.indexOf("//") == 0) continue;
  6739. if (commentStart) {
  6740. if (/\*\/$/.test(curGlob)) {
  6741. commentStart = false;
  6742. }
  6743. continue;
  6744. }
  6745. if (curGlob.indexOf("/*") == 0) {
  6746. commentStart = true;
  6747. continue;
  6748. }
  6749. if (curGlob.indexOf("/") == 0) {
  6750. let regMatch = curGlob.match(/^\/(.*)\/(\w*)$/);
  6751. if (regMatch && new RegExp(regMatch[1], regMatch[2]).test(href)) {
  6752. forceState == 1;
  6753. return;
  6754. }
  6755. } else if (globMatch(curGlob, href)) {
  6756. forceState == 1;
  6757. return;
  6758. }
  6759. }
  6760. }
  6761. _GM_registerMenuCommand(i18n("editCurrent"), () => {
  6762. picker.start();
  6763. });
  6764. ruleParser.initSavedRules(async () => {
  6765. let upBtnImg = rulesData.upBtnImg, downBtnImg = rulesData.downBtnImg, _sideControllerIcon = rulesData.sideControllerIcon;
  6766. if (upBtnImg && downBtnImg) {
  6767. downSvgCSS = downSvgCSS.replace("transform: rotate(180deg);", "");
  6768. } else if (upBtnImg && !downBtnImg) {
  6769. downBtnImg = upBtnImg;
  6770. } else if(downBtnImg && !upBtnImg) {
  6771. upBtnImg = downBtnImg;
  6772. }
  6773. if (upBtnImg) {
  6774. upSvg = /https?:|data/.test(upBtnImg) ? `<img class="pagetual" src="${upBtnImg}"/>` : `<span>${upBtnImg}</span>`;
  6775. }
  6776. if (downBtnImg) {
  6777. downSvg = /https?:|data/.test(downBtnImg) ? `<img class="pagetual" src="${downBtnImg}"/>` : `<span>${downBtnImg}</span>`;
  6778. }
  6779. if (_sideControllerIcon) {
  6780. sideControllerIcon = /https?:|data/.test(_sideControllerIcon) ? `<img class="pagetual" src="${_sideControllerIcon}"/>` : `<span>${_sideControllerIcon}</span>`;
  6781. }
  6782. setLoadingDiv(rulesData.loadingText || i18n("loadingText"));
  6783. if (typeof(rulesData.opacity) == "undefined") {
  6784. rulesData.opacity = 1;
  6785. }
  6786. if (typeof(rulesData.hideBar) == "undefined") {
  6787. rulesData.hideBar = false;
  6788. }
  6789. if (typeof(rulesData.dbClick2Stop) == "undefined") {
  6790. rulesData.dbClick2Stop = true;
  6791. }
  6792. if (typeof(rulesData.enableWhiteList) == "undefined") {
  6793. rulesData.enableWhiteList = false;
  6794. }
  6795. if (typeof(rulesData.enableHistory) == "undefined") {
  6796. rulesData.enableHistory = false;
  6797. }
  6798. if (typeof(rulesData.openInNewTab) == "undefined") {
  6799. rulesData.openInNewTab = false;
  6800. }
  6801. if (typeof(rulesData.enableDebug) == "undefined") {
  6802. rulesData.enableDebug = true;
  6803. }
  6804. if (typeof(rulesData.updateNotification) == "undefined") {
  6805. rulesData.updateNotification = true;
  6806. }
  6807. if (typeof(rulesData.initRun) == "undefined") {
  6808. rulesData.initRun = true;
  6809. }
  6810. if (typeof(rulesData.preload) == "undefined") {
  6811. rulesData.preload = true;
  6812. }
  6813. if (typeof(rulesData.customFirst) == "undefined") {
  6814. rulesData.customFirst = false;
  6815. }
  6816. if (typeof(rulesData.manualMode) == "undefined") {
  6817. rulesData.manualMode = false;
  6818. }
  6819. if (typeof(rulesData.clickMode) == "undefined") {
  6820. rulesData.clickMode = false;
  6821. }
  6822. if (typeof(rulesData.pageBarMenu) == "undefined") {
  6823. rulesData.pageBarMenu = true;
  6824. }
  6825. if (typeof(rulesData.arrowToScroll) == "undefined") {
  6826. rulesData.arrowToScroll = false;
  6827. }
  6828. if (typeof(rulesData.hideLoadingIcon) == "undefined") {
  6829. rulesData.hideLoadingIcon = false;
  6830. }
  6831. if (typeof(rulesData.hideBarArrow) == "undefined") {
  6832. rulesData.hideBarArrow = false;
  6833. }
  6834. if (typeof(rulesData.lastPageTips) == "undefined") {
  6835. rulesData.lastPageTips = true;
  6836. }
  6837. if (typeof(rulesData.rate) == "undefined") {
  6838. rulesData.rate = 1;
  6839. }
  6840. rate = rulesData.rate;
  6841. if (rulesData.autoLoadNum && rulesData.initRun) {
  6842. autoLoadNum = parseInt(rulesData.autoLoadNum);
  6843. }
  6844. openInNewTab = rulesData.openInNewTab ? 1 : 0;
  6845. enableDebug = rulesData.enableDebug;
  6846.  
  6847. let _nextSwitch = await getListData("nextSwitch", location.host);
  6848. if (typeof(_nextSwitch) !== "undefined") {
  6849. nextIndex = _nextSwitch || 0;
  6850. }
  6851.  
  6852. let _forceState = await getListData("forceState", location.host);
  6853. if (typeof(_forceState) == "undefined") {
  6854. _forceState = await getData("forceState_" + location.host);
  6855. }
  6856. if (typeof(_forceState) == "undefined") {
  6857. _forceState = (rulesData.enableWhiteList ? 1 : 0);
  6858. }
  6859. forceState = _forceState;
  6860.  
  6861. autoScroll = await getListData("autoScroll", location.host + location.pathname) || 0;
  6862.  
  6863. updateDate = await getData("ruleLastUpdate");
  6864.  
  6865. let _loadNowNum = await getData("loadNowNum");
  6866. if (typeof(_loadNowNum) != "undefined") {
  6867. loadNowNum = _loadNowNum;
  6868. }
  6869. let _autoScrollRate = await getData("autoScrollRate");
  6870. if (_autoScrollRate) {
  6871. autoScrollRate = _autoScrollRate;
  6872. }
  6873.  
  6874. author = await getData("author") || "";
  6875.  
  6876. manualPause = !!await getListData("pauseState", location.host);
  6877.  
  6878. let href = location.href.slice(0, 100);
  6879. try {
  6880. if (_unsafeWindow.initedPagetual) {
  6881. if (ruleImportUrlReg.test(href)) {
  6882. showTips(i18n('duplicate'));
  6883. }
  6884. return;
  6885. }
  6886. _unsafeWindow.initedPagetual = true;
  6887. } catch(e) {showTips(e)}
  6888. listenUrl();
  6889. _GM_registerMenuCommand(i18n("update"), () => {
  6890. showTips(i18n("beginUpdate"), "", 60000);
  6891. updateRules(() => {
  6892. showTips(i18n("updateSucc"));
  6893. location.reload();
  6894. },(rule, err) => {
  6895. showTips(`Failed to update ${rule.url} rules!`);
  6896. debug(err);
  6897. });
  6898. });
  6899. _GM_registerMenuCommand(i18n(forceState == 1 ? "enable" : "disableSite"), () => {
  6900. if (forceState == 1) {
  6901. forceState = 0;
  6902. showTips(i18n("enableSiteTips"));
  6903. changeStop(false, true);
  6904. } else {
  6905. forceState = 1;
  6906. showTips(i18n("disableSiteTips"));
  6907. changeStop(true, true);
  6908. sideController.remove();
  6909. }
  6910. setListData("forceState", location.host, forceState);
  6911. if (!ruleParser.curSiteRule.url) {
  6912. setTimeout(() => {
  6913. location.reload();
  6914. }, 500);
  6915. }
  6916. });
  6917. _GM_registerMenuCommand(i18n("toggleAutoScroll"), () => {
  6918. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  6919. autoScroll = parseInt(autoScroll) || 0;
  6920. if (autoScroll < 0) autoScroll = 0;
  6921. if (autoScroll && autoScroll != autoScrollRate) {
  6922. autoScrollRate = autoScroll;
  6923. storage.setItem("autoScrollRate", autoScrollRate);
  6924. }
  6925. setListData("autoScroll", location.host + location.pathname, autoScroll);
  6926. startAutoScroll();
  6927. });
  6928. startAutoScroll();
  6929.  
  6930.  
  6931. if (initConfig(href)) {
  6932. document.addEventListener("click", e => {
  6933. if (e.target && typeof e.target.dataset.pagetualPicker !== 'undefined') {
  6934. e.preventDefault();
  6935. e.stopPropagation();
  6936. picker.start();
  6937. }
  6938. });
  6939. return;
  6940. }
  6941. pageReady = true;
  6942. if (forceState == 1) return;
  6943. let now = new Date().getTime();
  6944. if (!updateDate || now - updateDate > 2 * 24 * 60 * 60 * 1000) {
  6945. updateRules(() => {
  6946. }, (rule, err) => {}, true);
  6947. storage.setItem("ruleLastUpdate", now);
  6948. }
  6949. callback();
  6950. });
  6951. });
  6952. }
  6953.  
  6954. let xhrFailed = false;
  6955. function requestDoc(url, callback) {
  6956. let postParams = url.match(/#p{(.*)}$/);
  6957. if (postParams) {
  6958. postParams = postParams[1];
  6959. url = url.replace(/#p{.*/, "");
  6960. }
  6961. let ruleHeaders = ruleParser.curSiteRule.headers;
  6962. let headers = {
  6963. 'Referer': location.href,
  6964. 'User-Agent': navigator.userAgent,
  6965. 'accept': 'text/html,application/xhtml+xml,application/xml',
  6966. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + charset,
  6967. };
  6968. if (ruleHeaders) {
  6969. if (ruleHeaders.referer) {
  6970. headers.referer = ruleHeaders.referer;
  6971. }
  6972. if (ruleHeaders.userAgent) {
  6973. headers.userAgent = ruleHeaders.userAgent;
  6974. }
  6975. if (ruleHeaders.accept) {
  6976. headers.accept = ruleHeaders.accept;
  6977. }
  6978. if (ruleHeaders.contentType) {
  6979. headers.contentType = ruleHeaders.contentType;
  6980. let ruleCharset = ruleHeaders.contentType.match(/charset\=([^;]+)/);
  6981. if (ruleCharset) charset = ruleCharset[1];
  6982. }
  6983. if (ruleHeaders.cookie) {
  6984. headers.cookie = ruleHeaders.cookie;
  6985. }
  6986. }
  6987. _GM_xmlhttpRequest({
  6988. url: url,
  6989. method: postParams ? 'POST' : 'GET',
  6990. data: postParams,
  6991. overrideMimeType: 'text/html;charset=' + charset,
  6992. headers: headers,
  6993. timeout: 50000,
  6994. onload: async function(res) {
  6995. if (isPause) return callback(false);
  6996. var doc = null, response = res.response;
  6997. try {
  6998. doc = document.implementation.createHTMLDocument('');
  6999. doc.documentElement.innerHTML = response;
  7000. } catch (e) {
  7001. debug('parse error:' + e.toString());
  7002. }
  7003. let pageElement = null;
  7004. let preCode = ruleParser.curSiteRule.pagePre;
  7005. if (preCode) {
  7006. try {
  7007. let preResult;
  7008. if (typeof preCode == 'function') {
  7009. preResult = await preCode(response, doc);
  7010. } else if (preCode.length == 2) {
  7011. preResult = response.replace(new RegExp(preCode[0], "gi"), preCode[1]);
  7012. } else {
  7013. preResult = await new AsyncFunction("response", "doc", '"use strict";' + preCode)(response, doc);
  7014. }
  7015. if (typeof preResult !== "undefined") {
  7016. if (typeof preResult === "string") {
  7017. doc.documentElement.innerHTML = preResult;
  7018. } else pageElement = preResult;
  7019. }
  7020. } catch(e) {
  7021. debug(e);
  7022. }
  7023. }
  7024. let base = doc.querySelector("base");
  7025. ruleParser.basePath = (base && base.href) || url;
  7026. if (charsetValid && !ruleHeaders) {
  7027. let equiv = doc.querySelector('[http-equiv="Content-Type"]');
  7028. if (equiv && equiv.content) {
  7029. let innerCharSet = equiv.content.match(/charset\=([^;]+)/);
  7030. if (innerCharSet && innerCharSet[1].replace("-", "").toLowerCase() != charset.replace("-", "").toLowerCase()) {
  7031. charset = innerCharSet[1];
  7032. return requestDoc(url, callback);
  7033. }
  7034. }
  7035. }
  7036. if (pageElement === null) {
  7037. pageElement = ruleParser.getPageElement(doc);
  7038. }
  7039. if ((!pageElement || pageElement.length == 0) && res.status >= 400) {
  7040. debug(res.status + " " + url, "Error status");
  7041. if (!ruleParser.curSiteRule.smart || !xhrFailed) {
  7042. xhrFailed = true;
  7043. return callback(false);
  7044. }
  7045. }
  7046. if (inCors && (!pageElement || pageElement.length == 0) && ruleParser.curSiteRule.smart) {
  7047. let article;
  7048. for (let i = 0; i < mainSel.length; i++) {
  7049. article = doc.querySelectorAll(mainSel[i]);
  7050. if (article && article.length === 1) break;
  7051. }
  7052. if (article && article.length == 1) {
  7053. article = article[0];
  7054. ruleParser.curSiteRule.pageElement = article.nodeName.toLowerCase() + (article.id ? "#" + article.id : "") + (article.className ? "." + article.className.replace(/ /g, ".") : "") + ">*";
  7055. pageElement = article.children;
  7056. } else {
  7057. ruleParser.curSiteRule.pageElement = allOfBody;
  7058. pageElement = ruleParser.getPageElement(doc);
  7059. }
  7060. ruleParser.getInsert(true);
  7061. }
  7062. //只有1的話怕不是圖片哦
  7063. if (pageElement && (pageElement.length > 1 || (pageElement.length == 1 && !compareNodeName(pageElement[0], ["img"])))) {
  7064. await ruleParser.insertPage(doc, pageElement, url, callback, false);
  7065. if (ruleParser.curSiteRule.action == 1) {
  7066. isLoading = true;
  7067. requestFromIframe(url, async (doc, eles) => {
  7068. if (eles) {
  7069. await ruleParser.insertPage(doc, eles, url, callback, true);
  7070. } else isLoading = false;
  7071. });
  7072. } else ruleParser.curSiteRule.action = 0;
  7073. } else if ((ruleParser.curSiteRule.smart || curPage == 1) && !inCors) {
  7074. ruleParser.curSiteRule.action = 1;
  7075. requestFromIframe(url, async (doc, eles) => {
  7076. if (eles) {
  7077. await ruleParser.insertPage(doc, eles, url, callback, true);
  7078. } else isLoading = false;
  7079. });
  7080. } else {
  7081. debug("Stop as no page element");
  7082. ruleParser.noValidContent(url);
  7083. changeStop(true);
  7084. callback(false);
  7085. }
  7086. },
  7087. onerror: function(e) {
  7088. debug(e, "NetError");
  7089. callback(false);
  7090. },
  7091. ontimeout: function(e) {
  7092. debug(e, "NetTimeout");
  7093. callback(false);
  7094. }
  7095. });
  7096. }
  7097.  
  7098. function initPage() {
  7099. ruleParser.initPage(() => {
  7100. if (ruleParser.curSiteRule.autoLoadNum) {
  7101. autoLoadNum = ruleParser.curSiteRule.autoLoadNum;
  7102. }
  7103. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  7104. _GM_registerMenuCommand(i18n("nextSwitch"), () => {
  7105. nextSwitch.start();
  7106. });
  7107. }
  7108. if (ruleParser.nextLinkHref) {
  7109. let isJs = ruleParser.hrefIsJs(ruleParser.nextLinkHref);
  7110. if (!isJs) {
  7111. let inForce = (forceState == 2 || forceState == 3);
  7112. _GM_registerMenuCommand(i18n(inForce ? "cancelForceIframe" : "forceIframe"), () => {
  7113. if (inForce) {
  7114. setListData("forceState", location.host, "");
  7115. } else {
  7116. let _state = ruleParser.curSiteRule.action > 0 || confirm(i18n("forceAllBody")) ? 2 : 3;
  7117. setListData("forceState", location.host, _state);
  7118. }
  7119. setTimeout(() => {
  7120. location.reload();
  7121. }, 500);
  7122. });
  7123. }
  7124. _GM_registerMenuCommand(i18n("loadNow"), () => {
  7125. if (autoLoadNum != -1) {
  7126. autoLoadNum = -1;
  7127. return;
  7128. }
  7129. let loadNum = window.prompt(i18n("loadConfirm"), loadNowNum);
  7130. if (loadNum === "" || loadNum === null) return;
  7131. loadNum = Math.abs(parseInt(loadNum)) || 0;
  7132. if (loadNowNum != loadNum) {
  7133. loadNowNum = loadNum;
  7134. storage.setItem("loadNowNum", loadNowNum);
  7135. }
  7136. autoLoadNum = loadNum;
  7137. nextPage();
  7138. });
  7139. }
  7140. initListener();
  7141. });
  7142. }
  7143.  
  7144. var pageBarStyle, mainStyleEle, mainStyleStyle;
  7145. function initView() {
  7146. if (!mainStyleStyle) {
  7147. mainStyleStyle = `
  7148. .pagetual_pageBar{
  7149. -moz-transition:all 0.3s ease-in-out 0s;
  7150. -webkit-transition:all 0.3s ease-in-out 0s;
  7151. transition:all 0.3s ease-in-out 0s;
  7152. font-family: Arial,sans-serif !important;
  7153. text-align: center !important;
  7154. }
  7155. .pagetual_pageBar.stop {
  7156. -webkit-filter: invert(100%);
  7157. filter: invert(100%);
  7158. opacity: 1!important;
  7159. }
  7160. .pagetual_pageBar.hide {
  7161. display: none!important;
  7162. }
  7163. .pagetual-hide {
  7164. display: none!important;
  7165. }
  7166. .pagetual_pageBar:hover {
  7167. opacity: 1!important;
  7168. box-shadow: 0px 0px 10px 0px #000000aa;
  7169. border-radius: 20px;
  7170. background-color: rgb(240 240 240 / 80%);
  7171. border-color: transparent!important;
  7172. }
  7173. .pagetual_pageBar span {
  7174. vertical-align: super;
  7175. }
  7176. .pagetual_pageBar a::before,
  7177. .pagetual_pageBar a::after {
  7178. content: none;
  7179. }
  7180. .pagetual_pageBar a>span {
  7181. margin-top: 0!important;
  7182. pointer-events: none;
  7183. padding: unset;
  7184. opacity: 0;
  7185. -moz-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  7186. -webkit-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  7187. transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  7188. transform: none;
  7189. left: 0;
  7190. margin-left: calc(50% - 20px);
  7191. }
  7192. .pagetual_pageBar a>span:hover {
  7193. color: red;
  7194. }
  7195. .pagetual_pageBar a:hover>span {
  7196. opacity: 1!important;
  7197. }
  7198. .pagetual_pageBar span.prevScreen,
  7199. .pagetual_pageBar span.nextScreen {
  7200. display: block!important;
  7201. top: unset !important;
  7202. padding: unset !important;
  7203. opacity: 0!important;
  7204. }
  7205. .pagetual_pageBar a:hover>span.prevScreen {
  7206. margin-top: -${rulesData.opacity == 1 ? 31 : 30}px!important;
  7207. pointer-events: all;
  7208. }
  7209. .pagetual_pageBar span.refreshRing {
  7210. position: absolute;
  7211. top: 0;
  7212. opacity: 0;
  7213. height: 30px;
  7214. margin-left: calc(50% - 23px);
  7215. display: block!important;
  7216. }
  7217. .pagetual_pageBar span.refreshRing>svg {
  7218. background: white;
  7219. border-radius: 50%;
  7220. }
  7221. .pagetual_pageBar a:hover>span.refreshRing {
  7222. opacity: 0.3;
  7223. -webkit-animation: pagetual_ring 2.0s infinite linear;
  7224. animation: pagetual_ring 2.0s infinite linear;
  7225. }
  7226. @-webkit-keyframes pagetual_ring {
  7227. 0% { -webkit-transform: rotate(0deg) }
  7228. 100% {
  7229. -webkit-transform: rotate(360deg);
  7230. }
  7231. }
  7232. @keyframes pagetual_ring {
  7233. 0% {
  7234. transform: rotate(0deg);
  7235. -webkit-transform: rotate(0deg);
  7236. } 100% {
  7237. transform: rotate(360deg);
  7238. -webkit-transform: rotate(360deg);
  7239. }
  7240. }
  7241. .pagetual_pageBar a:hover>span.nextScreen {
  7242. margin-top: 30px!important;
  7243. pointer-events: all;
  7244. }
  7245. .pagetual_pageBar span>svg {
  7246. -moz-transition:transform 0.5s ease, opacity 0.3s ease;
  7247. -webkit-transition:transform 0.5s ease, opacity 0.3s ease;
  7248. transition:transform 0.5 ease, opacity 0.3s ease;
  7249. opacity: 0;
  7250. }
  7251. .pagetual_pageBar.stop span>svg{
  7252. opacity: 1;
  7253. }
  7254. .pagetual_pageBar.stop span>svg>path{
  7255. transform: scale(.8);
  7256. transform-origin: center;
  7257. -moz-transition:transform 0.3s ease;
  7258. -webkit-transition:transform 0.3s ease;
  7259. transition:transform 0.3 ease;
  7260. }
  7261. .pagetual_pageBar.stop:hover span>svg>path{
  7262. transform: unset;
  7263. }
  7264. .pagetual_pageBar:hover span>svg {
  7265. opacity: 1;
  7266. }
  7267. .pagetual_pageBar span>svg.upSvg:hover {
  7268. transform: rotate(360deg) scale3d(1.2, 1.2, 1.2);
  7269. }
  7270. .pagetual_pageBar span>svg.downSvg:hover {
  7271. transform: rotate(540deg) scale3d(1.2, 1.2, 1.2)!important;
  7272. }
  7273. .pagetual_pageBar .pagetual_pageNum{
  7274. color: #55555f;
  7275. }
  7276. .pagetual_pageBar .pagetual_pageNum:hover{
  7277. color: #ff6464;
  7278. }
  7279. .pagetual_tipsWords {
  7280. font-size: 50px;
  7281. font-weight: bold;
  7282. font-family: "黑体", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
  7283. "Oxygen", "Ubuntu", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
  7284. "Segoe UI Emoji", "Segoe UI Symbol";
  7285. color: #ffffff;
  7286. min-height: 70px;
  7287. max-width: 80%;
  7288. line-height: 1.5;
  7289. position: fixed;
  7290. left: 50%;
  7291. top: 10%;
  7292. margin-left: -99999px;
  7293. padding: 0 15px;
  7294. z-index: 2147483647;
  7295. background-color: #000;
  7296. border: 1px solid #303030;
  7297. border-radius: 10px;
  7298. opacity: 0;
  7299. filter: alpha(opacity=65);
  7300. box-shadow: 5px 5px 20px 0px #000;
  7301. -moz-transition:opacity 0.3s ease-in-out 0s;
  7302. -webkit-transition:opacity 0.3s ease-in-out 0s;
  7303. transition:opacity 0.3s ease-in-out 0s;
  7304. pointer-events: none;
  7305. word-break: break-all;
  7306. }
  7307. .pagetual_tipsWords>a {
  7308. color: #ffffff;
  7309. }
  7310. .pagetual_loading {
  7311. width: 50px;
  7312. height: 50px;
  7313. margin: 10px auto;
  7314. border-radius: 100%;
  7315. display: flex;
  7316. -webkit-animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  7317. animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  7318. }
  7319. @-webkit-keyframes pagetual_loading_scaleout {
  7320. 0% { -webkit-transform: scale(0.0) }
  7321. 100% {
  7322. -webkit-transform: scale(1.0);
  7323. opacity: 0;
  7324. }
  7325. }
  7326. @keyframes pagetual_loading_scaleout {
  7327. 0% {
  7328. transform: scale(0.0);
  7329. -webkit-transform: scale(0.0);
  7330. } 100% {
  7331. transform: scale(1.0);
  7332. -webkit-transform: scale(1.0);
  7333. opacity: 0;
  7334. }
  7335. }
  7336. .pagetual_loading_text {
  7337. white-space: nowrap;
  7338. -webkit-animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  7339. animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  7340. }
  7341. @-webkit-keyframes pagetual_loading_opacity {
  7342. 0% { opacity: 1 }
  7343. 50% { opacity: 0.2 }
  7344. 100% { opacity: 1 }
  7345. }
  7346. @keyframes pagetual_loading_opacity {
  7347. 0% { opacity: 1 }
  7348. 50% { opacity: 0.2 }
  7349. 100% { opacity: 1 }
  7350. }
  7351. `;
  7352. 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%);"}`;
  7353. }
  7354. if (!mainStyleEle || !mainStyleEle.parentNode) {
  7355. mainStyleEle = _GM_addStyle(mainStyleStyle);
  7356. }
  7357. }
  7358. var loadingDiv = document.createElement("div");
  7359. 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;";
  7360.  
  7361. 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;`;
  7362. function setLoadingDiv(loadingText) {
  7363. 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>`}`);
  7364. }
  7365.  
  7366. 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>`;
  7367. 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;`;
  7368. 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>`;
  7369. 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);`;
  7370.  
  7371. 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;`;
  7372. 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;`;
  7373. var sideControllerIcon = '';
  7374.  
  7375. var tipsWords = document.createElement("div");
  7376. tipsWords.className = "pagetual_tipsWords";
  7377.  
  7378. function changeStop(stop, save) {
  7379. isPause = stop;
  7380. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar,#pagetual-sideController"), bar => {
  7381. if (isPause) {
  7382. bar.classList.add("stop");
  7383. } else {
  7384. bar.classList.remove("stop");
  7385. }
  7386. });
  7387. if (!isPause) ruleParser.showAddedElements();
  7388. manualPause = isPause;
  7389. if (save && sideController.inited) setListData("pauseState", location.host, isPause ? true : "");
  7390. }
  7391.  
  7392. function changeHideBar(hide) {
  7393. isHideBar = hide;
  7394. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar"), bar => {
  7395. if (isHideBar) {
  7396. bar.classList.add("hide");
  7397. } else {
  7398. bar.classList.remove("hide");
  7399. }
  7400. });
  7401. }
  7402.  
  7403. function isInViewPort(element) {
  7404. if (!getBody(document).contains(element)) return false;
  7405. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  7406. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  7407. const {
  7408. top,
  7409. right,
  7410. bottom,
  7411. left,
  7412. } = element.getBoundingClientRect();
  7413.  
  7414. return (
  7415. top >= 0 &&
  7416. left >= 0 &&
  7417. right <= viewWidth + 1 &&
  7418. top <= viewHeight * rate &&
  7419. isVisible(element, _unsafeWindow)
  7420. );
  7421. }
  7422.  
  7423. function getPageBar() {
  7424. let preBar = null, nextBar = null;
  7425. let pageBars = [].slice.call(document.querySelectorAll(".pagetual_pageBar"));
  7426. for (let i = 0; i < pageBars.length; i++) {
  7427. let pageBar = pageBars[i];
  7428. if (!pageBar || !getBody(document).contains(pageBar)) continue;
  7429. let {
  7430. top,
  7431. right,
  7432. bottom,
  7433. left,
  7434. } = pageBar.getBoundingClientRect();
  7435. if (top > 500) {
  7436. nextBar = pageBar;
  7437. preBar = (i - 1 >= 0 ? pageBars[i - 1] : null);
  7438. if (pageBar && getBody(document).contains(pageBar)) {
  7439. let {
  7440. top,
  7441. right,
  7442. bottom,
  7443. left,
  7444. } = pageBar.getBoundingClientRect();
  7445. if (top < -500) {
  7446. preBar = pageBar;
  7447. } else preBar = (i - 2 >= 0 ? pageBars[i - 2] : null);
  7448. }
  7449. break;
  7450. }
  7451. }
  7452. if (!nextBar) preBar = pageBars[pageBars.length - 2];
  7453. return {preBar: preBar, nextBar: nextBar};
  7454. }
  7455.  
  7456. var urlChanged = false;
  7457. var urlChanging = false;
  7458. var urlchangeHandler = e => {
  7459. if (ruleParser && ruleParser.curSiteRule && ruleParser.curSiteRule.listenUrlChange == false) return;
  7460. isPause = true;
  7461. setTimeout(() => {
  7462. lastActiveUrl = location.href;
  7463. if (urlChanging) return;
  7464. urlChanging = true;
  7465. let href = location.href.slice(0, 60);
  7466. if (href == configPage[1]) {
  7467. setTimeout(() => {
  7468. initConfig(href);
  7469. urlChanging = false;
  7470. }, 1000);
  7471. } else {
  7472. setTimeout(() => {
  7473. if (guidePage.test(href)) {
  7474. setTimeout(() => {
  7475. initConfig(href);
  7476. urlChanging = false;
  7477. }, 1000);
  7478. } else {
  7479. ruleParser.urlChanged();
  7480. if (!ruleParser.nextLinkHref) {
  7481. isLoading = false;
  7482. }
  7483. urlChanging = false;
  7484. //if (!pageReady && !ruleImportUrlReg.test(href)) location.reload();
  7485. }
  7486. }, 500);
  7487. }
  7488. }, 1);
  7489. };
  7490. window.addEventListener('pagetual_pushState', urlchangeHandler);
  7491. /*var _wr = function(type) {
  7492. var orig = history[type];
  7493. return function() {
  7494. var rv = orig.apply(this, arguments);
  7495. var e = new Event('pagetual_' + type);
  7496. e.arguments = arguments;
  7497. window.dispatchEvent(e);
  7498. return rv;
  7499. };
  7500. };
  7501. history.pushState = _wr('pushState');*/
  7502.  
  7503. function listenUrl() {
  7504. var prevPathname = window.location.pathname;
  7505. var prevSearch = window.location.search;
  7506. var checkUrlTime = 100;
  7507. var checkUrlTimer;
  7508. var checkClickedEle = null;
  7509. var checkFunc = () => {
  7510. if (forceState == 1) return;
  7511. if (checkClickedEle) {
  7512. if (!clickedSth && checkClickedEle && checkClickedEle.nodeName) {
  7513. if (compareNodeName(checkClickedEle, ["a", "button"])) {
  7514. clickedSth = true;
  7515. } else {
  7516. let targetStyle = _unsafeWindow.getComputedStyle(checkClickedEle);
  7517. if (targetStyle.cursor == "pointer") clickedSth = true;
  7518. }
  7519. }
  7520. checkClickedEle = null;
  7521. }
  7522. if (checkUrlTime < 5000) {
  7523. checkUrlTime += checkUrlTime>>1;
  7524. }
  7525. clearTimeout(checkUrlTimer);
  7526. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7527. if (document.hidden) return;
  7528. if (!ruleParser.canListenUrlChange()) {
  7529. return;
  7530. }
  7531. if ((prevPathname !== window.location.pathname || prevSearch !== window.location.search) && window.location.href != ruleParser.historyUrl) {
  7532. checkUrlTime = 2000;
  7533. urlWillChange = true;
  7534. var e = new Event('pagetual_pushState');
  7535. e.arguments = arguments;
  7536. window.dispatchEvent(e);
  7537. clickedSth = false;
  7538. }
  7539. prevPathname = window.location.pathname;
  7540. prevSearch = window.location.search;
  7541. };
  7542. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7543.  
  7544. document.addEventListener("click", e => {
  7545. if (!checkClickedEle) {
  7546. checkClickedEle = e.target;
  7547. checkUrlTime = 300;
  7548. clearTimeout(checkUrlTimer);
  7549. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7550. }
  7551. });
  7552. }
  7553.  
  7554. let scrollContainer;
  7555. function distToBottom () {
  7556. let scrolly = window.scrollY;
  7557. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  7558. if (!scrollContainer || !document.documentElement.contains(scrollContainer)) {
  7559. if (curPage > 1 || ruleParser.nextLinkHref) {
  7560. let pageEle = ruleParser.getPageElement(document);
  7561. if (pageEle && pageEle.length) {
  7562. let parent = pageEle[0].parentNode, pageScrollY = parent.scrollTop;
  7563. while (parent && pageScrollY == 0) {
  7564. parent = parent.parentNode;
  7565. pageScrollY = parent.scrollTop;
  7566. }
  7567. if (pageScrollY) {
  7568. scrollContainer = parent;
  7569. return scrollContainer.scrollHeight - pageScrollY - windowHeight;
  7570. }
  7571. }
  7572. }
  7573. }
  7574. if (scrollContainer) {
  7575. return scrollContainer.scrollHeight - scrollContainer.scrollTop - windowHeight;
  7576. }
  7577.  
  7578. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7579. return scrollH - scrolly - windowHeight;
  7580. }
  7581.  
  7582. let scrollHandler, clickToResetHandler, dblclickHandler, keydownHandler, hashchangeHandler, manualModeKeyHandler, pagetualNextHandler, keyupHandler, messageHandler;
  7583. function initListener () {
  7584. document.removeEventListener('scroll', scrollHandler, true);
  7585. document.removeEventListener('wheel', scrollHandler, true);
  7586. document.removeEventListener('dblclick', dblclickHandler);
  7587. document.removeEventListener('keydown', keydownHandler);
  7588. window.removeEventListener('hashchange', hashchangeHandler, false);
  7589. document.removeEventListener('keydown', manualModeKeyHandler);
  7590. document.removeEventListener('pagetual.next', pagetualNextHandler, false);
  7591. document.removeEventListener('keyup', keyupHandler);
  7592. _unsafeWindow.removeEventListener('message', messageHandler, true);
  7593. let loadmoreBtn, loadingMore = true, lastScroll = 0, checkLoadMoreTimes = 0, loadMoreInv;
  7594. if (ruleParser.curSiteRule.smart) {
  7595. loadingMore = false;
  7596. } else if (ruleParser.curSiteRule.loadMore) {
  7597. loadingMore = false;
  7598. }
  7599. clickMode = typeof ruleParser.curSiteRule.clickMode == 'undefined' ? rulesData.clickMode : ruleParser.curSiteRule.clickMode;
  7600. let clickingNext = false;
  7601. let clickNext = async () => {
  7602. if (clickingNext) return;
  7603. clickingNext = true;
  7604. setTimeout(() => {
  7605. clickingNext = false;
  7606. }, 1500);
  7607. let nextLink = ruleParser.nextLinkHref;
  7608. if (!nextLink) return;
  7609. let isJs = ruleParser.hrefIsJs(nextLink);
  7610. if (isJs) {
  7611. let nextBtn = ruleParser.nextLinkEle;
  7612. if (!nextBtn || !nextBtn.offsetParent) nextBtn = await ruleParser.getNextLink(document, true);
  7613. if (nextBtn) emuClick(nextBtn);
  7614. } else {
  7615. window.location.href = nextLink;
  7616. }
  7617. };
  7618. let checkScrollReach = () => {
  7619. let dist = distToBottom();
  7620. if (clickMode) {
  7621. if (dist < 10) {
  7622. clickNext();
  7623. }
  7624. } else if (dist < bottomGap) {
  7625. nextPage();
  7626. }
  7627. };
  7628. messageHandler = e => {
  7629. if (e.data.command === 'pagetual') {
  7630. let action = e.data.action;
  7631. let detail = e.data.detail;
  7632. switch (action) {
  7633. case "config":
  7634. if (!detail || typeof detail !== 'object') return;
  7635. rulesData = {
  7636. ...rulesData,
  7637. ...detail
  7638. }
  7639. storage.setItem("rulesData", rulesData);
  7640. break;
  7641. case "nextPage":
  7642. if (detail === "" || detail === null) return;
  7643. detail = parseInt(detail) || 0;
  7644. if (loadNowNum != detail) {
  7645. loadNowNum = detail;
  7646. }
  7647. autoLoadNum = detail;
  7648. nextPage();
  7649. break;
  7650. case "loadMore":
  7651. clearInterval(loadMoreInv);
  7652. if (detail === -1) return;
  7653. loadmoreBtn = getLoadMore(document, loadmoreBtn);
  7654. loadmoreBtn && emuClick(loadmoreBtn);
  7655. if (detail === 0) {
  7656. loadMoreInv = setInterval(() => {
  7657. loadmoreBtn = getLoadMore(document, loadmoreBtn);
  7658. loadmoreBtn && emuClick(loadmoreBtn);
  7659. }, 500);
  7660. }
  7661. break;
  7662. }
  7663. }
  7664. return true;
  7665. }
  7666. _unsafeWindow.addEventListener('message', messageHandler, true);
  7667. scrollHandler = e => {
  7668. if (urlChanged && !isLoading) {
  7669. ruleParser.initPage(() => {});
  7670. urlChanged = false;
  7671. loadingMore = false;
  7672. return;
  7673. }
  7674. if (isPause) return;
  7675. if (!loadingMore) {
  7676. loadmoreBtn = getLoadMore(document, loadmoreBtn);
  7677. if (loadmoreBtn) {
  7678. if (isInViewPort(loadmoreBtn)) {
  7679. emuClick(loadmoreBtn);
  7680. loadingMore = true;
  7681. setTimeout(() => {loadingMore = false}, 200);
  7682. }
  7683. } else {
  7684. loadingMore = true;
  7685. if (!ruleParser.curSiteRule.smart || checkLoadMoreTimes++ < 3) {
  7686. setTimeout(() => {loadingMore = false}, 200);
  7687. }
  7688. }
  7689. }
  7690. if (!isLoading && !stopScroll) {
  7691. checkScrollReach();
  7692. }
  7693. ruleParser.changeVisibility();
  7694. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  7695. if (ruleParser.curSiteRule.lockScroll) {
  7696. if (isLoading && Math.abs(lastScroll - curScroll) > 350) {
  7697. getBody(document).scrollTop = lastScroll;
  7698. document.documentElement.scrollTop = lastScroll;
  7699. } else {
  7700. lastScroll = curScroll;
  7701. }
  7702. }
  7703. if (targetY >= 0) {
  7704. if (Math.abs(targetY - curScroll) < 100) {
  7705. targetY = -1;
  7706. }
  7707. }
  7708. };
  7709. dblclickHandler = e => {
  7710. if (forceState == 1 || compareNodeName(e.target, ["input", "textarea", "select", "a", "button", "svg", "use", "img", "path"])) return;
  7711. if (!rulesData.dbClick2StopKey) {
  7712. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  7713. (rulesData.dbClick2StopAlt && !e.altKey) ||
  7714. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  7715. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  7716. return;
  7717. }
  7718. }
  7719. if (!compareNodeName(e.target, ["body"]) && !e.target.classList.contains('pagetual_pageBar')) {
  7720. try {
  7721. let selection = window.getSelection();
  7722. let selStr = selection.toString().trim();
  7723. if (!selStr) {
  7724. selection = selection.getRangeAt(0);
  7725. selStr = selection && selection.cloneContents().children[0];
  7726. if (selStr && !compareNodeName(selStr, ["img"])) selStr = false;
  7727. }
  7728. if (selStr) {
  7729. return;
  7730. }
  7731. } catch (e) {}
  7732. }
  7733. if (rulesData.dbClick2Stop && (ruleParser.nextLinkHref || loadmoreBtn)) {
  7734. setTimeout(() => {
  7735. if (rulesData.hideBarButNoStop || rulesData.hideBar) {
  7736. changeHideBar(!isHideBar);
  7737. }
  7738. if (!rulesData.hideBarButNoStop) {
  7739. changeStop(!isPause, true);
  7740. showTips(i18n(isPause ? "disable" : "enable"));
  7741. }
  7742. if (!isPause) {
  7743. checkScrollReach();
  7744. }
  7745. }, 10);
  7746. }
  7747. };
  7748. document.addEventListener('dblclick', dblclickHandler);
  7749. clickToResetHandler = e => {
  7750. if (!ruleParser.nextLinkHref) isLoading = false;
  7751. };
  7752. document.addEventListener('click', clickToResetHandler);
  7753. if (rulesData.dbClick2StopKey) {
  7754. keydownHandler = e => {
  7755. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  7756. (rulesData.dbClick2StopAlt && !e.altKey) ||
  7757. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  7758. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  7759. return;
  7760. }
  7761. if (document.activeElement &&
  7762. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  7763. document.activeElement.contentEditable == 'true')) {
  7764. return;
  7765. }
  7766. var key = e.key.toLowerCase();
  7767. if (rulesData.dbClick2StopKey.toLowerCase() == key) {
  7768. if (forceState == 1) {
  7769. forceState = 0;
  7770. showTips(i18n("enableSiteTips"));
  7771. changeStop(false, true);
  7772. } else {
  7773. forceState = 1;
  7774. showTips(i18n("disableSiteTips"));
  7775. changeStop(true, true);
  7776. sideController.remove();
  7777. }
  7778. if (!ruleParser.curSiteRule.url) {
  7779. setListData("forceState", location.host, forceState);
  7780. setTimeout(() => {
  7781. location.reload();
  7782. }, 500);
  7783. }
  7784. }
  7785. };
  7786. document.addEventListener('keydown', keydownHandler);
  7787. }
  7788. if (ruleParser.curSiteRule.listenHashChange) {
  7789. hashchangeHandler = () => {
  7790. isPause = true;
  7791. ruleParser.urlChanged();
  7792. if (!ruleParser.nextLinkHref) isLoading = false;
  7793. };
  7794. window.addEventListener('hashchange', hashchangeHandler, false);
  7795. }
  7796. let manualMode = typeof ruleParser.curSiteRule.manualMode == 'undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode;
  7797. if (manualMode) {
  7798. manualModeKeyHandler = e => {
  7799. if (document.activeElement &&
  7800. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  7801. document.activeElement.contentEditable == 'true')) {
  7802. return;
  7803. }
  7804. if (e.keyCode == 39) {
  7805. clickNext();
  7806. } else if (e.keyCode == 37) {
  7807. history.back();
  7808. }
  7809. };
  7810. document.addEventListener('keydown', manualModeKeyHandler);
  7811. pagetualNextHandler = () => {
  7812. clickNext();
  7813. };
  7814. document.addEventListener('pagetual.next', pagetualNextHandler, false);
  7815. return;
  7816. }
  7817. if (rulesData.arrowToScroll) {
  7818. keyupHandler = e => {
  7819. if (document.activeElement &&
  7820. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  7821. document.activeElement.contentEditable == 'true')) {
  7822. return;
  7823. }
  7824. if (e.keyCode == 39) {
  7825. let nextPageBar=getPageBar().nextBar;
  7826. if (nextPageBar) {
  7827. scrollToPageBar(nextPageBar);
  7828. } else {
  7829. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  7830. window.scrollTo({ top: scrollTop + (window.innerHeight || document.documentElement.clientHeight), behavior: 'instant'});
  7831. }
  7832. } else if (e.keyCode == 37) {
  7833. let prePageBar = getPageBar().preBar;
  7834. if (prePageBar) {
  7835. scrollToPageBar(prePageBar);
  7836. } else {
  7837. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  7838. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'instant'});
  7839. }
  7840. }
  7841. };
  7842. document.addEventListener('keyup', keyupHandler);
  7843. }
  7844. if (!ruleParser.curSiteRule.wheel) {
  7845. document.addEventListener('scroll', scrollHandler, true);
  7846. }
  7847. document.addEventListener('wheel', scrollHandler, true);
  7848. }
  7849.  
  7850. let hideTipsTimeout;
  7851. function showTips(content, href, time, wordColor, backColor) {
  7852. initView();
  7853. document.documentElement.appendChild(tipsWords);
  7854. tipsWords.style.color = wordColor || 0xFFFFFF;
  7855. tipsWords.style.backgroundColor = backColor || 0x000;
  7856. let _time = 1500;
  7857. if (href) {
  7858. _time = 3500;
  7859. tipsWords.innerHTML = createHTML(`<a href='${href}' target='_blank'>${content}</a>`);
  7860. tipsWords.style.pointerEvents = 'all';
  7861. } else {
  7862. tipsWords.innerHTML = createHTML(content);
  7863. }
  7864. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  7865. setTimeout(() => {
  7866. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  7867. }, 0);
  7868. setTimeout(() => {
  7869. tipsWords.style.opacity = 0.8;
  7870. clearTimeout(hideTipsTimeout);
  7871. hideTipsTimeout = setTimeout(() => {
  7872. tipsWords.style.opacity = 0;
  7873. tipsWords.style.pointerEvents = '';
  7874. }, time || _time);
  7875. }, 1);
  7876. }
  7877.  
  7878. const loadmoreReg = /^\s*((点击)?加载更多|(點擊)?加載更多|(load|view)\s*more|もっと読み込む)[.…▼\s]*$/i;
  7879. 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";
  7880. function getLoadMore(doc, loadmoreBtn) {
  7881. if (!loadmoreBtn || !getBody(doc).contains(loadmoreBtn) || /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  7882. if (!ruleParser.curSiteRule.smart && !ruleParser.curSiteRule.loadMore) return null;
  7883. if (loadmoreBtn) return loadmoreBtn;
  7884. let btnSel = ruleParser.curSiteRule.loadMore || defaultLoadmoreSel;
  7885. if (btnSel) {
  7886. loadmoreBtn = getElement(btnSel, doc, null, true);
  7887. }
  7888. if (!loadmoreBtn) {
  7889. let buttons = doc.querySelectorAll("input,button,a,div[onclick]");
  7890. for (let i = 0; i < buttons.length; i++) {
  7891. let button = buttons[i];
  7892. if (!button.innerText || button.innerText.length > 20) continue;
  7893. if (button && loadmoreReg.test(button.innerText)) {
  7894. loadmoreBtn = button;
  7895. break;
  7896. }
  7897. }
  7898. }
  7899. if (loadmoreBtn && !ruleParser.curSiteRule.loadMore && loadmoreBtn.dataset.ajax !== "true") {
  7900. let href = loadmoreBtn.getAttribute("href");
  7901. if (href && href != "/" && !ruleParser.hrefIsJs(href)) {
  7902. loadmoreBtn = null;
  7903. }
  7904. }
  7905. if (loadmoreBtn && /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  7906. if (loadmoreBtn) debug(loadmoreBtn, 'Load more button');
  7907. return loadmoreBtn;
  7908. }
  7909.  
  7910. var targetY = -1;
  7911. function scrollToPageBar(bar) {
  7912. if (window.pageYOffset == 0) {
  7913. bar.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" });
  7914. } else {
  7915. let yOffset = -20;
  7916. if (typeof ruleParser.curSiteRule.pageBarTop !== 'undefined') {
  7917. yOffset = -ruleParser.curSiteRule.pageBarTop;
  7918. }
  7919. targetY = bar.getBoundingClientRect().top + window.pageYOffset + yOffset;
  7920. window.scrollTo({ top: targetY, behavior: 'smooth'});
  7921. }
  7922. }
  7923.  
  7924. const pageNumReg=/[&\/\?](p=|page[=\/_-]?)\d+|[_-]\d+\./;
  7925. function createPageBar(url) {
  7926. curPage++;
  7927. sideController.setup();
  7928. let posEle = null;
  7929. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7930. let insert = ruleParser.getInsert();
  7931. if (!insert || !insert.parentNode) return;
  7932. if (forceState == 2) {
  7933. posEle = getBody(document);
  7934. posEle = posEle.children[posEle.children.length - 1];
  7935. } else {
  7936. posEle = insert;
  7937. }
  7938. while (posEle && !posEle.offsetParent) {
  7939. posEle = posEle.previousElementSibling || posEle.parentNode;
  7940. }
  7941. if (posEle) {
  7942. let actualBottom = getElementBottom(posEle);
  7943. bottomGap = scrollH - actualBottom + (window.innerHeight || document.documentElement.clientHeight) * rate;
  7944. if (bottomGap < 100) bottomGap = 100;
  7945. } else {
  7946. bottomGap = 1000;
  7947. }
  7948. if (rulesData.opacity == 0 || ruleParser.curSiteRule.pageBar === 0) return null;
  7949. url = url.replace(/#p{.*/, "");
  7950. let example = (ruleParser.curSiteRule.insertPos == 2 || ruleParser.curSiteRule.insertPos == "in") ? insert.children[0] : (insert.parentNode.children[0] || insert);
  7951. while (example && (compareNodeName(example, ["script", "style"]) || example.className == "pagetual_pageBar")) {
  7952. example = example.nextElementSibling;
  7953. }
  7954. if (!example || !example.parentNode) example = insert;
  7955. if (example.nodeType != 1) {
  7956. example = example.previousElementSibling || example.parentNode;
  7957. if (!example || example.nodeType != 1) return;
  7958. }
  7959. let exampleStyle = _unsafeWindow.getComputedStyle(example);
  7960. let inTable, inLi;
  7961. if (forceState == 2) {
  7962. inTable = inLi = false;
  7963. } else {
  7964. inTable = compareNodeName(example.parentNode, ["table", "tbody"]) ||
  7965. compareNodeName(example, ["tr", "tbody"]) ||
  7966. exampleStyle.display == "table-row" ||
  7967. (example.nextElementSibling && compareNodeName(example.nextElementSibling, ["tr", "tbody"]));
  7968. inLi = compareNodeName(example, ["li"]) || (example.nextElementSibling && compareNodeName(example.nextElementSibling, ["li"]));
  7969. }
  7970. let pageBar = document.createElement(inTable ? "tr" : (inLi ? "li" : "div"));
  7971. let upSpan = document.createElement("span");
  7972. let downSpan = document.createElement("span");
  7973. let pageText = document.createElement("a");
  7974. let pageNum;
  7975. pageBar.className = isHideBar ? "pagetual_pageBar hide" : "pagetual_pageBar";
  7976. pageBar.id = "pagetual_pageBar" + curPage;
  7977. pageBar.setAttribute("translate", "no");
  7978. if (isPause) {
  7979. pageBar.classList.add("stop");
  7980. }
  7981. pageBar.style.cssText = pageBarStyle;
  7982. pageBar.title = i18n(isPause ? "enable" : "disable");
  7983. upSpan.innerHTML = createHTML(upSvg);
  7984. upSpan.children[0].style.cssText = upSvgCSS;
  7985. upSpan.title = i18n("toTop");
  7986. downSpan.innerHTML = createHTML(downSvg);
  7987. downSpan.children[0].style.cssText = downSvgCSS;
  7988. downSpan.title = i18n("toBottom");
  7989. upSpan.style.cssText = initStyle;
  7990. downSpan.style.cssText = initStyle;
  7991. pageText.href = url;
  7992. pageText.style.cssText = pageTextStyle;
  7993. pageText.title = i18n("current");
  7994. if (openInNewTab == 1) pageText.target = "_blank";
  7995. pageBar.appendChild(upSpan);
  7996. pageBar.appendChild(pageText);
  7997. let touched = false;
  7998. let touchBodyHandler = e => {
  7999. touched = false;
  8000. getBody(document).removeEventListener('touchstart', touchBodyHandler, { passive: false, capture: false });
  8001. };
  8002. pageText.addEventListener("touchstart", e => {
  8003. if (touched) return;
  8004. touched = true;
  8005. pageText.style.pointerEvents = 'none';
  8006. setTimeout(() => {
  8007. pageText.style.pointerEvents = 'all';
  8008. }, 250);
  8009. getBody(document).addEventListener("touchstart", touchBodyHandler, { passive: false, capture: false });
  8010. }, { passive: false, capture: false });
  8011. if (ruleParser.nextTitle) {
  8012. pageText.innerHTML = createHTML(ruleParser.nextTitle + " ");
  8013. pageText.title = ruleParser.nextTitle;
  8014. }
  8015. if (ruleParser.curSiteRule.pageNum || pageNumReg.test(url)) {
  8016. pageText.innerHTML = createHTML(pageText.innerHTML + i18n("page"));
  8017. pageNum = document.createElement("span");
  8018. let num = ruleParser.getPageNumFromUrl(url, curPage);
  8019. pageNum.innerHTML = createHTML(num + "<i style='font-size: 0;'>&nbsp;</i>");
  8020. pageNum.className = "pagetual_pageNum";
  8021. pageNum.title = i18n("inputPageNum");
  8022. pageNum.style.cssText = pageTextStyle;
  8023. pageNum.style.cursor = "pointer";
  8024. pageNum.style.color = "";
  8025. pageNum.style.marginLeft = "5px";
  8026. pageNum.addEventListener("click", e => {
  8027. let pageInput = prompt(i18n("inputPageNum"), num || "1");
  8028. if (pageInput) {
  8029. let localPageBar = document.querySelector("#pagetual_pageBar" + pageInput);
  8030. if (localPageBar) {
  8031. scrollToPageBar(localPageBar);
  8032. } else {
  8033. let pageLink = ruleParser.getLinkByPage(url, pageInput);
  8034. if (pageLink) {
  8035. _GM_openInTab(pageLink, {active:true});
  8036. }
  8037. }
  8038. }
  8039. e.preventDefault();
  8040. e.stopPropagation();
  8041. });
  8042. pageBar.appendChild(pageNum);
  8043. } else {
  8044. pageText.innerHTML = createHTML(pageText.innerHTML + i18n("page") + curPage + "<i style='font-size: 0;'>&nbsp;</i>");
  8045. }
  8046. let preBtn = document.createElement("span");
  8047. preBtn.innerHTML = createHTML("∧");
  8048. preBtn.title = i18n("prevPage");
  8049. preBtn.className = "prevScreen";
  8050. 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; ";
  8051. let nextBtn = document.createElement("span");
  8052. nextBtn.innerHTML = createHTML("∨");
  8053. nextBtn.title = i18n("nextPage");
  8054. nextBtn.className = "nextScreen";
  8055. 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; ";
  8056. let localPage = curPage;
  8057. preBtn.addEventListener("click", e => {
  8058. e.stopPropagation();
  8059. e.preventDefault();
  8060. let prePageBar = document.querySelector("#pagetual_pageBar" + (localPage - 1));
  8061. if (prePageBar) {
  8062. scrollToPageBar(prePageBar);
  8063. } else {
  8064. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  8065. targetY = scrollTop - (window.innerHeight || document.documentElement.clientHeight);
  8066. window.scrollTo({ top: targetY, behavior: 'smooth'});
  8067. }
  8068. });
  8069. nextBtn.addEventListener("click", e => {
  8070. e.stopPropagation();
  8071. e.preventDefault();
  8072. let nextPageBar = document.querySelector("#pagetual_pageBar" + (localPage + 1));
  8073. if (nextPageBar) {
  8074. scrollToPageBar(nextPageBar);
  8075. } else {
  8076. scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  8077. targetY = scrollH || 9999999;
  8078. window.scrollTo({ top: targetY, behavior: 'smooth'});
  8079. }
  8080. });
  8081. if (!rulesData.hideBarArrow) {
  8082. pageText.insertBefore(preBtn, pageText.firstChild);
  8083. pageText.insertBefore(nextBtn, pageText.firstChild);
  8084. }
  8085. if (curForceIframe) {
  8086. let bgRing = document.createElement("span");
  8087. bgRing.className = "refreshRing";
  8088. bgRing.style.display = "none";
  8089. bgRing.innerHTML = createHTML(upSvg);
  8090. pageText.title = "Refresh";
  8091. pageText.appendChild(bgRing);
  8092. pageText.addEventListener("click", e => {
  8093. e.stopPropagation();
  8094. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  8095. e.preventDefault();
  8096. let nextEle = pageBar && pageBar.nextElementSibling;
  8097. if (nextEle && nextEle.name == 'pagetual-iframe') {
  8098. if (curForceIframe == nextEle) {
  8099. nextEle.setAttribute("loaded", "refresh");
  8100. }
  8101. nextEle.src = nextEle.src;
  8102. }
  8103. });
  8104. } else if (rulesData.pageBarMenu) {
  8105. pageText.addEventListener("click", e => {
  8106. e.stopPropagation();
  8107. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  8108. e.preventDefault();
  8109. picker.start();
  8110. });
  8111. }
  8112. pageBar.appendChild(downSpan);
  8113. if (forceState == 2) {
  8114. pageBar.style.width = "99%";
  8115. } else {
  8116. let parentStyle = _unsafeWindow.getComputedStyle(example.parentNode);
  8117. let parentWidth = example.parentNode.offsetWidth || parseInt(parentStyle.width);
  8118. pageBar.style.width = parentWidth - parseInt(parentStyle.paddingLeft) - parseInt(parentStyle.paddingRight) - 10 + "px";
  8119. pageBar.style.margin = '10px 5px';
  8120. if (parentStyle.display == "grid" || parentStyle.display == "inline-grid") {
  8121. pageBar.style.gridColumn = "1/-1";
  8122. }
  8123. if (inTable) {
  8124. example = compareNodeName(example, ["tr", "tbody"]) ? example : example.nextElementSibling || example;
  8125. if (compareNodeName(example, ["tbody"])) example = example.querySelector("tr");
  8126. let nextTr = example;
  8127. while (nextTr && nextTr.children.length == 0) nextTr = nextTr.nextElementSibling;
  8128. if (nextTr) example = nextTr;
  8129. let tdNum = 0;
  8130. if (exampleStyle.display == "table-row") {
  8131. [].forEach.call(example.children, el => {
  8132. tdNum += el.colSpan || 1;
  8133. });
  8134. } else {
  8135. [].forEach.call(example.children, el => {
  8136. if (compareNodeName(el, ["td", "th"])) {
  8137. tdNum += el.colSpan || 1;
  8138. }
  8139. });
  8140. }
  8141. pageBar.style.cssText = "";
  8142. pageBar.style.display = "table-row";
  8143. pageBar.style.backgroundColor = "unset";
  8144. pageBar.style.lineHeight = "20px";
  8145. pageBar.style.boxShadow = "";
  8146. let td = document.createElement("td");
  8147. td.colSpan = tdNum || 1;
  8148. let inTd = document.createElement("div");
  8149. inTd.style.cssText = pageBarStyle;
  8150. inTd.style.display = "";
  8151. inTd.className = pageBar.className;
  8152. pageBar.className = "";
  8153. inTd.appendChild(upSpan);
  8154. inTd.appendChild(pageText);
  8155. if (pageNum) inTd.appendChild(pageNum);
  8156. inTd.appendChild(downSpan);
  8157. td.appendChild(inTd);
  8158. pageBar.appendChild(td);
  8159. } else if (inLi) {
  8160. example = compareNodeName(example, ["li"]) ? example : example.nextElementSibling || example;
  8161. pageBar.style.opacity = 1;
  8162. pageBar.style.display = getComputedStyle(example).display;
  8163. pageBar.style.backgroundColor = "unset";
  8164. pageBar.style.lineHeight = "20px";
  8165. pageBar.style.boxShadow = "";
  8166. pageBar.style.border = "";
  8167. pageBar.style.width = "";
  8168. pageBar.style.maxWidth = "unset";
  8169. pageBar.style.flex = "auto";
  8170. let inTd = document.createElement("div");
  8171. inTd.style.cssText = pageBarStyle;
  8172. inTd.style.display = "";
  8173. inTd.style.margin = "0"
  8174. inTd.style.padding = "0 0";
  8175. inTd.style.textAlign = "center";
  8176. inTd.style.minWidth = "150px";
  8177. inTd.style.width = 'calc(100% - 20px)';
  8178. inTd.className = pageBar.className;
  8179. pageBar.className = "";
  8180. inTd.appendChild(upSpan);
  8181. inTd.appendChild(pageText);
  8182. if (pageNum) inTd.appendChild(pageNum);
  8183. inTd.appendChild(downSpan);
  8184. if (pageBar.style.display === 'table-row') {
  8185. let td = document.createElement("td");
  8186. td.colSpan = example.children.length;
  8187. td.style.width = '100%';
  8188. td.appendChild(inTd);
  8189. pageBar.appendChild(td);
  8190. } else {
  8191. inTd.style.width = '100%';
  8192. pageBar.appendChild(inTd);
  8193. }
  8194. }
  8195. }
  8196.  
  8197. upSpan.addEventListener("click", e => {
  8198. getBody(document).scrollTop = 0;
  8199. document.documentElement.scrollTop = 0;
  8200. e.preventDefault();
  8201. e.stopPropagation();
  8202. });
  8203. downSpan.addEventListener("click", e => {
  8204. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  8205. changeStop(true, true);
  8206. }
  8207. pageBar.title = i18n(isPause ? "enable" : "disable");
  8208. scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  8209. getBody(document).scrollTop = scrollH || 9999999;
  8210. document.documentElement.scrollTop = scrollH || 9999999;
  8211. e.preventDefault();
  8212. e.stopPropagation();
  8213. });
  8214. pageBar.addEventListener("click", e => {
  8215. changeStop(!isPause, true);
  8216. pageBar.title = i18n(isPause ? "enable" : "disable");
  8217. });
  8218. ruleParser.insertElement(pageBar);
  8219. ruleParser.runPageBar(pageBar);
  8220.  
  8221. return pageBar;
  8222. }
  8223.  
  8224. async function waitForElement(sel, doc) {
  8225. if (!sel) return null;
  8226. return new Promise((resolve) => {
  8227. let checkInv = setInterval(() => {
  8228. let result = getElement(sel, doc, null, true);
  8229. if (result) {
  8230. clearInterval(checkInv);
  8231. resolve(result);
  8232. }
  8233. }, 100);
  8234. });
  8235. }
  8236.  
  8237. async function clickAction(sel, doc) {
  8238. let btn = await waitForElement(sel, doc);
  8239. emuClick(btn, doc);
  8240. }
  8241.  
  8242. async function enterAction(sel, doc) {
  8243. let btn = await waitForElement(sel, doc);
  8244. let eventParam = { key: "Enter", keyCode: 13, bubbles: true };
  8245. let event = new KeyboardEvent('keydown', eventParam);
  8246. btn.dispatchEvent(event);
  8247. event = new KeyboardEvent('keyup', eventParam);
  8248. btn.dispatchEvent(event);
  8249. event = new KeyboardEvent('keypress', eventParam);
  8250. btn.dispatchEvent(event);
  8251. }
  8252.  
  8253. async function inputAction(sel, v, doc) {
  8254. let input = await waitForElement(sel, doc);
  8255. let event = new Event('focus', { bubbles: true });
  8256. input.dispatchEvent(event);
  8257. let lastValue = input.value;
  8258. if (input.nodeName.toUpperCase() == "INPUT") {
  8259. var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
  8260. nativeInputValueSetter.call(input, v);
  8261. } else if (input.nodeName.toUpperCase() == "TEXTAREA") {
  8262. var nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
  8263. nativeTextareaValueSetter.call(input, v);
  8264. } else {
  8265. input.innerHTML = createHTML(v);
  8266. }
  8267. event = new Event('input', { bubbles: true });
  8268. let tracker = input._valueTracker;
  8269. if (tracker) {
  8270. tracker.setValue(lastValue);
  8271. }
  8272. input.dispatchEvent(event);
  8273. event = new Event('change', { bubbles: true });
  8274. input.dispatchEvent(event);
  8275. debug(input, `input ${sel}`);
  8276. }
  8277.  
  8278. function emuClick(btn, doc) {
  8279. if (!doc) doc = document;
  8280. let curScroll = getBody(doc).scrollTop || doc.documentElement.scrollTop;
  8281. let orgHref = btn.getAttribute('href');
  8282. if (orgHref && orgHref.replace(location.origin + location.pathname, "").indexOf("#") === 0) {
  8283. let hashAction = e => {
  8284. e.preventDefault();
  8285. getBody(doc).scrollTop = curScroll;
  8286. doc.documentElement.scrollTop = curScroll;
  8287. btn.removeEventListener('click', hashAction, false);
  8288. };
  8289. btn.addEventListener('click', hashAction, false);
  8290. }
  8291. if (!PointerEvent) return btn.click();
  8292. let eventParam = {
  8293. isTrusted: true,
  8294. altKey: false,
  8295. azimuthAngle: 0,
  8296. bubbles: true,
  8297. button: 0,
  8298. buttons: 0,
  8299. clientX: 1,
  8300. clientY: 1,
  8301. cancelBubble: false,
  8302. cancelable: true,
  8303. composed: true,
  8304. ctrlKey: false,
  8305. defaultPrevented: false,
  8306. detail: 1,
  8307. eventPhase: 2,
  8308. fromElement: null,
  8309. height: 1,
  8310. isPrimary: false,
  8311. metaKey: false,
  8312. pointerId: 1,
  8313. pointerType: "mouse",
  8314. pressure: 0,
  8315. relatedTarget: null,
  8316. returnValue: true,
  8317. shiftKey: false,
  8318. toElement: null,
  8319. twist: 0,
  8320. which: 1
  8321. };
  8322. let mouseEvent = new PointerEvent("mousedown", eventParam);
  8323. btn.dispatchEvent(mouseEvent);
  8324. mouseEvent = new PointerEvent("mouseup", eventParam);
  8325. btn.dispatchEvent(mouseEvent);
  8326. let dispatchTouchEvent = (ele, type) => {
  8327. let touchEvent;
  8328. try {
  8329. touchEvent = document.createEvent('TouchEvent')
  8330. touchEvent.initTouchEvent(type, true, true)
  8331. } catch (err) {
  8332. try {
  8333. touchEvent = document.createEvent('UIEvent')
  8334. touchEvent.initUIEvent(type, true, true)
  8335. } catch (err) {
  8336. touchEvent = document.createEvent('Event')
  8337. touchEvent.initEvent(type, true, true)
  8338. }
  8339. }
  8340. if (touchEvent) {
  8341. try {
  8342. touchEvent.targetTouches = [{
  8343. pageX: 1,
  8344. pageY: 1,
  8345. clientX: 1,
  8346. clientY: 1,
  8347. target: btn
  8348. }];
  8349. touchEvent.touches = [{
  8350. pageX: 1,
  8351. pageY: 1,
  8352. clientX: 1,
  8353. clientY: 1,
  8354. target: btn
  8355. }];
  8356. touchEvent.changedTouches = [{
  8357. pageX: 1,
  8358. pageY: 1,
  8359. clientX: 1,
  8360. clientY: 1,
  8361. target: btn
  8362. }];
  8363. } catch (err) {}
  8364. ele.dispatchEvent(touchEvent);
  8365. }
  8366. }
  8367. dispatchTouchEvent(btn, "touchstart");
  8368. dispatchTouchEvent(btn, "touchend");
  8369.  
  8370. btn.click();
  8371. }
  8372.  
  8373. function emuInput(input, v) {
  8374. let result = false;
  8375. if (!input) return true;
  8376. let event = new Event('focus', { bubbles: true });
  8377. input.dispatchEvent(event);
  8378. let lastValue = input.value;
  8379. if (input.type == 'file') {
  8380. let file = v;
  8381. let blob = new Blob([file], {
  8382. type: 'text/plain'
  8383. });
  8384. file = new File([blob], 'noname.txt', { type: blob.type });
  8385. let dataTransfer = new DataTransfer();
  8386. dataTransfer.items.add(file);
  8387. input.files = dataTransfer.files;
  8388. v = "c:/fakepath/fakefile";
  8389. } else if (/INPUT/i.test(input.nodeName)) {
  8390. var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
  8391. nativeInputValueSetter.call(input, v);
  8392. } else if (/SELECT/i.test(input.nodeName)) {
  8393. var nativeSelectValueSetter = Object.getOwnPropertyDescriptor(window.HTMLSelectElement.prototype, "value").set;
  8394. nativeSelectValueSetter.call(input, v);
  8395. } else if (input.nodeName.toUpperCase() == "TEXTAREA") {
  8396. var nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
  8397. nativeTextareaValueSetter.call(input, v);
  8398. } else {
  8399. input.innerHTML = createHTML(v);
  8400. }
  8401. event = new Event('input', { bubbles: true });
  8402. let tracker = input._valueTracker;
  8403. if (tracker) {
  8404. tracker.setValue(lastValue);
  8405. }
  8406. input.dispatchEvent(event);
  8407. event = new Event('change', { bubbles: true });
  8408. input.dispatchEvent(event);
  8409. return result;
  8410. }
  8411.  
  8412. var failFromIframe = 0;
  8413. var inCors = false;
  8414. var checkRemoveIntv;
  8415. function requestFromIframe(url, callback){
  8416. if (location.protocol === 'https:' && !/^https:/.test(url)) {
  8417. ruleParser.noValidContent(url);
  8418. }
  8419. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  8420. let iframe = document.createElement('iframe');
  8421. iframe.name = 'pagetual-iframe';
  8422. iframe.width = '100%';
  8423. iframe.height = '1000';
  8424. iframe.frameBorder = '0';
  8425. if (ruleParser.curSiteRule.sandbox != false) {
  8426. iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  8427. }
  8428. 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;';
  8429. let waitTime = 100, checkEval;
  8430. ruleParser.runWait((_checkEval, _waitTime) => {
  8431. if (_checkEval) {
  8432. checkEval = _checkEval;
  8433. }
  8434. if (_waitTime) {
  8435. waitTime = _waitTime;
  8436. }
  8437. });
  8438. if (checkRemoveIntv) clearInterval(checkRemoveIntv);
  8439. checkRemoveIntv = setInterval(() => {
  8440. if (!iframe || !getBody(document).contains(iframe)) {
  8441. clearInterval(checkRemoveIntv);
  8442. loadPageOver();
  8443. }
  8444. }, 500);
  8445. let loadedHandler = async e => {
  8446. if (e.data != 'pagetual-iframe:DOMLoaded' && e.type != 'load') return;
  8447. clearInterval(checkRemoveIntv);
  8448. window.removeEventListener('message', loadedHandler, false);
  8449. iframe.removeEventListener('load', loadedHandler, false);
  8450. let pageEleTryTimes = 0;
  8451. async function checkIframe() {
  8452. if (urlChanged || isPause) {
  8453. return callback(false, false);
  8454. }
  8455. try {
  8456. let doc = iframe.contentDocument || iframe.contentWindow.document;
  8457. if (checkEval && !await checkEval(doc)) {
  8458. setTimeout(() => {
  8459. checkIframe();
  8460. }, waitTime);
  8461. return;
  8462. } else {
  8463. let preCode = ruleParser.curSiteRule.pagePre, eles = null;
  8464. if (preCode) {
  8465. try {
  8466. let preResult;
  8467. if (typeof preCode == 'function') {
  8468. preResult = await preCode(doc.documentElement.innerHTML, doc);
  8469. } else if (preCode.length == 2) {
  8470. preResult = doc.documentElement.innerHTML.replace(new RegExp(preCode[0], "gi"), preCode[1]);
  8471. } else {
  8472. preResult = await new AsyncFunction("response", "doc", '"use strict";' + preCode)(doc.documentElement.innerHTML, doc);
  8473. }
  8474. if (typeof preResult !== "undefined") {
  8475. if (typeof preResult === "string") {
  8476. doc.documentElement.innerHTML = preResult;
  8477. } else eles = preResult;
  8478. }
  8479. } catch(e) {
  8480. debug(e);
  8481. }
  8482. }
  8483. let base = doc.querySelector("base");
  8484. ruleParser.basePath = (base && base.href) || url;
  8485. if (eles === null) eles = ruleParser.getPageElement(doc, iframe.contentWindow, pageEleTryTimes < 25);
  8486. if (eles && eles.length > 0) {
  8487. await ruleParser.hookUrl(doc);
  8488. await callback(doc, eles);
  8489. } else if (pageEleTryTimes++ < 100) {
  8490. getBody(doc).scrollTop = 9999999;
  8491. doc.documentElement.scrollTop = 9999999;
  8492. setTimeout(() => {
  8493. checkIframe();
  8494. }, waitTime);
  8495. return;
  8496. } else {
  8497. if (failFromIframe++ > 2) {
  8498. failFromIframe = 0;
  8499. debug("Stop as failFromIframe");
  8500. changeStop(true);
  8501. callback(false, false);
  8502. } else {
  8503. ruleParser.noValidContent(url);
  8504. callback(false, false);
  8505. }
  8506. }
  8507. }
  8508. } catch(e) {
  8509. inCors = true;
  8510. if (forceState === 3) {
  8511. debug("Stop as cors");
  8512. isPause = true;
  8513. }
  8514. if (!ruleParser.curSiteRule.pageElement) {
  8515. ruleParser.curSiteRule.pageElement = allOfBody;
  8516. ruleParser.getInsert(true);
  8517. }
  8518. ruleParser.curSiteRule.action = 0;
  8519. ruleParser.nextLinkHref = url;
  8520. callback(false, false);
  8521. nextPage();
  8522. }
  8523. if (iframe && iframe.parentNode) iframe.parentNode.removeChild(iframe);
  8524. }
  8525. setTimeout(() => {
  8526. checkIframe();
  8527. }, waitTime);
  8528. };
  8529. let code = ruleParser.curSiteRule.iframeInit;
  8530. if (code) {
  8531. let checkReady = setInterval(() => {
  8532. let doc;
  8533. try {
  8534. doc = iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document);
  8535. } catch(e) {
  8536. clearInterval(checkReady);
  8537. return;
  8538. }
  8539. if (doc) {
  8540. clearInterval(checkReady);
  8541. try {
  8542. Function('win', 'iframe', '"use strict";' + code)(iframe.contentWindow, iframe);
  8543. } catch(e) {
  8544. debug(e);
  8545. }
  8546. }
  8547. }, 50);
  8548. }
  8549. window.addEventListener('message', loadedHandler, false);
  8550. iframe.addEventListener('load', loadedHandler, false);
  8551. iframe.src = url;
  8552. try {
  8553. getBody(document).appendChild(iframe);
  8554. } catch (e) {
  8555. return callback(false, false);
  8556. }
  8557. }
  8558.  
  8559. var emuIframe, lastActiveUrl, orgContent, meetCors = false;
  8560. function emuPage(callback) {
  8561. let orgPage = null, preContent = null, iframeDoc, checkTimes = 0, loadmoreBtn, pageEle, nextLink, loadmoreEnd = false, waitTimes = 80, changed = false;
  8562. function returnFalse(log) {
  8563. if (curPage > 1) {
  8564. if (rulesData.lastPageTips) showTips(i18n("lastPage"), "", 800);
  8565. _unsafeWindow.postMessage({
  8566. action: "lastPage",
  8567. command: 'pagetual'
  8568. }, '*');
  8569. } else {
  8570. sideController.remove();
  8571. }
  8572. debug(log);
  8573. isPause = true;
  8574. callback(false, false);
  8575. if (emuIframe && emuIframe.parentNode) {
  8576. emuIframe.parentNode.removeChild(emuIframe);
  8577. emuIframe = null;
  8578. }
  8579. }
  8580. function cloneStatus() {
  8581. if (!iframeDoc) return;
  8582. let inputs = document.querySelectorAll("input:not([type=button],[type=image],[type=reset],[type=submit])");
  8583. let selectOptions = document.querySelectorAll("select>option");
  8584. [...inputs].forEach(input => {
  8585. let sel = geneSelector(input, true, true);
  8586. let mirrorEle = iframeDoc.querySelector(sel);
  8587. if (!mirrorEle) return;
  8588. emuInput(mirrorEle, input.value);
  8589. });
  8590. [...selectOptions].forEach(option => {
  8591. let sel = geneSelector(option, true, true);
  8592. let mirrorEle = iframeDoc.querySelector(sel);
  8593. if (!mirrorEle) return;
  8594. let selected = option.selected;
  8595. mirrorEle.selected = !!selected;
  8596. mirrorEle.parentNode.dispatchEvent(new Event('change'));
  8597. });
  8598. }
  8599. async function checkPage() {
  8600. if (isPause) return loadPageOver();
  8601. try {
  8602. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  8603. } catch(e) {
  8604. returnFalse("Stop as cors");
  8605. return;
  8606. }
  8607.  
  8608. let waitTime = 200, checkEval;
  8609. ruleParser.runWait((_checkEval, _waitTime) => {
  8610. if (_checkEval) {
  8611. checkEval = _checkEval;
  8612. }
  8613. if (_waitTime) {
  8614. waitTime = _waitTime;
  8615. }
  8616. });
  8617.  
  8618. if (!orgPage) {
  8619. if (!loadmoreEnd) {
  8620. loadmoreBtn = getLoadMore(iframeDoc);
  8621. if (loadmoreBtn && isVisible(loadmoreBtn, emuIframe.contentWindow)) {
  8622. emuClick(loadmoreBtn, iframeDoc);
  8623. let intv = setInterval(() => {
  8624. loadmoreBtn = getLoadMore(iframeDoc);
  8625. if (!loadmoreBtn || !getBody(document).contains(loadmoreBtn) || !isVisible(loadmoreBtn, emuIframe.contentWindow)) {
  8626. clearInterval(intv);
  8627. loadmoreEnd = true;
  8628. setTimeout(() => {
  8629. checkPage();
  8630. }, 500);
  8631. } else if (isInViewPort(loadmoreBtn)) {
  8632. emuClick(loadmoreBtn, iframeDoc);
  8633. }
  8634. }, 200);
  8635. return;
  8636. } else {
  8637. loadmoreEnd = true;
  8638. }
  8639. }
  8640. if (checkEval && !await checkEval(iframeDoc)) {
  8641. waitTimes = 50;
  8642. setTimeout(() => {
  8643. checkPage();
  8644. }, waitTime);
  8645. return;
  8646. } else {
  8647. if (!nextLink || !nextLink.offsetParent) nextLink = await ruleParser.getNextLink(iframeDoc, true);
  8648. if (nextLink) pageEle = ruleParser.getPageElement(iframeDoc, emuIframe.contentWindow, true);
  8649. if (!pageEle || pageEle.length == 0 || !nextLink) {
  8650. getBody(iframeDoc).scrollTop = 9999999;
  8651. iframeDoc.documentElement.scrollTop = 9999999;
  8652. if (waitTimes-- > 0) {
  8653. setTimeout(() => {
  8654. checkPage();
  8655. }, waitTime);
  8656. return;
  8657. }
  8658. }
  8659. }
  8660. if (!pageEle || pageEle.length == 0) {
  8661. returnFalse("Stop as no page when emu");
  8662. return;
  8663. }
  8664. pageEle = [].filter.call(pageEle, ele => {return ele && !compareNodeName(ele, ["style", "script", "meta"])});
  8665. if (compareNodeName(pageEle[0], ["ul"]) || pageEle.length == 1) pageEle = pageEle[0];
  8666. else if (pageEle[0].parentNode == pageEle[1].parentNode) {
  8667. pageEle = pageEle[0].parentNode;
  8668. } else {
  8669. pageEle = pageEle[0];
  8670. }
  8671. if (ruleParser.curSiteRule.smart && orgContent != pageEle.innerHTML) {
  8672. orgContent = pageEle.innerHTML;
  8673. if (waitTimes-- > 0) {
  8674. setTimeout(() => {
  8675. checkPage();
  8676. }, 500);
  8677. return;
  8678. }
  8679. }
  8680. orgPage = pageEle;
  8681. if (nextLink) {
  8682. if (compareNodeName(orgPage, ["img"])) {
  8683. if (!ruleParser.curSiteRule.lazyImgSrc) ruleParser.curSiteRule.lazyImgSrc = "0";
  8684. if (orgPage.src) {
  8685. orgContent = orgPage.src;
  8686. } else {
  8687. setTimeout(() => {
  8688. checkPage();
  8689. }, 500);
  8690. return;
  8691. }
  8692. } else {
  8693. orgContent = orgPage.innerHTML;
  8694. }
  8695. preContent = orgContent;
  8696. if (!isVisible(nextLink, emuIframe.contentWindow)) {
  8697. returnFalse("Stop as next hide when emu");
  8698. } else {
  8699. emuClick(nextLink, iframeDoc);
  8700. setTimeout(() => {
  8701. checkPage();
  8702. }, 500);
  8703. }
  8704. } else {
  8705. returnFalse("Stop as no next when emu");
  8706. }
  8707. return;
  8708. }
  8709. if (!ruleParser.checkStopSign(nextLink, iframeDoc)) {
  8710. return returnFalse("Stop as stopSign");
  8711. }
  8712. if (checkTimes++ > 200) {
  8713. returnFalse("Stop as timeout when emu");
  8714. return;
  8715. }
  8716. if (checkEval && !await checkEval(iframeDoc)) {
  8717. checkTimes = 0;
  8718. setTimeout(() => {
  8719. checkPage();
  8720. }, waitTime);
  8721. return;
  8722. }
  8723. let eles = ruleParser.getPageElement(iframeDoc, emuIframe.contentWindow, true), checkItem;
  8724. if (eles && eles.length > 0) {
  8725. eles = [].filter.call(eles, ele => {return ele && !compareNodeName(ele, ["style", "script", "meta"])});
  8726. if (compareNodeName(eles[0], ["ul"]) || eles.length == 1) checkItem = eles[0];
  8727. else if (eles[0].parentNode == eles[1].parentNode) {
  8728. checkItem = eles[0].parentNode;
  8729. } else {
  8730. checkItem = eles[0];
  8731. }
  8732. }
  8733. if (!checkItem) {
  8734. setTimeout(() => {
  8735. checkPage();
  8736. }, waitTime);
  8737. } else {
  8738. let checkInner;
  8739. if (compareNodeName(checkItem, ["img"])) {
  8740. if (checkItem.src) {
  8741. checkInner = checkItem.src;
  8742. } else {
  8743. setTimeout(() => {
  8744. checkPage();
  8745. }, waitTime);
  8746. return;
  8747. }
  8748. } else {
  8749. checkInner = checkItem.innerHTML;
  8750. }
  8751. if (orgPage != checkItem || checkInner != preContent) {
  8752. changed = true;
  8753. orgPage = checkItem;
  8754. preContent = checkInner;
  8755. setTimeout(() => {
  8756. checkPage();
  8757. }, 500);
  8758. } else if (changed) {
  8759. checkTimes = 0;
  8760. if (orgContent == preContent && (ruleParser.curSiteRule.smart || ruleParser.curSiteRule.stopSame)) {
  8761. returnFalse("Stop as same content");
  8762. } else {
  8763. orgContent = preContent;
  8764. await ruleParser.hookUrl(iframeDoc);
  8765. callback(iframeDoc, eles);
  8766. }
  8767. } else {
  8768. if (checkTimes % 10 === 5) {
  8769. if (!nextLink || !nextLink.offsetParent) {
  8770. nextLink = await ruleParser.getNextLink(iframeDoc, true);
  8771. }
  8772. if (nextLink) {
  8773. emuClick(nextLink, iframeDoc);
  8774. }
  8775. }
  8776. setTimeout(() => {
  8777. checkPage();
  8778. }, waitTime);
  8779. }
  8780. }
  8781. }
  8782. if (!emuIframe) {
  8783. let loaded = false;
  8784. emuIframe = document.createElement('iframe');
  8785. emuIframe.name = 'pagetual-iframe';
  8786. let notSetSandbox = typeof ruleParser.curSiteRule.sandbox == 'undefined';
  8787. if (notSetSandbox || ruleParser.curSiteRule.sandbox == true) {
  8788. emuIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  8789. } else if (ruleParser.curSiteRule.sandbox) {
  8790. emuIframe.sandbox = ruleParser.curSiteRule.sandbox;
  8791. }
  8792. emuIframe.width = '100%';
  8793. emuIframe.height = '100%';
  8794. emuIframe.frameBorder = '0';
  8795. 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;';
  8796. emuIframe.addEventListener("load", e => {
  8797. try {
  8798. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  8799. } catch(e) {
  8800. if (e.message && e.message.indexOf("cross-origin") != -1 && notSetSandbox && emuIframe.hasAttribute("sandbox")) {
  8801. emuIframe.removeAttribute("sandbox");
  8802. meetCors = true;
  8803. callback(false, false);
  8804. if (ruleParser.curSiteRule.smart) {
  8805. ruleParser.findNoNext();
  8806. }
  8807. } else {
  8808. returnFalse("Stop as cors");
  8809. }
  8810. return;
  8811. }
  8812. setTimeout(async () => {
  8813. if (meetCors && ruleParser.curSiteRule.smart) {
  8814. ruleParser.smartRules = ruleParser.smartRules.filter(item => {return item && item.url !== ruleParser.curSiteRule.url;});
  8815. storage.setItem("smartRules", ruleParser.smartRules);
  8816. }
  8817. meetCors = false;
  8818. let code = ruleParser.curSiteRule.init;
  8819. if (code) {
  8820. try {
  8821. 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)});
  8822. } catch(e) {
  8823. debug(e);
  8824. }
  8825. } else {
  8826. let refreshByClickSel = ruleParser.curSiteRule.refreshByClick;
  8827. if (iframeDoc && refreshByClickSel) {
  8828. let clickBtn = await waitForElement(refreshByClickSel, iframeDoc);
  8829. await sleep(500);
  8830. cloneStatus();
  8831. emuClick(clickBtn, iframeDoc);
  8832. await sleep(500);
  8833. }
  8834. }
  8835. if (loaded) return;
  8836. loaded = true;
  8837. checkPage();
  8838. }, 500);
  8839. });
  8840. let code = ruleParser.curSiteRule.iframeInit;
  8841. if (code) {
  8842. let checkReady = setInterval(() => {
  8843. try {
  8844. iframeDoc = emuIframe.contentDocument || (emuIframe.contentWindow && emuIframe.contentWindow.document);
  8845. } catch(e) {
  8846. clearInterval(checkReady);
  8847. return;
  8848. }
  8849. if (iframeDoc) {
  8850. clearInterval(checkReady);
  8851. try {
  8852. Function('win', 'iframe', '"use strict";' + code)(emuIframe.contentWindow, emuIframe);
  8853. } catch(e) {
  8854. debug(e);
  8855. }
  8856. }
  8857. }, 50);
  8858. }
  8859. if (!lastActiveUrl) lastActiveUrl = location.href;
  8860. emuIframe.src = lastActiveUrl;
  8861. getBody(document).appendChild(emuIframe);
  8862. } else {
  8863. if (emuIframe.src != lastActiveUrl || meetCors) {
  8864. emuIframe.src = lastActiveUrl;
  8865. return;
  8866. }
  8867. checkPage();
  8868. }
  8869. }
  8870.  
  8871. var scrollToResizeInited = false;
  8872. var resizePool = [];
  8873. var scrollingToResize = false;
  8874.  
  8875. function isTouchViewPort(element) {
  8876. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  8877. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  8878. const {
  8879. top,
  8880. right,
  8881. bottom,
  8882. left,
  8883. } = element.getBoundingClientRect();
  8884.  
  8885. return (
  8886. top < viewHeight &&
  8887. left < viewWidth &&
  8888. right > 0 &&
  8889. bottom > 0
  8890. );
  8891. }
  8892.  
  8893. function resizeIframe(iframe, frameDoc, pageEle) {
  8894. if (targetY >= 0) {
  8895. window.scrollTo({ top: targetY, behavior: 'instant'});
  8896. targetY = -1;
  8897. }
  8898. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  8899. if (ruleParser.curSiteRule.smart || forceState === 2) {
  8900. let height = (getBody(frameDoc).scrollHeight || getBody(frameDoc).offsetHeight || 500);
  8901. if (!iframe.style.height || parseInt(iframe.style.height) === 0 || height - parseInt(iframe.style.height) > window.innerHeight) {
  8902. iframe.style.height = height + "px";
  8903. iframe.style.minHeight = iframe.style.height;
  8904. }
  8905. iframe.style.width = "100%";
  8906. frameDoc.documentElement.scrollTop = 0;
  8907. frameDoc.documentElement.scrollLeft = 0;
  8908. } else {
  8909. if (pageEle) {
  8910. if (document.body.scrollWidth) frameDoc.documentElement.style.width = document.body.scrollWidth + "px";
  8911. let fitWidth = ruleParser.curSiteRule.fitWidth !== false;
  8912. let targetElement = pageEle[0];
  8913. if (!targetElement) return;
  8914. if (pageEle.length > 1) {
  8915. targetElement = targetElement.parentNode;
  8916. }
  8917. let scrollHeight = targetElement.scrollHeight || targetElement.offsetHeight || 500;
  8918. iframe.style.height = scrollHeight + "px";
  8919. let scrollTop = 0, scrollLeft = 0;
  8920. getBody(frameDoc).scrollTop = 0;
  8921. getBody(frameDoc).scrollLeft = 0;
  8922. while (targetElement && targetElement.offsetParent) {
  8923. targetElement.offsetParent.scrollTop = targetElement.offsetTop;
  8924. if (targetElement.offsetParent.scrollTop == 0) {
  8925. scrollTop += targetElement.offsetTop;
  8926. }
  8927. if (fitWidth) {
  8928. targetElement.offsetParent.scrollLeft = targetElement.offsetLeft;
  8929. if (targetElement.offsetParent.scrollLeft == 0) {
  8930. scrollLeft += targetElement.offsetLeft;
  8931. }
  8932. }
  8933. targetElement = targetElement.offsetParent;
  8934. }
  8935. frameDoc.documentElement.scrollTop = scrollTop;
  8936. frameDoc.documentElement.scrollLeft = scrollLeft;
  8937. if (frameDoc.documentElement.scrollTop == 0 && frameDoc.documentElement.scrollLeft == 0) {
  8938. getBody(frameDoc).scrollTop += scrollTop;
  8939. getBody(frameDoc).scrollLeft += scrollLeft;
  8940. }
  8941. if (!fitWidth && iframe.style.marginLeft == '0px') {
  8942. iframe.style.width = "100vw";
  8943. iframe.style.maxWidth = "100vw";
  8944. iframe.style.minWidth = "100vw";
  8945. var cWidth = document.body.clientWidth || document.documentElement.clientWidth;
  8946. var iWidth = window.innerWidth;
  8947. iframe.style.marginLeft = -iframe.getBoundingClientRect().left - (iWidth - cWidth) / 2 + "px";
  8948. }
  8949. }
  8950. }
  8951. let newScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  8952. if (newScroll != curScroll) {
  8953. getBody(document).scrollTop = curScroll;
  8954. document.documentElement.scrollTop = curScroll;
  8955. }
  8956. }
  8957.  
  8958. function scrollToResize(e) {
  8959. if (scrollingToResize) return;
  8960. else {
  8961. scrollingToResize = true;
  8962. let resizeHandler = () => {
  8963. let touched = 0;
  8964. for (let i = 0; i < resizePool.length; i++) {
  8965. let resizeArr = resizePool[i];
  8966. let iframe = resizeArr[1]();
  8967. if (isTouchViewPort(iframe)) {
  8968. touched++;
  8969. let pageEle = resizeArr[0]();
  8970. let frameDoc = resizeArr[2]();
  8971. resizeIframe(iframe, frameDoc, pageEle);
  8972. } else if (touched) {
  8973. if (touched == 1) {
  8974. let pageEle = resizeArr[0]();
  8975. let frameDoc = resizeArr[2]();
  8976. resizeIframe(iframe, frameDoc, pageEle);
  8977. }
  8978. break;
  8979. } else if (!iframe.parentNode) {
  8980. resizePool.splice(i, 1);
  8981. break;
  8982. }
  8983. }
  8984. };
  8985. setTimeout(() => {
  8986. scrollingToResize = false;
  8987. }, 300);
  8988. resizeHandler();
  8989. }
  8990. }
  8991.  
  8992. var curForceIframe;
  8993. function forceIframe(url, callback) {
  8994. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  8995. let curIframe = document.createElement('iframe'), iframeDoc, pageElement = null, inAction = true;
  8996. let loadedHandler = () => {
  8997. let getPageEle = () => {
  8998. if (ruleParser.curSiteRule.smart) {
  8999. return null;
  9000. } else {
  9001. if (!pageElement || pageElement.length === 0 || !pageElement[0].offsetParent) {
  9002. pageElement = ruleParser.getPageElement(iframeDoc, curIframe.contentWindow);
  9003. }
  9004. return pageElement;
  9005. }
  9006. };
  9007. resizeIframe(curIframe, iframeDoc, getPageEle());
  9008. let loaded = curIframe.getAttribute("loaded");
  9009. if (loaded == "true") {
  9010. return;
  9011. }
  9012. curIframe.setAttribute("loaded", "true");
  9013. let getIframe = () => {
  9014. return curIframe;
  9015. };
  9016. let getFrameDoc = () => {
  9017. return iframeDoc;
  9018. };
  9019. ruleParser.insertPage(iframeDoc, [], url, ele => {
  9020. callback(curIframe, loaded == "refresh");
  9021. inAction = false;
  9022. }, true);
  9023. if (!loaded) {
  9024. resizePool.push([getPageEle, getIframe, getFrameDoc]);
  9025. }
  9026. };
  9027. let checkIframeTimer = setInterval(() => {
  9028. if (!curIframe.parentNode) {
  9029. clearInterval(checkIframeTimer);
  9030. return curIframe.getAttribute("loaded") == "true" || callback(false);
  9031. }
  9032. }, 500);
  9033. let code = ruleParser.curSiteRule.iframeInit;
  9034. if (code) {
  9035. let checkReady = setInterval(() => {
  9036. try {
  9037. iframeDoc = curIframe.contentDocument || (curIframe.contentWindow && curIframe.contentWindow.document);
  9038. } catch(e) {
  9039. clearInterval(checkReady);
  9040. return;
  9041. }
  9042. if (iframeDoc) {
  9043. clearInterval(checkReady);
  9044. try {
  9045. Function('win', 'iframe', '"use strict";' + code)(curIframe.contentWindow, curIframe);
  9046. } catch(e) {
  9047. debug(e);
  9048. }
  9049. }
  9050. }, 50);
  9051. }
  9052. let waitTime = 300, checkEval;
  9053. ruleParser.runWait((_checkEval, _waitTime) => {
  9054. if (_checkEval) {
  9055. checkEval = _checkEval;
  9056. }
  9057. if (_waitTime) {
  9058. waitTime = _waitTime;
  9059. }
  9060. });
  9061. async function checkIframe() {
  9062. if (checkEval && !await checkEval(iframeDoc)) {
  9063. setTimeout(() => {
  9064. checkIframe();
  9065. }, waitTime);
  9066. return;
  9067. }
  9068. loadedHandler();
  9069. }
  9070. curIframe.name = 'pagetual-iframe';
  9071. curIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  9072. curIframe.frameBorder = '0';
  9073. curIframe.scrolling = "no";
  9074. 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;';
  9075. curIframe.addEventListener("load", async e => {
  9076. clearInterval(checkIframeTimer);
  9077. if (isPause) return callback(false);
  9078. try {
  9079. iframeDoc = curIframe.contentDocument || curIframe.contentWindow.document;
  9080. } catch(e) {
  9081. debug("Stop as cors");
  9082. isPause = true;
  9083. callback(false);
  9084. return;
  9085. }
  9086. let css = ruleParser.curSiteRule.css || rulesData.customCss;
  9087. if (css) {
  9088. let cssArr = css.split("inIframe:");
  9089. if (cssArr && cssArr.length > 1) {
  9090. let styleEle = iframeDoc.createElement("style");
  9091. styleEle.innerHTML = cssArr[1];
  9092. iframeDoc.head.appendChild(styleEle);
  9093. }
  9094. }
  9095. curIframe.style.height = "";
  9096. checkIframe();
  9097. iframeDoc.addEventListener('wheel', e => {
  9098. document.dispatchEvent(new Event('wheel'));
  9099. }, true);
  9100. });
  9101. let checkTimes = 0, findPageEle = false;
  9102. let forceRefresh = e => {
  9103. if (inAction || !iframeDoc) return;
  9104. inAction = true;
  9105. let foundNext = () => {
  9106. document.removeEventListener("scroll", forceRefresh);
  9107. }
  9108. setTimeout(async () => {
  9109. inAction = false;
  9110. if (!ruleParser.nextLinkHref && !isPause) {
  9111. checkTimes++;
  9112. await ruleParser.getNextLink(iframeDoc, true);
  9113. if (ruleParser.nextLinkHref) {
  9114. foundNext();
  9115. if (isLoading) isLoading = false;
  9116. } else if (checkTimes >= 10) {
  9117. foundNext();
  9118. } else if (checkTimes >= 3 && !findPageEle) {
  9119. if (!pageElement) pageElement = ruleParser.getPageElement(iframeDoc, curIframe.contentWindow);
  9120. if (!pageElement) {
  9121. inAction = true;
  9122. curIframe.contentWindow.location.reload();
  9123. } else {
  9124. findPageEle = true;
  9125. }
  9126. }
  9127. } else {
  9128. foundNext();
  9129. }
  9130. }, 100);
  9131. };
  9132. document.addEventListener("scroll", forceRefresh);
  9133. curIframe.src = url;
  9134. curForceIframe = curIframe;
  9135. let insert = ruleParser.getInsert();
  9136. let body = getBody(document);
  9137. let curScroll = body.scrollTop || document.documentElement.scrollTop;
  9138. if (forceState == 2) {
  9139. document.documentElement.appendChild(loadingDiv);
  9140. body.appendChild(curIframe);
  9141. let bodyStyle = getComputedStyle(body);
  9142. if (bodyStyle.display == "flex" || bodyStyle.display == "inline-flex") {
  9143. body.style.flexDirection = "column";
  9144. }
  9145. } else {
  9146. ruleParser.insertElement(curIframe);
  9147. }
  9148. body.scrollTop = curScroll;
  9149. document.documentElement.scrollTop = curScroll;
  9150.  
  9151. if (!scrollToResizeInited) {
  9152. scrollToResizeInited = true;
  9153. document.addEventListener("scroll", scrollToResize);
  9154. }
  9155. return curIframe;
  9156. }
  9157.  
  9158. function loadPageOver() {
  9159. isLoading = false;
  9160. stopScroll = true;
  9161. setTimeout(() => {stopScroll = false;}, 300);
  9162. if (loadingDiv.parentNode) {
  9163. loadingDiv.parentNode.removeChild(loadingDiv);
  9164. }
  9165. if (rate !== 1 && !clickMode) {
  9166. setTimeout(() => {
  9167. if (distToBottom() < bottomGap) {
  9168. nextPage();
  9169. }
  9170. }, 1);
  9171. }
  9172. }
  9173.  
  9174. function checkAutoLoadNum() {
  9175. if (autoLoadNum >= 0) {
  9176. if (autoLoadNum !== 0 && --autoLoadNum === 0) {
  9177. autoLoadNum = -1;
  9178. } else {
  9179. setTimeout(() => nextPage(), 1);
  9180. }
  9181. }
  9182. }
  9183.  
  9184. async function nextPage() {
  9185. if (isPause || isLoading || forceState === 1) return;
  9186. if (ruleParser.curSiteRule.delay) {
  9187. try {
  9188. let checkDelay = ((typeof ruleParser.curSiteRule.delay === 'function') ? ruleParser.curSiteRule.delay : Function('"use strict";' + ruleParser.curSiteRule.delay))();
  9189. if (!checkDelay) return;
  9190. } catch(e) {
  9191. debug(e);
  9192. }
  9193. }
  9194. let nextLink = ruleParser.nextLinkHref;
  9195. if (!nextLink) {
  9196. isLoading = true;
  9197. if (curPage === 1) {
  9198. await ruleParser.getNextLink(document, true);
  9199. nextLink = ruleParser.nextLinkHref;
  9200. }
  9201. if (!nextLink) {
  9202. if (curPage === 1) {
  9203. if (ruleParser.curSiteRule.pinUrl) {
  9204. setTimeout(() => {isLoading = false;}, 500);
  9205. } else if (tryTimes++ < 5) {
  9206. setTimeout(() => {isLoading = false;}, 1000);
  9207. } else {
  9208. ruleParser.findNoNext();
  9209. }
  9210. } else if (!showedLastPageTips) {
  9211. if (rulesData.lastPageTips) {
  9212. showTips(i18n("lastPage"), "", 800);
  9213. }
  9214. showedLastPageTips = true;
  9215. _unsafeWindow.postMessage({
  9216. action: "lastPage",
  9217. command: 'pagetual'
  9218. }, '*');
  9219. }
  9220. return;
  9221. }
  9222. isLoading = false;
  9223. }
  9224. showedLastPageTips = false;
  9225. let pvGallery = document.querySelector("span.pv-gallery-container");
  9226. if (pvGallery && pvGallery.style.display !== "none") return;
  9227. let insert = ruleParser.getInsert();
  9228. if (insert) {
  9229. if (curPage === 1) initView();
  9230. /*if (curPage == 1) {
  9231. window.postMessage({
  9232. command: 'pagetual.insert'
  9233. }, '*');
  9234. }*/
  9235. let isJs = ruleParser.curSiteRule.action == 3 || ruleParser.hrefIsJs(nextLink);
  9236. if (!isJs) {
  9237. emuIframe = null;
  9238. lastActiveUrl = nextLink;
  9239. if (location.protocol === "https:" && /^http:/.test(nextLink)) {
  9240. nextLink = nextLink.replace(/^http/, "https");
  9241. }
  9242. }
  9243. isLoading = true;
  9244. if (curPage !== 1 || !isJs || !ruleParser.curSiteRule.smart) {
  9245. ruleParser.beginLoading(loadingDiv);
  9246. }
  9247. let sleep = ruleParser.curSiteRule.sleep || 0;
  9248. setTimeout(() => {
  9249. if (ruleParser.curSiteRule.pageElementByJs) {
  9250. var over = eles => {
  9251. if (urlChanged || isPause) {
  9252. loadPageOver();
  9253. return;
  9254. }
  9255. if (eles) {
  9256. ruleParser.insertPage(document, eles, nextLink, () => {
  9257. createPageBar(nextLink);
  9258. checkAutoLoadNum();
  9259. }, true);
  9260. } else {
  9261. debug("Stop as no page when get by js");
  9262. isPause = true;
  9263. loadPageOver();
  9264. }
  9265. };
  9266. try {
  9267. ((typeof ruleParser.curSiteRule.pageElementByJs === 'function') ? ruleParser.curSiteRule.pageElementByJs : Function("over", "pageNum",'"use strict";' + ruleParser.curSiteRule.pageElementByJs))(over, curPage);
  9268. } catch(e) {
  9269. debug(e);
  9270. }
  9271. } else if ((forceState === 2 || ruleParser.curSiteRule.action == 2) && !isJs) {
  9272. forceIframe(nextLink, (iframe, refresh) => {
  9273. if (urlChanged || isPause) {
  9274. loadPageOver();
  9275. return;
  9276. }
  9277. if (!refresh) {
  9278. let pageBar = createPageBar(nextLink);
  9279. if (pageBar && iframe && iframe.parentNode) iframe.parentNode.insertBefore(pageBar, iframe);
  9280. }
  9281. loadPageOver();
  9282. checkAutoLoadNum();
  9283. });
  9284. } else if ((forceState === 3 || ruleParser.curSiteRule.action == 1) && !isJs) {
  9285. requestFromIframe(nextLink, async (doc, eles) => {
  9286. if (urlChanged || isPause) {
  9287. loadPageOver();
  9288. return;
  9289. }
  9290. if (eles) {
  9291. await ruleParser.insertPage(doc, eles, nextLink, () => {
  9292. createPageBar(nextLink);
  9293. checkAutoLoadNum();
  9294. }, true);
  9295. } else {
  9296. loadPageOver();
  9297. if (autoLoadNum >= 0) {
  9298. setTimeout(() => nextPage(), 2000);
  9299. }
  9300. }
  9301. });
  9302. } else {
  9303. if (!isJs) {
  9304. requestDoc(nextLink, (eles) => {
  9305. if (urlChanged || isPause) {
  9306. loadPageOver();
  9307. return;
  9308. }
  9309. if (eles) {
  9310. createPageBar(nextLink);
  9311. checkAutoLoadNum();
  9312. } else {
  9313. loadPageOver();
  9314. if (autoLoadNum >= 0) {
  9315. setTimeout(() => nextPage(), 2000);
  9316. }
  9317. }
  9318. });
  9319. } else {
  9320. emuPage((doc, eles) => {
  9321. if (urlChanged || isPause) {
  9322. loadPageOver();
  9323. return;
  9324. }
  9325. if (eles) {
  9326. ruleParser.insertPage(doc, eles, "", () => {
  9327. createPageBar(nextLink);
  9328. checkAutoLoadNum();
  9329. }, true);
  9330. } else {
  9331. loadPageOver();
  9332. if (autoLoadNum >= 0) {
  9333. setTimeout(() => nextPage(), 2000);
  9334. }
  9335. }
  9336. });
  9337. }
  9338. }
  9339. }, sleep);
  9340. }
  9341. }
  9342.  
  9343. function init() {
  9344. if (document.readyState === 'loading' || document.readyState === 'uninitialized') {
  9345. let domReady = e => {
  9346. initRules(() => {
  9347. initPage();
  9348. });
  9349. document.removeEventListener("DOMContentLoaded", domReady, false);
  9350. };
  9351. document.addEventListener("DOMContentLoaded", domReady, false);
  9352. } else {
  9353. initRules(() => {
  9354. initPage();
  9355. });
  9356. }
  9357. }
  9358.  
  9359. function visibilitychangeHandler() {
  9360. document.removeEventListener('visibilitychange', visibilitychangeHandler);
  9361. init();
  9362. }
  9363.  
  9364. setTimeout(() => {
  9365. if (document.hidden) {
  9366. document.addEventListener('visibilitychange', visibilitychangeHandler);
  9367. } else {
  9368. init();
  9369. }
  9370. }, 300);
  9371. })();