东方永页机

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

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

  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.49
  14. // @description Perpetual pages - powerful auto-pager script. Auto fetching next paginated web pages and inserting into current page for infinite scroll. Support thousands of web sites without any rule.
  15. // @description:zh-CN 终极自动翻页 - 加载并拼接下一分页内容至当前页尾,智能适配任意网页
  16. // @description:zh-TW 終極自動翻頁 - 加載並拼接下一分頁內容至當前頁尾,智能適配任意網頁
  17. // @description:ja Webページを自動で読み込み継ぎ足し表示を行うブラウザ拡張です、次のページ付けされた Web ページの自動読み込みと現在のページへの挿入 ルールなしで何千もの Web サイトをサポートします。
  18. // @description:ko 페이지가 매겨진 다음 웹 페이지를 자동으로 로드하고 현재 페이지에 삽입합니다. 규칙 없이 수천 개의 웹 사이트를 지원합니다.
  19. // @description:ru Автоматическая подгрузка следующих страниц и вставка их содержимого в текущую страницу. Поддерживает тысячи сайтов даже с настройками по умолчанию.
  20. // @description:de Automatisches Laden der nächsten paginierten Webseiten und Einfügen in die aktuelle Seite. Unterstützen Sie Tausende von Websites ohne Regeln.
  21. // @description:es Carga automática de las siguientes páginas web paginadas e inserción en la página actual. Admite miles de sitios web sin ninguna regla.
  22. // @description:fr Chargement automatique des pages Web paginées suivantes et insertion dans la page en cours. Prend en charge des milliers de sites Web sans aucune règle.
  23. // @description:it Caricamento automatico delle pagine Web impaginate successive e inserimento nella pagina corrente. Supporta migliaia di siti web senza alcuna regola.
  24. // @author hoothin
  25. // @license MPL-2.0
  26. // @match *://*/*
  27. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAdVBMVEUAAAD3VU33VU32VEz8U073VU32VU33VU32VUz0Uk/3VE32VU32VUz2VU32VU32VU32VU33VU33U0z2VU34Wkv3VE32VUz/mpj/nJj2VUz2VU32VE33VEz2VU32VU32VUz3VE32VEz3VE3/mZf2Vkz2VU3/mpilFFolAAAAJXRSTlMA3Lp/GvTBT5YQLuawZ/DOyZwlPQeKc21N04+FX1bqpm9DNoB4T68ePwAAAitJREFUWMPt1tuasiAUBuCFCG5Rs3QybTPV1/1f4v/3PDkyIojn8x5qBrI+ltAfh32/yysmBKvyXb+njb6bDL9kzTd5SzjDAsYT8nFoGSxYe6BVqoNDp2jFDit25BRgVUAODB4YWcETWVTwVNGiGN5iWtBgg4YMCpsoI38dNunmmWyxUTvbPwwbsYR0fIzZLQ0pTG8eieRmBLMmpdH9uimQEf6TNRnXXKLZHixpJtywLzOgMHtFCqdM64DahHRnOE1dsrekm9wr2WtLcAlpdHwcp1pAJySXYnERclzp4+v19jXdmcTvQUJtz+ZaI4i05/V/UGYrCxbaAsOYoNfIKEQxpqQuzCgJJJ/3f42O8ywEZuMVWi/8hODxGj3GW2b0udkbGULLDOjimAG0S3fLGlBnXQM9irG1CiQdVQi0dqQsOSDlyEEz7Vy9OxxfR71VCXsSB23jMrKJYZXSjw57sqgLn5Z0wolsOCz0RyJkyeYjgz7pwwVq20eboZwtVUl2EnN5gJ50dQZFdryATvABRTr/tJXkUMdaAK5pwtCapwtFLskguwuyMh/Sd9WChQ4sIvIUYSk3PYqQvCQlOC04IfN7PkdjOyRKWhdKXMmiAFt9i3sJ5jxoRuR0vqAghxxwHuqfQE5OHGDKOrwEnqs1DgAZ2e4Eev1d45TN7JfhrQLKgfwMFYAsvp33dXII073aVQLI2gN5S58lfmGnKKFtah7nkgnBZB7zlP7Y/QNiTM6sYNzawwAAAABJRU5ErkJggg==
  28. // @grant GM_xmlhttpRequest
  29. // @grant GM_registerMenuCommand
  30. // @grant GM_notification
  31. // @grant GM_getValue
  32. // @grant GM_setValue
  33. // @grant GM_addStyle
  34. // @grant GM_openInTab
  35. // @grant GM_deleteValue
  36. // @grant GM_info
  37. // @grant GM_setClipboard
  38. // @grant GM.xmlHttpRequest
  39. // @grant GM.registerMenuCommand
  40. // @grant GM.notification
  41. // @grant GM.getValue
  42. // @grant GM.setValue
  43. // @grant GM.addStyle
  44. // @grant GM.openInTab
  45. // @grant GM.deleteValue
  46. // @grant GM.info
  47. // @grant GM.setClipboard
  48. // @supportURL https://github.com/hoothin/UserScripts/issues
  49. // @connect wedata.net
  50. // @connect githubusercontent.com
  51. // @connect ghproxy.com
  52. // @connect hoothin.github.io
  53. // @run-at document-idle
  54. // @connect *
  55. // @contributionURL https://ko-fi.com/hoothin
  56. // @contributionAmount 1
  57. // ==/UserScript==
  58.  
  59. (function() {
  60. 'use strict';
  61.  
  62. const pauseVideo = () => {
  63. setTimeout(() => {
  64. [].forEach.call(document.querySelectorAll("video"), video => {
  65. video.removeAttribute && video.removeAttribute("autoplay");
  66. video.pause && video.pause();
  67. });
  68. }, 1000);
  69. };
  70. if (window.name === 'pagetual-iframe' || (window.frameElement && window.frameElement.name === 'pagetual-iframe')) {
  71. [].forEach.call(document.querySelectorAll("iframe"), iframe => {
  72. iframe.name = 'pagetual-iframe';
  73. });
  74. var domloaded = function() {
  75. window.parent.postMessage('pagetual-iframe:DOMLoaded', '*');
  76. };
  77. if (window.opera) {
  78. document.addEventListener('DOMContentLoaded', domloaded, false);
  79. pauseVideo();
  80. } else {
  81. domloaded();
  82. if (document.readystate === 'complete') {
  83. pauseVideo();
  84. } else {
  85. window.addEventListener('load', () => {
  86. pauseVideo();
  87. }, false);
  88. }
  89. }
  90. if (getComputedStyle(document.documentElement).display === 'none') {
  91. document.documentElement.style.display = 'block';
  92. }
  93. if (document.body && getComputedStyle(document.body).display === 'none') {
  94. document.body.style.display = 'block';
  95. }
  96. return;
  97. }
  98.  
  99. if (window.top !== window.self) {
  100. try {
  101. if (window.self.innerWidth < 300 || window.self.innerHeight < 300) {
  102. return;
  103. }
  104. } catch(e) {
  105. return;
  106. }
  107. }
  108.  
  109. const noRuleTest = false;
  110. const lang = navigator.appName === "Netscape" ? navigator.language : navigator.userLanguage;
  111. const langData = [
  112. {
  113. //Translated by Prankster 199 (vfggf95565).
  114. name: "Arabic",
  115. match: ["ar"],
  116. lang: {
  117. enableDebug: "تمكين تصحيح الأخطاء",
  118. updateNotification: "إشعار بعد تحديث القواعد",
  119. disable: "معطل",
  120. disableSite: "تبديل حالة التعطيل/التفعيل للموقع",
  121. disableSiteTips: "معطل على هذا الموقع",
  122. enableSiteTips: "مفعل على هذا الموقع",
  123. enable: "مفعل",
  124. toTop: "إلى الأعلى",
  125. toBottom: "إلى الأسفل",
  126. current: "الصفحة الحالية",
  127. forceIframe: "إجبار على الانضمام للصفحة التالية",
  128. cancelForceIframe: "إلغاء الانضمام القسري",
  129. configure: "إعداد",
  130. firstUpdate: "انقر هنا لتفعيل القواعد لأول مرة",
  131. update: "تحديث القواعد عبر الإنترنت",
  132. click2update: "انقر لتحديث القواعد من الرابط الآن",
  133. loadNow: "تحميل التالي تلقائيًا",
  134. loadConfirm: "كم عدد الصفحات التي ترغب تحميلها؟ (0 يعني لانهائي)",
  135. noNext: "لم يتم العثور على رابط الصفحة التالية، يرجى إنشاء قاعدة جديدة",
  136. passSec: "تم التحديث منذ #t# ثانية",
  137. passMin: "تم التحديث منذ #t# دقيقة",
  138. passHour: "تم التحديث منذ #t# ساعة",
  139. passDay: "تم التحديث منذ #t# يوم",
  140. cantDel: "لا يمكن حذف القواعد المدمجة",
  141. confirmDel: "هل أنت متأكد من حذف هذه القاعدة؟",
  142. updateSucc: "تم التحديث بنجاح",
  143. beginUpdate: "بدأ التحديث، يرجى الانتظار لحظة",
  144. customUrls: "استيراد رابط قاعدة Pagetual أو AutoPagerize، رابط واحد لكل سطر",
  145. customRules: "إدخال القواعد المخصصة. <a href='#t#'>✍️ساهم بالقواعد</a>",
  146. save: "حفظ",
  147. /* From the creator hoothin :
  148. "Shojo Now Loading..." is a meme that refers to the game loading text in the Japanese Touhou (東方) game series. */
  149. loadingText: "جارٍ التحميل...",
  150. opacity: "الشفافية",
  151. opacityPlaceholder: "0: إخفاء الفاصل",
  152. hideBar: "إخفاء الفاصل التصفحي",
  153. hideBarButNoStop: "إخفاء، لكن لا تتوقف",
  154. dbClick2Stop: "انقر مزدوج على المساحة الفارغة للإيقاف",
  155. sortTitle: "يتم تفعيل الفرز بعد التحديث التالي للقواعد",
  156. autoRun: "تمكين تلقائي (وضع القائمة السوداء)",
  157. autoLoadNum: "عدد صفحات التحميل المسبق",
  158. turnRate: "الانتقال للصفحة التالية عندما تكون المسافة أقل من 【X】 مرات ارتفاع الصفحة من التذييل",
  159. inputPageNum: "أدخل رقم الصفحة للانتقال",
  160. enableHistory: "كتابة سجل التصفح بعد تحويل الصفحة",
  161. enableHistoryAfterInsert: "كتابة سجل التصفح فورًا بعد الدمج، أو بعد التصفح",
  162. contentVisibility: "التنقل التلقائي لرؤية المحتوى, لتحسين أداء العرض",
  163. initRun: "الانتقال بين الصفحات فور الفتح",
  164. preload: "تحميل الصفحة التالية مسبقًا لتسريع الأداء",
  165. click2ImportRule: "انقر لاستيراد رابط القواعد الأساسية، ثم انتظر حتى يكتمل التحديث",
  166. forceAllBody: "دمج كامل الصفحة كإطار؟",
  167. openInNewTab: "فتح الروابط الإضافية في علامة تبويب جديدة",
  168. importSucc: "تم الاستيراد بنجاح",
  169. import: "استيراد",
  170. editCurrent: "تحرير القاعدة للحالية",
  171. editBlacklist: "تحرير عناوين القائمة السوداء، سطر بسطر، دعم؟ * للرموز المتحركة",
  172. upBtnImg: "أيقونة العودة إلى الأعلى",
  173. downBtnImg: "أيقونة الانتقال إلى الأسفل",
  174. sideControllerIcon: "أيقونة الشريط الجانبي",
  175. loadingTextTitle: "تحميل النص",
  176. dbClick2StopCtrl: "مفتاح Ctrl",
  177. dbClick2StopAlt: "مفتاح Alt",
  178. dbClick2StopShift: "مفتاح Shift",
  179. dbClick2StopMeta: "مفتاح Meta",
  180. dbClick2StopKey: "مفاتيح الاختصار",
  181. pageElementCss: "نمط مخصص لعناصر الصفحة الرئيسية",
  182. customCss: "مخصص بالكامل CSS نمط",
  183. firstAlert: "لم تستورد القاعدة الأساسية بعد، يرجى اختيار القاعدة المناسبة للاستيراد",
  184. picker: "محدد عناصر الصفحة Pagetual",
  185. closePicker: "إغلاق محدد Pagetual",
  186. pickerPlaceholder: "محدد العناصر، اتركه فارغًا إذا كنت لا تعرف",
  187. pickerCheck: "تحقق من المحدد ونسخ",
  188. switchSelector: "انقر للتبديل بين العناصر",
  189. gotoEdit: "اذهب لتحرير القاعدة بالمحدد الحالي",
  190. manualMode: "تعطيل الدمج/الربط، واستخدام مفتاح الاتجاه الأيمن يدويًا للتمرير، واستخدام مفتاح السهم الأيسر للرجوع",
  191. clickMode: "تعطيل الدمج/الربط، عند التمرير إلى نهاية الصفحة، سيتم النقر تلقائيًا على الصفحة التالية",
  192. pageBarMenu: "انقر على مركز شريط الصفحة لفتح قائمة التحديد",
  193. nextSwitch: "تبديل الرابط التالي",
  194. arrowToScroll: "انقر على مفتاح السهم الأيمن للتمرير التالي ومفتاح السهم الأيسر للتمرير السابق",
  195. sideController: "عرض شريط التحكم في التصفح الترقيم في الشريط الجانبي",
  196. sideControllerScroll: "تبديل التمرير",
  197. sideControllerAlways: "عرض دائمًا",
  198. hideLoadingIcon: "إخفاء رمز التحميل",
  199. hideBarArrow: "إخفاء سهم شريط الصفحة",
  200. duplicate: "تم تثبيت Pagetual مكرر، تحقق من مدير النصوص البرمجية الخاص بك!",
  201. forceStateIframe: "تضمين الصفحة بالكامل كإطار",
  202. forceStateDynamic: "تحميل المحتوى الديناميكي عبر الإطار",
  203. forceStateDisable: "تعطيل تحويل الصفحات على هذا الموقع",
  204. autoScrollRate: "سرعة التمرير (1~1000)",
  205. disableAutoScroll: "إيقاف التمرير التلقائي",
  206. enableAutoScroll: "تمكين التمرير التلقائي",
  207. toggleAutoScroll: "تبديل التمرير التلقائي",
  208. ruleRequest: "طلب قاعدة",
  209. page: "صفحة ",
  210. prevPage: "الصفحة السابقة",
  211. nextPage: "الصفحة التالية",
  212. errorRulesMustBeArray: "يجب أن تكون القواعد مصفوفة!",
  213. errorJson: "خطأ في JSON، تحقق مرة أخرى!",
  214. editSuccess: "تم التحرير بنجاح",
  215. errorWrongUrl: "عنوان URL خاطئ، تحقق مرة أخرى!",
  216. errorAlreadyExists: "موجود بالفعل!",
  217. settingsSaved: "تم حفظ الإعدادات، قم بالتحديث لعرض",
  218. iframe: "إطار",
  219. dynamic: "ديناميكي",
  220. reloadPage: "اكتمل التحرير، إعادة تحميل الصفحة الآن؟",
  221. copied: "تم النسخ",
  222. noValidContent: "لم يتم الكشف عن محتوى صالح، قد يكون الإجراء Captcha مطلوبًا، انقر لعرض",
  223. outOfDate: "النص البرمجي قديم، قم بالتحديث إلى الإصدار الأحدث في الوقت المناسب!",
  224. hideBarTips: "إخفاء شريط التحكم في التصفح الترقيم ، والتبديل لوضع كامل الصفحة",
  225. setConfigPage: "تعيين الصفحة الحالية كصفحة الإعداد الافتراضية",
  226. wedata2github: "تغيير عنوان الويب داتا إلى العنوان البديل المرآة, في مستودع جيت هاب",
  227. addOtherProp: "إضافة خاصية قاعدة",
  228. addNextSelector: "إضافة محتوى المحدد كـ nextLink",
  229. addPageSelector: "إضافة محتوى المحدد كـ pageElement",
  230. propName: "أدخل اسم خاصية القاعدة",
  231. propValue: "أدخل قيمة خاصية القاعدة",
  232. customFirst: "تجاهل ذاكرة التخزين المؤقت للقواعد المخصصة المحلية",
  233. rulesExample: "مثال على القواعد",
  234. lastPage: "تم الوصول إلى الصفحة الأخيرة",
  235. lastPageTips: "عرض تلميحات عند الوصول إلى الصفحة الأخيرة"
  236. }
  237. },
  238. {
  239. name: "English",
  240. match: ["en"],
  241. lang: {
  242. enableDebug: "Enable debug output",
  243. updateNotification: "Notification after rules updated",
  244. disable: "Disable",
  245. disableSite: "Toggle disabled state",
  246. disableSiteTips: "Disabled on this site",
  247. enableSiteTips: "Enabled on this site",
  248. enable: "Enable",
  249. toTop: "To Top",
  250. toBottom: "To Bottom",
  251. current: "Current Page",
  252. forceIframe: "Force to join next page",
  253. cancelForceIframe: "Cancel Force join",
  254. configure: "Configure",
  255. firstUpdate: "Click here to initialize the rules",
  256. update: "Update online rules",
  257. click2update: "Click to update rules from url now",
  258. loadNow: "Load next automatically",
  259. loadConfirm: "How much pages do you want to load? (0 means infinite)",
  260. noNext: "No next link found, please create a new rule",
  261. passSec: "Updated #t# seconds ago",
  262. passMin: "Updated #t# minutes ago",
  263. passHour: "Updated #t# hours ago",
  264. passDay: "Updated #t# days ago",
  265. cantDel: "Can't delete buildin rules",
  266. confirmDel: "Are you sure you want to delete this rule?",
  267. updateSucc: "Update succeeded",
  268. beginUpdate: "Begin update, wait a minute please",
  269. customUrls: "Import Pagetual or AutoPagerize rule url, One url per line",
  270. customRules: "Input custom rules. <a href='#t#'>✍️Contribute rules</a>",
  271. save: "Save",
  272. loadingText: "Shojo Now Loading...",
  273. opacity: "Opacity",
  274. opacityPlaceholder: "0: hide spacer",
  275. hideBar: "Hide the paging spacer",
  276. hideBarButNoStop: "Hide but not stop",
  277. dbClick2Stop: "Double-click on the blank space to pause",
  278. sortTitle: "Sorting takes effect after the next rule update",
  279. autoRun: "Auto enable (blacklist mode)",
  280. autoLoadNum: "Amount for preload pages",
  281. turnRate: "Turn the next page when it's less than 【X】 times page height from the footer",
  282. inputPageNum: "Enter page number to jump",
  283. enableHistory: "Write browsing history after page turning",
  284. enableHistoryAfterInsert: "Write browsing history immediately after splicing, otherwise write after browsing",
  285. contentVisibility: "Automatically switch contentVisibility to improve rendering performance",
  286. initRun: "Turn pages immediately after opening",
  287. preload: "Preload next page for speeding up",
  288. click2ImportRule: "Click to import base rules link, then wait until the update is complete: ",
  289. forceAllBody: "Join full body of page?",
  290. openInNewTab: "Open urls of additions in new tab",
  291. importSucc: "Import completed",
  292. import: "Import",
  293. editCurrent: "Edit rule for current",
  294. editBlacklist: "Edit the blacklist urls, line by line, Support ? * for wildcard",
  295. upBtnImg: "Icon of back to top",
  296. downBtnImg: "Icon of go to footer",
  297. sideControllerIcon: "Icon of sidebar",
  298. loadingTextTitle: "Loading text",
  299. dbClick2StopCtrl: "Ctrl key",
  300. dbClick2StopAlt: "Alt key",
  301. dbClick2StopShift: "Shift key",
  302. dbClick2StopMeta: "Meta key",
  303. dbClick2StopKey: "Shortcut key",
  304. pageElementCss: "Custom style for main page elements",
  305. customCss: "Custom complete css",
  306. firstAlert: "You have not imported the base rule, please select the appropriate rule to import",
  307. picker: "Pagetual page element picker",
  308. closePicker: "Close Pagetual picker",
  309. pickerPlaceholder: "Element selector, Leave empty if you have no idea",
  310. pickerCheck: "Check selector and copy",
  311. switchSelector: "Click to switch element",
  312. gotoEdit: "Go to edit rule with current selector",
  313. manualMode: "Disable splicing, manually turn pages with the right arrow keys (or dispatch event 'pagetual.next')",
  314. clickMode: "Disable splicing, automatically click the next page when scrolling to the end of the page",
  315. pageBarMenu: "Click the center of the page bar to open the picker menu",
  316. nextSwitch: "Switch next link",
  317. arrowToScroll: "Press left arrow key to scroll prev and right arrow key to scroll next",
  318. sideController: "Display the paging control bar in the sidebar",
  319. sideControllerScroll: "Scroll toggle",
  320. sideControllerAlways: "Always show",
  321. hideLoadingIcon: "Hide loading animation",
  322. hideBarArrow: "Hide arrow for page bar",
  323. duplicate: "Duplicate Pagetual have been installed, check your script manager!",
  324. forceStateIframe: "Embed full page as iframe",
  325. forceStateDynamic: "Load dynamic content via iframe",
  326. forceStateDisable: "Disable page turning on this site",
  327. autoScrollRate: "Scroll speed (1~1000)",
  328. disableAutoScroll: "Stop Auto Scroll",
  329. enableAutoScroll: "Enable Auto Scroll",
  330. toggleAutoScroll: "Toggle Auto Scroll",
  331. ruleRequest: "Rule Request",
  332. page: "Page ",
  333. prevPage: "Prev page",
  334. nextPage: "Next page",
  335. errorRulesMustBeArray: "Rules must be a Array!",
  336. errorJson: "JSON error, check again!",
  337. editSuccess: "Edit successfully",
  338. errorWrongUrl: "Wrong url, check again!",
  339. errorAlreadyExists: "Already exists!",
  340. settingsSaved: "The settings are saved, refresh to view",
  341. iframe: "Iframe",
  342. dynamic: "Dynamic",
  343. reloadPage: "Edit completed, reload page now?",
  344. copied: "Copied",
  345. noValidContent: "No valid content detected, Captcha action may be required, click to view",
  346. outOfDate: "The script is outdated, update to the latest version in time!",
  347. hideBarTips: "Hide the pagination bar, toggle immersive experience",
  348. setConfigPage: "Set current page as the default configuration page",
  349. wedata2github: "Change the wedata address to the mirror address in the github repository",
  350. addOtherProp: "Add rule property",
  351. addNextSelector: "Add selector content as nextLink",
  352. addPageSelector: "Add selector content as pageElement",
  353. propName: "Enter rule property name",
  354. propValue: "Enter rule property value",
  355. customFirst: "Ignore cache for local custom rules",
  356. rulesExample: "Rules Example",
  357. lastPage: "Reached the last page",
  358. lastPageTips: "Show tips when reaching the last page"
  359. }
  360. },
  361. {
  362. name: "简体中文",
  363. match: ["zh-CN", "zh-SG"],
  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 规则 url,一行一条",
  393. customRules: "输入【东方永页机】格式的自定义规则 <a href='#t#'>✍️贡献规则</a>",
  394. save: "保存设置",
  395. loadingText: "少女祈祷中...",
  396. opacity: "不透明值",
  397. opacityPlaceholder: "0: 隐藏分隔条",
  398. hideBar: "隐藏分页隔条",
  399. hideBarButNoStop: "隐藏但不停止",
  400. dbClick2Stop: "空白处双击暂停翻页",
  401. sortTitle: "排序在下次更新规则后生效",
  402. autoRun: "自动启用,否则为白名单模式",
  403. autoLoadNum: "自动加载指定页数",
  404. turnRate: "距离页尾【X】倍页面高度时就开始翻页",
  405. inputPageNum: "输入页码跳转",
  406. enableHistory: "翻页后写入历史记录",
  407. enableHistoryAfterInsert: "拼接后立即写入历史记录,否则浏览完毕后再行写入",
  408. contentVisibility: "自动切换 contentVisibility,提升渲染性能",
  409. initRun: "打开页面后立即尝试翻页,否则滚动至页尾再翻页",
  410. preload: "翻页前预读下一页,加速浏览",
  411. click2ImportRule: "点击下方任意一条添加规则库,并静待更新成功,请预先打开链接确认能正常访问再行导入:",
  412. forceAllBody: "是否拼接整个页面?",
  413. openInNewTab: "使拼接页面的内容在新页面打开",
  414. importSucc: "导入成功",
  415. import: "导入",
  416. editCurrent: "编辑此站规则",
  417. editBlacklist: "编辑黑名单网址,一行一条,支持? *通配符与正则",
  418. upBtnImg: "回到页首图标",
  419. downBtnImg: "前往页尾图标",
  420. sideControllerIcon: "侧边栏图标",
  421. loadingTextTitle: "加载中文字",
  422. dbClick2StopCtrl: "Ctrl",
  423. dbClick2StopAlt: "Alt",
  424. dbClick2StopShift: "Shift",
  425. dbClick2StopMeta: "Meta",
  426. dbClick2StopKey: "快捷键",
  427. pageElementCss: "页面主体框架的样式",
  428. customCss: "自定义 css",
  429. firstAlert: "你还未导入规则库,请选择合适的规则库导入哦",
  430. picker: "东方永页机主体元素抓取器",
  431. closePicker: "关闭东方永页机抓取器",
  432. pickerPlaceholder: "元素选择器,没想法建议留空",
  433. pickerCheck: "检查你编辑的选择器并复制",
  434. switchSelector: "点击切换元素",
  435. gotoEdit: "使用当前的选择器前往编辑规则",
  436. manualMode: "禁用拼接,手动用右方向键翻页,可使用左方向键返回",
  437. clickMode: "禁用拼接,滚动至页尾时自动点击下一页",
  438. pageBarMenu: "点击分隔条中间弹出菜单",
  439. nextSwitch: "切换其他页码",
  440. arrowToScroll: "左方向键滚动至上一页,右方向键滚动至下一页",
  441. sideController: "在侧边显示翻页控制栏",
  442. sideControllerScroll: "滚动开关",
  443. sideControllerAlways: "始终显示",
  444. hideLoadingIcon: "隐藏加载动画",
  445. hideBarArrow: "隐藏分隔条定位箭头",
  446. duplicate: "检测到永页机重复安装,请删除其他脚本管理器中的永页机!",
  447. forceStateIframe: "以 iframe 嵌入整页",
  448. forceStateDynamic: "通过 iframe 加载动态内容后取出",
  449. forceStateDisable: "在此站禁用",
  450. autoScrollRate: "滚动速度(1~1000)",
  451. disableAutoScroll: "停止自动滚动",
  452. enableAutoScroll: "开启自动滚动",
  453. toggleAutoScroll: "自动滚动开关",
  454. ruleRequest: "适配请求",
  455. page: "Page ",
  456. prevPage: "上一页",
  457. nextPage: "下一页",
  458. errorRulesMustBeArray: "规则必须为数组形式!",
  459. errorJson: "JSON 格式有错,请重新检查!",
  460. editSuccess: "编辑成功",
  461. errorWrongUrl: "URL 错误, 请重新检查!",
  462. errorAlreadyExists: "已经存在!",
  463. settingsSaved: "设置已保存,刷新后生效",
  464. iframe: "强制拼接",
  465. dynamic: "动态加载",
  466. reloadPage: "编辑完成,是否立即刷新页面?",
  467. copied: "已复制",
  468. noValidContent: "没有检测到有效内容,可能需要人机校验,点击查看",
  469. outOfDate: "脚本已过时,请及时更新到最新版本!",
  470. hideBarTips: "隐藏分页隔条,沉浸式体验",
  471. setConfigPage: "将当前页面设为默认配置页",
  472. wedata2github: "将 wedata 地址更改为 github 仓库内的镜像地址",
  473. addOtherProp: "添加规则属性",
  474. addNextSelector: "添加选择器内容为 nextLink",
  475. addPageSelector: "添加选择器内容为 pageElement",
  476. propName: "输入规则属性名",
  477. propValue: "输入规则属性值",
  478. customFirst: "为本地自定义规则忽略缓存",
  479. rulesExample: "自定义规则详解",
  480. lastPage: "已到达最后一页",
  481. lastPageTips: "到达最后一页时进行提示"
  482. }
  483. },
  484. {
  485. name: "正體中文",
  486. match: ["zh-TW", "zh-HK"],
  487. lang: {
  488. enableDebug: "調試模式,輸出信息至控制台",
  489. updateNotification: "規則更新后提示",
  490. disable: "暫時禁用",
  491. disableSite: "站點禁用開關",
  492. disableSiteTips: "已在此站禁用",
  493. enableSiteTips: "已在此站啟用",
  494. enable: "啟用自動翻頁",
  495. toTop: "回到頂部",
  496. toBottom: "前往頁尾",
  497. current: "當前頁",
  498. forceIframe: "強制拼接",
  499. cancelForceIframe: "取消强制拼接",
  500. configure: "打開配置頁面",
  501. firstUpdate: "點擊此處初始化規則",
  502. update: "更新在綫規則",
  503. click2update: "點擊立即更新規則",
  504. loadNow: "立即翻頁",
  505. loadConfirm: "要翻几頁?(0為不間斷)",
  506. noNext: "沒有找到下一頁,請新建規則",
  507. passSec: "更新于 #t# 秒前",
  508. passMin: "更新于 #t# 分鐘前",
  509. passHour: "更新于 #t# 小時前",
  510. passDay: "更新于 #t# 天前",
  511. cantDel: "無法刪除内置規則",
  512. confirmDel: "是否確認要刪除此規則?",
  513. updateSucc: "更新成功",
  514. beginUpdate: "正在更新,請稍候",
  515. customUrls: "導入 Pagetual 或 AutoPagerize 規則 url,一行一條",
  516. customRules: "輸入【東方永頁機】格式的自定義規則 <a href='#t#'>✍️貢獻規則</a>",
  517. save: "存儲設置",
  518. loadingText: "少女祈禱中...",
  519. opacity: "不透明值",
  520. opacityPlaceholder: "0: 隱藏分隔條",
  521. hideBar: "隱藏分頁隔條",
  522. hideBarButNoStop: "隱藏但不停止",
  523. dbClick2Stop: "空白處雙擊暫停翻頁",
  524. sortTitle: "排序在下次更新規則後生效",
  525. autoRun: "自動啓用,否則為白名單模式",
  526. autoLoadNum: "自動加載指定頁數",
  527. turnRate: "距離頁尾【X】倍頁面高度時就開始翻頁",
  528. inputPageNum: "輸入頁碼跳轉",
  529. enableHistory: "翻頁后寫入歷史記錄",
  530. enableHistoryAfterInsert: "拼接後立即寫入歷史記錄,否則瀏覽完畢後再行寫入",
  531. contentVisibility: "自動切換 contentVisibility,提升渲染性能",
  532. initRun: "打開頁面后立即嘗試翻頁,否則滾動至頁尾再翻頁",
  533. preload: "翻頁前預讀下一頁,加速瀏覽",
  534. click2ImportRule: "點擊下方添加特殊規則庫,并靜待更新成功:",
  535. forceAllBody: "是否拼接整個頁面?",
  536. openInNewTab: "使拼接頁面的内容在新頁面打開",
  537. importSucc: "導入成功",
  538. import: "導入",
  539. editCurrent: "編輯此站規則",
  540. editBlacklist: "編輯黑名單網址,一行一條,支持? *通配符與正則",
  541. upBtnImg: "回到頁首圖標",
  542. downBtnImg: "前往頁尾圖標",
  543. sideControllerIcon: "側邊欄圖標",
  544. loadingTextTitle: "加載中文字",
  545. dbClick2StopCtrl: "Ctrl",
  546. dbClick2StopAlt: "Alt",
  547. dbClick2StopShift: "Shift",
  548. dbClick2StopMeta: "Meta",
  549. dbClick2StopKey: "快捷鍵",
  550. pageElementCss: "頁面主體框架的樣式",
  551. customCss: "自定義 css",
  552. firstAlert: "你還未導入規則庫,請選擇合適的規則庫導入哦",
  553. picker: "東方永頁機主體元素抓取器",
  554. closePicker: "關閉東方永頁機抓取器",
  555. pickerPlaceholder: "元素選擇器,沒想法建議留空",
  556. pickerCheck: "檢查你編輯的選擇器並複製",
  557. switchSelector: "點擊切換元素",
  558. gotoEdit: "使用當前的選擇器前往編輯規則",
  559. manualMode: "禁用拼接,手動用右方向鍵翻頁,左方向鍵返回",
  560. clickMode: "禁用拼接,滾動至頁尾時自動點擊下一頁",
  561. pageBarMenu: "點擊分隔條中間彈出菜單",
  562. nextSwitch: "切換其他頁碼",
  563. arrowToScroll: "左方向鍵滾動至上一頁,右方向鍵滾動至下一頁",
  564. sideController: "在側邊顯示翻頁控制欄",
  565. sideControllerScroll: "滾燈開關",
  566. sideControllerAlways: "始終顯示",
  567. hideLoadingIcon: "隱藏加載動畫",
  568. hideBarArrow: "隱藏分隔條定位箭頭",
  569. duplicate: "檢測到永頁機重複安裝,請刪除其他腳本管理器中的永頁機!",
  570. forceStateIframe: "以 iframe 嵌入整頁",
  571. forceStateDynamic: "通過 iframe 加載動態內容後取出",
  572. forceStateDisable: "在此站禁用",
  573. autoScrollRate: "滾動速度(1~1000)",
  574. disableAutoScroll: "停止自動滾動",
  575. enableAutoScroll: "開啟自動滾動",
  576. toggleAutoScroll: "自動滾動開關",
  577. ruleRequest: "適配請求",
  578. page: "Page ",
  579. prevPage: "上一頁",
  580. nextPage: "下一頁",
  581. errorRulesMustBeArray: "規則必須為陣列形式!",
  582. errorJson: "JSON 格式有錯,請重新檢查!",
  583. editSuccess: "編輯成功",
  584. errorWrongUrl: "URL 錯誤, 請重新檢查!",
  585. errorAlreadyExists: "已經存在!",
  586. settingsSaved: "設置已保存,刷新後生效",
  587. iframe: "強制拼接",
  588. dynamic: "動態加載",
  589. reloadPage: "編輯完成,是否立即刷新頁面?",
  590. copied: "已復制",
  591. noValidContent: "沒有檢測到有效内容,可能需要人機校驗,點擊查看",
  592. outOfDate: "脚本已過時,請及時更新到最新版本!",
  593. hideBarTips: "隱藏分頁隔條,沉浸式體驗",
  594. setConfigPage: "將當前頁面設為默認配置頁",
  595. wedata2github: "將 wedata 地址更改為 github 倉庫內的鏡像地址",
  596. addOtherProp: "添加規則屬性",
  597. addNextSelector: "添加選擇器內容為 nextLink",
  598. addPageSelector: "添加選擇器內容為 pageElement",
  599. propName: "輸入規則屬性名",
  600. propValue: "輸入規則屬性值",
  601. customFirst: "為本地自定義規則忽略緩存",
  602. rulesExample: "自定義規則詳解",
  603. lastPage: "已到達最後一頁",
  604. lastPageTips: "到達最後一頁時進行提示"
  605. }
  606. },
  607. {
  608. name: "日本語",
  609. match: ["ja"],
  610. lang: {
  611. enableDebug: "デバッグモード",
  612. updateNotification: "ルール更新後の通知",
  613. disable: "一時的に無効",
  614. disableSite: "無効状態の切り替え",
  615. disableSiteTips: "このサイトで既に無効になっています",
  616. enableSiteTips: "このサイトで既に有効になっています",
  617. enable: "ページめくりを有効にする",
  618. toTop: "トップに戻る",
  619. toBottom: "ページの下部に移動",
  620. current: "現在のページ",
  621. forceIframe: "強制ステッチ",
  622. cancelForceIframe: "強制ステッチをキャンセル",
  623. configure: "設定ページを開く",
  624. firstUpdate: "ここをクリックしてルールを初期化します",
  625. update: "更新ルール",
  626. click2update: "今すぐルールを更新してください",
  627. loadNow: "今すぐページをめくる",
  628. loadConfirm: "数ページめくりたいですか?(0は途切れない)",
  629. noNext: "次のページが見つかりません、新しいルールを作成してください",
  630. passSec: "#t#秒前に更新",
  631. passMin: "#t#分前に更新",
  632. passHour: "#t#時間前に更新",
  633. passDay: "#t#日前に更新",
  634. cantDel: "組み込みルールを削除できません",
  635. confirmDel: "このルールを削除してもよろしいですか?",
  636. updateSucc: "更新に成功しました",
  637. beginUpdate: "更新中、お待ちください",
  638. customUrls: "インポートルールのURL、1行に1つ",
  639. customRules: "【東方永頁機】の形式でカスタムルールを入力してください <a href='#t#'>✍️寄稿ルール</a>",
  640. save: "設定を保存",
  641. loadingText: "少女祈祷中...",
  642. opacity: "不透明値",
  643. opacityPlaceholder: "0: 隠す",
  644. hideBar: "ページ区切り文字を非表示にします",
  645. hideBarButNoStop: "非表示にするが停止しない",
  646. dbClick2Stop: "空白部分をダブルクリックしてページめくりを一時停止します",
  647. sortTitle: "並べ替えは、次のルールの更新後に有効になります",
  648. autoRun: "自動的に有効",
  649. autoLoadNum: "指定したページ数を自動的に読み込みます",
  650. turnRate: "ページの端からページの高さの【X】倍になったらページをめくる",
  651. inputPageNum: "ジャンプするページ番号を入力",
  652. enableHistory: "ページめくり後の履歴を書く",
  653. enableHistoryAfterInsert: "スプライシングの直後に履歴レコードを書き込みます。それ以外の場合は、閲覧後に書き込みます",
  654. contentVisibility: "contentVisibility を自動的に切り替えてレンダリング パフォーマンスを向上させる",
  655. initRun: "Webページを開いた直後にページをめくる",
  656. preload: "事前に次のページを読む",
  657. click2ImportRule: "以下をクリックして、ルールベースを追加します:",
  658. forceAllBody: "フルページ埋め込み?",
  659. openInNewTab: "スプライスされたページのコンテンツを新しいページで開きます",
  660. importSucc: "インポート完了",
  661. import: "インポート",
  662. editCurrent: "現在のルールの編集",
  663. editBlacklist: "ブラックリストのURLを編集し、1行ずつ、サポート? *ワイルドカード",
  664. upBtnImg: "トップアイコンに戻る",
  665. downBtnImg: "フッターアイコンに移動",
  666. sideControllerIcon: "サイドバー アイコン",
  667. loadingTextTitle: "テキストをロード",
  668. dbClick2StopCtrl: "Ctrlキー",
  669. dbClick2StopAlt: "Altキー",
  670. dbClick2StopShift: "Shiftキー",
  671. dbClick2StopMeta: "Metaキー",
  672. dbClick2StopKey: "Shortcutキー",
  673. pageElementCss: "ページ本文フレームの STYLE",
  674. customCss: "カスタム css",
  675. firstAlert: "ルールベースをインポートしていないため、インポートする適切なルールベースを選択してください",
  676. picker: "Pagetualページ要素ピッカー",
  677. closePicker: "Pagetualピッカーを閉じる",
  678. pickerPlaceholder: "わからない場合は空のままにしてください",
  679. pickerCheck: "セレクターをチェックしてコピー",
  680. switchSelector: "クリックして要素を切り替えます",
  681. gotoEdit: "現在のセレクターでルールを編集する",
  682. manualMode: "スプライシングを無効にします。手動で右の矢印キーを使用してページをめくります",
  683. clickMode: "スティッチングを無効にします。ページの最後までスクロールすると、次のページが自動的にクリックされます",
  684. pageBarMenu: "ページバーの中央をクリックしてメニューをポップアップ表示",
  685. nextSwitch: "次のページに切り替え",
  686. arrowToScroll: "左矢印キーで前へ、右矢印キーで次へ",
  687. sideController: "サイドバーにページング コントロール バーを表示する",
  688. sideControllerScroll: "スクロール スイッチ",
  689. sideControllerAlways: "常に表示",
  690. hideLoadingIcon: "読み込み中のアニメーションを隠す",
  691. hideBarArrow: "分割線の位置矢印を隠す",
  692. duplicate: "Pagetual の重複インストールが検出されました。他のスクリプト マネージャで永続的なページ マシンを削除してください!",
  693. forceStateIframe: "iframe にページ全体を埋め込む",
  694. forceStateDynamic: "iframe 経由で動的コンテンツを読み込む",
  695. forceStateDisable: "このステーションでのページめくりを無効にする",
  696. autoScrollRate: "スクロール速度 (1~1000)",
  697. disableAutoScroll: "自動スクロールを停止します",
  698. EnableAutoScroll: "自動スクロールを有効にする",
  699. toggleAutoScroll: "自動スクロールの切り替え",
  700. ruleRequest: "ルール要求",
  701. page: "Page ",
  702. prevPage: "Prev page",
  703. nextPage: "Next page",
  704. errorRulesMustBeArray: "Rules must be a Array!",
  705. errorJson: "JSON error, check again!",
  706. editSuccess: "Edit successfully",
  707. errorWrongUrl: "Wrong url, check again!",
  708. errorAlreadyExists: "Already exists!",
  709. settingsSaved: "The settings are saved, refresh to view",
  710. iframe: "Iframe",
  711. dynamic: "Dynamic",
  712. reloadPage: "Edit completed, reload page now?",
  713. copied: "Copied",
  714. noValidContent: "有効なコンテンツが検出されませんでした。クリックして表示",
  715. outOfDate: "スクリプトが古くなっています。最新バージョンに更新してください。",
  716. hideBarTips: "ページネーション バーを非表示にします。没入型エクスペリエンス",
  717. setConfigPage: "現在のページをデフォルト設定ページとして設定",
  718. wedata2github: "wedata アドレスを github ウェアハウスのミラー アドレスに変更",
  719. addOtherProp: "ルールプロパティを追加",
  720. addNextSelector: "セレクターのコンテンツを nextLink として追加",
  721. addPageSelector: "セレクタ コンテンツを pageElement として追加",
  722. propName: "ルールのプロパティ名を入力してください",
  723. propValue: "ルールのプロパティ値を入力してください",
  724. customFirst: "ローカルカスタムルールのキャッシュを無視する",
  725. rulesExample: "カスタムルールの詳しい説明",
  726. lastPage: "最後のページに到達しました",
  727. lastPageTips: "最後のページに到達した時にヒントを表示する"
  728. }
  729. },
  730. {
  731. name: "Русский",
  732. match: ["ru", "ru-RU"],
  733. lang: {
  734. enableDebug: "Включить отладку",
  735. updateNotification: "Уведомление после обновления правила",
  736. disable: "Выключить",
  737. disableSite: "Включить/выключить на сайте",
  738. disableSiteTips: "Выключено для этого сайта",
  739. enableSiteTips: "Включено для этого сайта",
  740. enable: "Включить",
  741. toTop: "Наверх",
  742. toBottom: "Вниз",
  743. current: "Текущая страница",
  744. forceIframe: "Подгрузить ещё страницу",
  745. cancelForceIframe: "Отменить подгрузку",
  746. configure: "Настройки",
  747. firstUpdate: "Нажмите здесь, чтобы инициализировать правила",
  748. update: "Обновить правила",
  749. click2update: "Нажмите, чтобы обновить правила",
  750. loadNow: "Загрузить следующую страницу",
  751. loadConfirm: "Сколько страниц вы хотите загрузить? (0 означает бесконечность)",
  752. noNext: "Ссылка на следующую страницу не найдена. Пожалуйста, создайте новое правило",
  753. passSec: "Обновлено #t# секунд назад",
  754. passMin: "Обновлено #t# минут назад",
  755. passHour: "Обновлено #t# часов назад",
  756. passDay: "Обновлено #t# дней назад",
  757. cantDel: "Нельзя удалить правила по умолчанию",
  758. confirmDel: "Вы уверены, что хотите удалить эту ссылку?",
  759. updateSucc: "Правила обновлены",
  760. beginUpdate: "Обновление. Пожалуйста, немного подождите",
  761. customUrls: "Ссылки с правилами для импорта. Одна ссылка на строку",
  762. customRules: "Введите пользовательские правила в формате Pagetual. <a href='#t#'>✍️Улучшить встроенные правила</a>",
  763. save: "Сохранить настройки",
  764. loadingText: "Следующая страница подгружается…",
  765. opacity: "Прозрачность",
  766. opacityPlaceholder: "0 - скрыть",
  767. hideBar: "Скрыть разделитель страниц",
  768. hideBarButNoStop: "Скрыть, но не останавливать",
  769. dbClick2Stop: "Двойной клик на странице для выключения",
  770. sortTitle: "Правило сортировки применится после следующего обновления правил",
  771. autoRun: "Автозапуск (режим черного списка)",
  772. autoLoadNum: "Количество страниц для предзагрузки",
  773. turnRate: "Подгрузить страницу, когда она будет в 【X】 раз больше высоты страницы от конца страницы",
  774. inputPageNum: "Введите номер страницы для перехода",
  775. enableHistory: "Записать историю после переключения страниц",
  776. enableHistoryAfterInsert: "Записать запись истории сразу после вставки, иначе записать после просмотра",
  777. contentVisibility: "Автоматически переключать contentVisibility для повышения производительности рендеринга",
  778. initRun: "Подгружать страницы сразу после открытия",
  779. preload: "Предзагрузка следующей страницы",
  780. click2ImportRule: "Нажмите, чтобы импортировать базовые правила: ",
  781. forceAllBody: "Присоединить страницу целиком?",
  782. openInNewTab: "Открыть дополнительные ссылки в новой вкладке",
  783. importSucc: "Импорт завершен",
  784. import: "Импорт",
  785. editCurrent: "Изменить правило для текущего сайта",
  786. editBlacklist: "Изменить черный список. Одна ссылка на строку. Поддерживаются метасимволы: ? и *",
  787. upBtnImg: "Иконка перехода к началу",
  788. downBtnImg: "Иконка перехода к концу",
  789. sideControllerIcon: "Значок боковой панели",
  790. loadingTextTitle: "Текст во время загрузки",
  791. dbClick2StopCtrl: "Ctrl",
  792. dbClick2StopAlt: "Alt",
  793. dbClick2StopShift: "Shift",
  794. dbClick2StopMeta: "Meta",
  795. dbClick2StopKey: "Клавиша",
  796. pageElementCss: "Пользовательский стиль для основных элементов страницы",
  797. customCss: "Полный пользовательский CSS",
  798. firstAlert: "Вы не импортировали базовое правило. Пожалуйста, выберите соответствующее правило для импорта",
  799. picker: "Pagetual: выбор элемента страницы",
  800. closePicker: "Закрыть окно Pagetual",
  801. pickerPlaceholder: "Если не знаете, что тут писать — оставьте поле пустым",
  802. pickerCheck: "Проверить и скопировать селектор",
  803. switchSelector: "Нажмите для выбора элемента",
  804. gotoEdit: "Перейти к редактированию правила с текущим селектором",
  805. manualMode: "Отключить автоматическую загрузку страниц. Загружать вручную с помощью стрелки вправо (или вызова события 'pagetual.next')",
  806. clickMode: "Отключить \"сшивание\" страниц. При прокрутке до конца автоматически переходить на следующую страницу",
  807. pageBarMenu: "Открывать меню кликом на середину панели страниц",
  808. nextSwitch: "Переключить ссылку на следующую страницу",
  809. arrowToScroll: "Листать страницы клавишами со стрелками влево и вправо",
  810. sideController: "Показать справа панель перемещения по вкладке",
  811. sideControllerScroll: "Переключатель прокрутки",
  812. sideControllerAlways: "Всегда показывать",
  813. hideLoadingIcon: "Скрыть анимацию загрузки",
  814. hideBarArrow: "Скрыть кнопки перемещения на разделителе",
  815. duplicate: "Похоже, Pagetual установлен несколько раз. Пожалуйста, удалите Pagetual из других менеджеров скриптов!",
  816. forceStateIframe: "Вставить полную страницу как iframe",
  817. forceStateDynamic: "Загружать динамический контент через iframe",
  818. forceStateDisable: "Отключить перелистывание страниц на этой станции",
  819. autoScrollRate: "Скорость прокрутки (1~1000)",
  820. disableAutoScroll: "Остановить автоматическую прокрутку",
  821. enableAutoScroll: "Включить автопрокрутку",
  822. toggleAutoScroll: "Переключить автопрокрутку",
  823. ruleRequest: "Запрос правил",
  824. page: "Страница ",
  825. prevPage: "Предыдущая страница",
  826. nextPage: "Следующая страница",
  827. errorRulesMustBeArray: "Правила должны быть массивом!",
  828. errorJson: "Ошибка разбора JSON. Пожалуйста, исправьте его",
  829. editSuccess: "Редактирование успешно",
  830. errorWrongUrl: "Ссылка некорректна. Пожалуйста, исправьте её",
  831. errorAlreadyExists: "Уже существует!",
  832. settingsSaved: "Настройки сохранены. Обновите страницы",
  833. iframe: "iframe",
  834. dynamic: "Динамически",
  835. reloadPage: "Редактирование завершено. Обновить страницу?",
  836. copied: "Скопировано",
  837. noValidContent: "Действительный контент не обнаружен, нажмите для просмотра",
  838. outOfDate: "Скрипт устарел, своевременно обновляйте до последней версии!",
  839. hideBarTips: "Скрыть панель разбиения на страницы, иммерсивный опыт",
  840. setConfigPage: "Установить текущую страницу в качестве страницы конфигурации по умолчанию",
  841. wedata2github: "Изменить адрес wedata на зеркальный адрес на складе github",
  842. addOtherProp: "Добавить свойство правила",
  843. addNextSelector: "Добавить содержимое селектора как nextLink",
  844. addPageSelector: "Добавить содержимое селектора как pageElement",
  845. propName: "Введите имя свойства правила",
  846. propValue: "Введите значение свойства правила",
  847. customFirst: "Игнорировать кеш для локальных пользовательских правил",
  848. rulesExample: "Подробное объяснение настраиваемых правил",
  849. lastPage: "Достигнута последняя страница",
  850. lastPageTips: "Показывать подсказки при достижении последней страницы"
  851. }
  852. }
  853. ];
  854. var langList = {};
  855. langData.forEach(lang => {
  856. langList[lang.match[0]] = lang.name;
  857. });
  858. var i18nData = langData[0].lang;
  859. function setLang(la) {
  860. for (let i = 0; i < langData.length; i++) {
  861. let lang = langData[i];
  862. if (lang && lang.match.indexOf(la) !== -1) {
  863. i18nData = lang.lang;
  864. break;
  865. }
  866. }
  867. }
  868. setLang(lang);
  869. var enableDebug = true;
  870. var _GM_xmlhttpRequest, _GM_registerMenuCommand, _GM_notification, _GM_addStyle, _GM_openInTab, _GM_info, _GM_setClipboard;
  871. function i18n(name, param) {
  872. return i18nData[name] ? i18nData[name].replace("#t#", param) : name;
  873. }
  874.  
  875. function debug(str, title) {
  876. if (enableDebug) {
  877. console.log(
  878. `%cPagetual v.${_GM_info.script.version}】 ${title ? title : 'debug'}:`,
  879. 'color: yellow;font-size: large;font-weight: bold;background-color: darkblue;',
  880. str
  881. );
  882. }
  883. }
  884.  
  885. if (typeof GM_xmlhttpRequest !== 'undefined') {
  886. _GM_xmlhttpRequest = GM_xmlhttpRequest;
  887. } else if (typeof GM !== 'undefined' && typeof GM.xmlHttpRequest !== 'undefined') {
  888. _GM_xmlhttpRequest = GM.xmlHttpRequest;
  889. } else {
  890. _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())};
  891. }
  892. if (typeof GM_registerMenuCommand !== 'undefined') {
  893. _GM_registerMenuCommand = GM_registerMenuCommand;
  894. } else if (typeof GM !== 'undefined' && typeof GM.registerMenuCommand !== 'undefined') {
  895. _GM_registerMenuCommand = GM.registerMenuCommand;
  896. } else {
  897. _GM_registerMenuCommand = (s, f) => {debug(s); debug(f);};
  898. }
  899. if (typeof GM_info !== 'undefined') {
  900. _GM_info = GM_info;
  901. } else if (typeof GM !== 'undefined' && typeof GM.info !== 'undefined') {
  902. _GM_info = GM.info;
  903. } else {
  904. _GM_info = {script: {}};
  905. }
  906. if (typeof GM_notification !== 'undefined') {
  907. _GM_notification = GM_notification;
  908. } else if (typeof GM !== 'undefined' && typeof GM.notification !== 'undefined') {
  909. _GM_notification = GM.notification;
  910. } else {
  911. _GM_notification = (s) => {showTips(String(s.text || s));};
  912. }
  913. if (typeof GM_openInTab !== 'undefined') {
  914. _GM_openInTab = GM_openInTab;
  915. } else if (typeof GM !== 'undefined' && typeof GM.openInTab !== 'undefined') {
  916. _GM_openInTab = GM.openInTab;
  917. } else {
  918. _GM_openInTab = (s,t) => {window.open(s); debug(t);};
  919. }
  920. if (typeof GM_addStyle !== 'undefined') {
  921. _GM_addStyle = GM_addStyle;
  922. } else if (typeof GM !== 'undefined' && typeof GM.addStyle !== 'undefined') {
  923. _GM_addStyle = GM.addStyle;
  924. } else {
  925. _GM_addStyle = cssStr => {
  926. let styleEle = document.createElement("style");
  927. styleEle.innerHTML = cssStr;
  928. document.head.appendChild(styleEle);
  929. return styleEle;
  930. };
  931. }
  932. if (typeof GM_setClipboard !== 'undefined') {
  933. _GM_setClipboard = GM_setClipboard;
  934. } else if (typeof GM !== 'undefined' && typeof GM.setClipboard !== 'undefined') {
  935. _GM_setClipboard = GM.setClipboard;
  936. } else {
  937. _GM_setClipboard = (s, i) => {debug(s); debug(i);};
  938. }
  939. const _unsafeWindow = (typeof unsafeWindow === 'undefined') ? window : unsafeWindow;//兼容 ios userscripts 的寫法
  940. const storage = {
  941. supportGM: typeof GM_getValue === 'function' && typeof GM_getValue('a', 'b') !== 'undefined',
  942. supportGMPromise: typeof GM !== 'undefined' && typeof GM.getValue === 'function' && typeof GM.getValue('a', 'b') !== 'undefined' && typeof GM.getValue('a', 'b').then === 'function',
  943. supportCrossSave: function() {
  944. return this.supportGM || this.supportGMPromise;
  945. },
  946. mxAppStorage: (function() {
  947. try {
  948. return window.external.mxGetRuntime().storage;
  949. } catch(e) {
  950. }
  951. })(),
  952. operaUJSStorage: (function() {
  953. try {
  954. return window.opera.scriptStorage;
  955. } catch(e) {
  956. }
  957. })(),
  958. setItem: function(key, value) {
  959. if (this.supportGMPromise) {
  960. GM.setValue(key, value);
  961. if (value === "" && typeof GM !== 'undefined' && typeof GM.deleteValue !== 'undefined') {
  962. GM.deleteValue(key);
  963. }
  964. } else if (this.supportGM) {
  965. GM_setValue(key, value);
  966. if (value === "" && typeof GM_deleteValue !== 'undefined') {
  967. GM_deleteValue(key);
  968. }
  969. } else if (this.operaUJSStorage) {
  970. this.operaUJSStorage.setItem(key, value);
  971. } else if (this.mxAppStorage) {
  972. this.mxAppStorage.setConfig(key, value);
  973. } else if (window.localStorage) {
  974. window.localStorage.setItem(key, value);
  975. }
  976. },
  977. getItem: function(key, cb) {
  978. var value;
  979. if (this.supportGMPromise) {
  980. value = GM.getValue(key).then(v => {cb(v);});
  981. return;
  982. } else if (this.supportGM) {
  983. value = GM_getValue(key);
  984. } else if (this.operaUJSStorage) {
  985. value = this.operaUJSStorage.getItem(key);
  986. } else if (this.mxAppStorage) {
  987. value = this.mxAppStorage.getConfig(key);
  988. } else if (window.localStorage) {
  989. value = window.localStorage.getItem(key);
  990. }
  991. cb(value);
  992. }
  993. };
  994. async function getData(key) {
  995. return new Promise((resolve) => {
  996. storage.getItem(key, value => {
  997. resolve(value);
  998. });
  999. });
  1000. }
  1001. async function getListData(list, key) {
  1002. return new Promise((resolve) => {
  1003. storage.getItem(list, listData => {
  1004. let value;
  1005. if (listData) {
  1006. for(var i = 0; i < listData.length; i++) {
  1007. let data = listData[i];
  1008. if (data.k === key) {
  1009. value = data.v;
  1010. break;
  1011. }
  1012. }
  1013. }
  1014. resolve(value);
  1015. });
  1016. });
  1017. }
  1018. function setListData(list, key, value, length) {
  1019. storage.getItem(list, listData => {
  1020. if (!listData) {
  1021. listData = [];
  1022. }
  1023. listData = listData.filter(data => data && data.k !== key);
  1024. if (value !== "") {
  1025. listData.unshift({k: key, v: value});
  1026. if (listData.length > (length || 100)) {
  1027. listData.pop();
  1028. }
  1029. }
  1030. storage.setItem(list, listData);
  1031. });
  1032. }
  1033. const isMobile = ('ontouchstart' in document.documentElement);
  1034. const configPage = [`https://pagetual.hoothin.com/${lang === 'zh-CN' ? 'cn/' : ''}rule.html`,
  1035. "https://github.com/hoothin/UserScripts/tree/master/Pagetual",
  1036. "https://hoothin.github.io/UserScripts/Pagetual/"];
  1037. const firstRunPage = "https://pagetual.hoothin.com/firstRun";
  1038. const guidePage = /^https?:\/\/.*pagetual.*rule\.html/i;
  1039. const ruleImportUrlReg = /greasyfork\.org\/.*scripts\/438684(\-[^\/]*)?(\/discussions|\/?$|\/feedback)|github\.com\/hoothin\/UserScripts\/(tree\/master\/Pagetual|issues)/i;
  1040. const allOfBody = "body>*";
  1041. const mainSel = ["article,.article","[role=main],main,.main,#main","#results"];
  1042. 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");
  1043. 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");
  1044. 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"];
  1045. var rulesData = {uninited: true, firstRun: true, sideController: !isMobile}, ruleUrls, updateDate, clickedSth = false, loadNowNum = 5, autoScrollRate = 50;
  1046. 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;
  1047. var tryTimes = 0, showedLastPageTips = false, rate = 1, author = '';
  1048.  
  1049. function getBody(doc) {
  1050. return doc.body || doc.querySelector('body') || doc;
  1051. }
  1052.  
  1053. function getElementByXpath(xpath, doc, contextNode) {
  1054. doc = doc || document;
  1055. contextNode = contextNode || doc;
  1056. try {
  1057. let result = doc.evaluate(xpath, contextNode, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  1058. return result.singleNodeValue && result.singleNodeValue.nodeType === 1 && result.singleNodeValue;
  1059. } catch (err) {
  1060. debug(`Invalid xpath: ${xpath}`);
  1061. }
  1062. return null;
  1063. }
  1064.  
  1065. function getAllElementsByXpath(xpath, contextNode, doc) {
  1066. doc = doc || document;
  1067. contextNode = contextNode || doc;
  1068. var result = [];
  1069. try {
  1070. var query = doc.evaluate(xpath, contextNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  1071. for (var i = 0; i < query.snapshotLength; i++) {
  1072. var node = query.snapshotItem(i);
  1073. if (node.nodeType === 1) {
  1074. result.push(node);
  1075. }
  1076. }
  1077. } catch (err) {
  1078. debug(`Invalid xpath: ${xpath}`);
  1079. }
  1080. return result;
  1081. }
  1082.  
  1083. function isXPath(xpath) {
  1084. if (!xpath) {
  1085. return false;
  1086. }
  1087. return /^\(*(descendant::|\.\/|\/|id\()/.test(xpath);
  1088. }
  1089.  
  1090. function getAllElements(sel, doc, contextNode) {
  1091. try {
  1092. if (!isXPath(sel)) {
  1093. return doc.querySelectorAll(sel);
  1094. }
  1095. } catch(e) {
  1096. debug(e, 'Error selector');
  1097. }
  1098. return getAllElementsByXpath(sel, contextNode, doc);
  1099. }
  1100.  
  1101. function getElement(sel, doc, contextNode, bySort) {
  1102. try {
  1103. if (!isXPath(sel)) {
  1104. if (!bySort) {
  1105. return doc.querySelector(sel);
  1106. } else {
  1107. let selArr = sel.split(",");
  1108. try {
  1109. for (let i = 0; i < selArr.length; i++) {
  1110. let ele = doc.querySelector(selArr[i].trim());
  1111. if (ele) {
  1112. return ele;
  1113. }
  1114. }
  1115. } catch(e) {
  1116. return doc.querySelector(sel);
  1117. }
  1118. return null;
  1119. }
  1120. }
  1121. } catch(e) {
  1122. debug(e, 'Error selector');
  1123. }
  1124. return getElementByXpath(sel, doc, contextNode);
  1125. }
  1126.  
  1127. function compareNodeName(node, names) {
  1128. if (!node || !node.nodeName || !node.nodeName.toLowerCase) {
  1129. return false;
  1130. }
  1131. let nodeName = node.nodeName.toLowerCase();
  1132. for (let i = 0; i < names.length; i++) {
  1133. if (names[i] === nodeName) {
  1134. return true;
  1135. }
  1136. }
  1137. return false;
  1138. }
  1139.  
  1140. function geneSelector(ele, addID, exact) {
  1141. let selector = ele.nodeName.toLowerCase();
  1142. //Google id class都是隨機。百度更過分,style script順序都是隨機的
  1143. if (selector !== "html" && selector !== "body") {
  1144. let hasId = false;
  1145. if (addID && ele.id && /^[a-z_][\w\-_]*$/i.test(ele.id)) {
  1146. if (ele.ownerDocument && ele.ownerDocument.querySelectorAll("#" + ele.id).length === 1) {
  1147. hasId = true;
  1148. selector = '#' + ele.id;
  1149. }
  1150. }
  1151. if (!hasId) {
  1152. let className = "";
  1153. if (ele.className) {
  1154. let classList = ele.classList;
  1155. for (let i = 0; i < classList.length; i++) {
  1156. let c = classList[i];
  1157. if (/^[\w\-_]+$/.test(c) && !/\d{4,}/.test(c)) {
  1158. className += '.' + c;
  1159. }
  1160. }
  1161. selector += className;
  1162. }
  1163. let parent = ele.parentElement;
  1164. if (parent) {
  1165. if (exact) {
  1166. let i, nth = 0, all = 0;
  1167. for (i = 0; i < parent.children.length; i++) {
  1168. if (parent.children[i].nodeName === ele.nodeName) {
  1169. all++;
  1170. if (parent.children[i] === ele) {
  1171. nth = all;
  1172. }
  1173. if (nth > 0 && all > 1) {
  1174. break;
  1175. }
  1176. }
  1177. }
  1178. selector += (all === 1 ? "" : `:nth-of-type(${nth})`);
  1179. } else if (!className && !hasId && parent.children.length > 1 && !compareNodeName(parent, ["html"])) {
  1180. let prevE = ele.previousElementSibling;
  1181. if (prevE && prevE.className) {
  1182. let classList = prevE.classList;
  1183. for (let i = 0; i < classList.length; i++) {
  1184. let c = classList[i];
  1185. if (/^[\w\-_]+$/.test(c) && !/\d{4,}/.test(c)) {
  1186. className += '.' + c;
  1187. }
  1188. }
  1189. if (className) {
  1190. selector = prevE.nodeName.toLowerCase() + className + "+" + selector;
  1191. }
  1192. }
  1193. if (!className) {
  1194. let i, nth = 0, all = 0;
  1195. for (i = 0; i < parent.children.length; i++) {
  1196. if (parent.children[i].nodeName === ele.nodeName) {
  1197. all++;
  1198. if (parent.children[i] === ele) {
  1199. nth = all;
  1200. }
  1201. if (nth > 0 && all > 1) {
  1202. break;
  1203. }
  1204. }
  1205. }
  1206. selector += (all === 1 ? "" : `:nth-of-type(${nth})`);
  1207. }
  1208. }
  1209. selector = geneSelector(parent, addID, exact) + ' > ' + selector;
  1210. }
  1211. }
  1212. }
  1213. return selector;
  1214. }
  1215.  
  1216. function createXPathFromElement(elm) {
  1217. let allNodes = document.getElementsByTagName('*'), segs;
  1218. for (segs = []; elm && elm.nodeType === 1; elm = elm.parentNode) {
  1219. if (compareNodeName(elm, ["body", "html"])) {
  1220. segs.unshift(elm.localName.toLowerCase());
  1221. continue;
  1222. }
  1223. if (elm.hasAttribute && elm.hasAttribute('id')) {
  1224. var uniqueIdCount = 0;
  1225. for (var n = 0; n < allNodes.length; n++) {
  1226. if (allNodes[n].hasAttribute('id') && allNodes[n].id === elm.id) {
  1227. uniqueIdCount++;
  1228. }
  1229. if (uniqueIdCount > 1) {
  1230. break;
  1231. }
  1232. }
  1233. if ( uniqueIdCount === 1) {
  1234. segs.unshift('id("' + elm.getAttribute('id') + '")');
  1235. return segs.join('/');
  1236. } else {
  1237. segs.unshift(elm.localName.toLowerCase() + '[@id="' + elm.getAttribute('id') + '"]');
  1238. }
  1239. } else if (elm.hasAttribute && elm.hasAttribute('class')) {
  1240. segs.unshift(elm.localName.toLowerCase() + '[@class="' + elm.getAttribute('class') + '"]');
  1241. } else {
  1242. let i, sib;
  1243. for (i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling) {
  1244. if (sib.localName === elm.localName) {
  1245. i++;
  1246. }
  1247. }
  1248. segs.unshift(elm.localName.toLowerCase() + '[' + i + ']');
  1249. }
  1250. }
  1251. return segs.length ? '/' + segs.join('/') : null;
  1252. }
  1253.  
  1254. const escapeHTMLPolicy = (_unsafeWindow.trustedTypes && _unsafeWindow.trustedTypes.createPolicy) ? _unsafeWindow.trustedTypes.createPolicy('pagetual_default', {
  1255. createHTML: (string, sink) => string
  1256. }) : null;
  1257.  
  1258. function createHTML(html) {
  1259. return escapeHTMLPolicy ? escapeHTMLPolicy.createHTML(html) : html;
  1260. }
  1261.  
  1262. const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
  1263.  
  1264. async function sleep(time) {
  1265. await new Promise((resolve) => {
  1266. setTimeout(() => {
  1267. resolve();
  1268. }, time);
  1269. });
  1270. }
  1271.  
  1272. class RuleParser {
  1273. constructor() {
  1274. this.hpRules = [];
  1275. this.smartRules = [];
  1276. this.customRules = [];
  1277. this.rules = [];
  1278. this.pageDoc = document;
  1279. this.nextLinkHref = null;
  1280. this.nextTitle = "";
  1281. this.oldUrl = "";
  1282. this.curUrl = location.href;
  1283. this.curSiteRule = {};
  1284. }
  1285.  
  1286. async initSavedRules(callback) {
  1287. var self = this;
  1288. let smartRules = await getData("smartRules");
  1289. if (smartRules) self.smartRules = smartRules;
  1290. let hpRules = await getData("hpRules");
  1291. if (hpRules) self.hpRules = hpRules;
  1292. let customRules = await getData("customRules");
  1293. if (customRules) self.customRules = customRules;
  1294. if (_unsafeWindow.pagetualRules && _unsafeWindow.pagetualRules.length) {
  1295. _unsafeWindow.pagetualRules.forEach(rule => {
  1296. rule.isScript = true;
  1297. });
  1298. self.customRules = _unsafeWindow.pagetualRules.concat(self.customRules);
  1299. }
  1300. let rules = await getData("rules");
  1301. if (rules) self.rules = rules;
  1302. callback();
  1303. }
  1304.  
  1305. saveCurSiteRule() {
  1306. /*if(!this.curSiteRule || !this.curSiteRule.url || this.curSiteRule.smart || this.curSiteRule.url.length<13)return;
  1307. this.hpRules=this.hpRules.filter(item=>{return item&&item.url!=this.curSiteRule.url});
  1308. this.hpRules.unshift(this.curSiteRule);
  1309. if(this.hpRules.length>30){
  1310. this.hpRules.pop();
  1311. }
  1312. storage.setItem("hpRules", this.hpRules);*/
  1313. }
  1314.  
  1315. requestJSON(url, callback) {
  1316. _GM_xmlhttpRequest({
  1317. url: url,
  1318. method: 'GET',
  1319. timeout: 20000,
  1320. headers: {
  1321. 'accept': 'application/json,text/html',
  1322. 'Referer': url,
  1323. },
  1324. onload: function(res) {
  1325. let json = null;
  1326. try {
  1327. json = JSON.parse(res.response || res.responseText);
  1328. } catch(e) {
  1329. debug(e, 'Error json');
  1330. }
  1331. callback(json);
  1332. },
  1333. onerror: function(e) {
  1334. callback(null, e);
  1335. },
  1336. ontimeout: function(e) {
  1337. callback(null, e);
  1338. }
  1339. });
  1340. }
  1341.  
  1342. formatRule(item, from) {
  1343. if (item.data && item.data.url) {
  1344. let result = {
  1345. name: item.name,
  1346. from: from,
  1347. action: item.data.forceIframe === "true" ? 1 : undefined,
  1348. url: item.data.url,
  1349. pageElement: item.data.pageElement,
  1350. nextLink: item.data.nextLink,
  1351. insert: item.data.insertBefore||undefined,
  1352. updatedAt: item.updated_at
  1353. };
  1354. let _css = (item.data.Stylus || '') + (item.data.CSS || '');
  1355. if (_css) result.css = _css;
  1356. if (item.data.bookmarklet) result.pageAction = item.data.bookmarklet;
  1357. return result;
  1358. } else {
  1359. item.from = from;
  1360. return item;
  1361. }
  1362. return null;
  1363. }
  1364.  
  1365. addRuleByUrl(url, from, callback) {
  1366. if (url.indexOf("?") === -1) {
  1367. url = url + "?" + Date.now();
  1368. } else {
  1369. url = url + "&" + Date.now();
  1370. }
  1371. this.requestJSON(url, (json,err) => {
  1372. if (!json) {
  1373. debug(err, "Failed to update " + url + " rules!");
  1374. }
  1375. this.addRules(json, from);
  1376. callback(json, err);
  1377. });
  1378. }
  1379.  
  1380. addRules(rules, from) {
  1381. if (rules && rules.length > 0) {
  1382. let first = -1;
  1383. this.rules = this.rules.filter((item, i) => {
  1384. if (item.from === from) {
  1385. if (first === -1) first = i;
  1386. return false;
  1387. } else return true;
  1388. });
  1389. if (first === -1) first = 0;
  1390. rules.forEach(item => {
  1391. let rule = this.formatRule(item, from);
  1392. if (rule) {
  1393. this.rules.splice(first, 0, rule)
  1394. }
  1395. });
  1396. }
  1397. }
  1398.  
  1399. ruleMatchPre(r) {
  1400. if (r.include) {
  1401. let include;
  1402. if (Array && Array.isArray && Array.isArray(r.include)) {
  1403. include = r.include.every((sel, i) => {
  1404. let ele = getElement(sel, document);
  1405. return !!ele;
  1406. });
  1407. } else include = getElement(r.include, document);
  1408. if (!include) return false;
  1409. }
  1410. if (r.exclude) {
  1411. let exclude;
  1412. if (Array && Array.isArray && Array.isArray(r.exclude)) {
  1413. exclude = !r.exclude.every((sel, i) => {
  1414. let ele = getElement(sel, document);
  1415. return !ele;
  1416. });
  1417. } else exclude = getElement(r.exclude, document);
  1418. if (exclude) return false;
  1419. }
  1420. return true;
  1421. }
  1422.  
  1423. ruleMatchReady(r) {
  1424. let findIndex = 0;
  1425. if (r.nextLink && r.nextLink !== 0) {
  1426. let nextLinkSel = r.nextLink, nextLink;
  1427. if (Array && Array.isArray && Array.isArray(nextLinkSel)) {
  1428. nextLink = !nextLinkSel.every((sel, i) => {
  1429. let ele = getElement(sel, document);
  1430. if (ele) findIndex = i;
  1431. return !ele;
  1432. });
  1433. } else nextLink = getElement(nextLinkSel, document);
  1434. if (!nextLink) return false;
  1435. }
  1436. if (r.pageElement) {
  1437. let pageElementSel = r.pageElement, pageElement;
  1438. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  1439. pageElementSel = pageElementSel[findIndex];
  1440. }
  1441. pageElement = getElement(pageElementSel, document);
  1442. if (!pageElement) return false;
  1443. }
  1444. if (r.insert) {
  1445. let insertSel = r.insert, insert;
  1446. if (Array && Array.isArray && Array.isArray(insertSel)) {
  1447. insertSel = insertSel[findIndex];
  1448. }
  1449. insert = getElement(insertSel, document);
  1450. if (!insert) return false;
  1451. }
  1452. //if (findIndex !== 0) nextIndex = findIndex;
  1453. return true;
  1454. }
  1455.  
  1456. ruleMatch(r) {
  1457. return this.ruleMatchPre(r) && this.ruleMatchReady(r);
  1458. }
  1459.  
  1460. scrollToShow(sel, doc) {
  1461. let exclude = getElement(sel, doc);
  1462. if (exclude) {
  1463. var actualTop = exclude.offsetTop;
  1464. var current = exclude.offsetParent;
  1465. while (current !== null) {
  1466. actualTop += current.offsetTop;
  1467. current = current.offsetParent;
  1468. }
  1469. getBody(doc).scrollTop = 0;
  1470. doc.documentElement.scrollTop = 0;
  1471. let maxHeight = Math.max(getBody(doc).scrollHeight, doc.documentElement.scrollHeight);
  1472. getBody(doc).scrollTop = actualTop - 10;
  1473. doc.documentElement.scrollTop = actualTop - 10;
  1474. setTimeout(() => {
  1475. while (actualTop < maxHeight) {
  1476. actualTop += 200;
  1477. getBody(doc).scrollTop = actualTop;
  1478. doc.documentElement.scrollTop = actualTop;
  1479. }
  1480. }, 0);
  1481. return false;
  1482. }
  1483. return true;
  1484. }
  1485.  
  1486. waitElement(doc, selArr) {
  1487. if (!selArr) selArr = this.curSiteRule.waitElement;
  1488. if (!Array.isArray(selArr)) {
  1489. selArr = [selArr];
  1490. }
  1491. let includeSel = selArr[0].trim(), excludeSel;
  1492. if (selArr.length === 2) {
  1493. excludeSel = selArr[1].trim().replace(/^!/, '');
  1494. } else if (includeSel.indexOf('!') === 0) {
  1495. excludeSel = includeSel.replace(/^!/, '');
  1496. includeSel = '';
  1497. }
  1498. if (includeSel) {
  1499. let include = getElement(includeSel, doc);
  1500. if (!include) {
  1501. if (doc !== document) {
  1502. getBody(doc).scrollTop = 9999999;
  1503. doc.documentElement.scrollTop = 9999999;
  1504. }
  1505. return false;
  1506. }
  1507. }
  1508. if (doc === document) return true;
  1509. if (excludeSel) {
  1510. if (!this.scrollToShow(excludeSel, doc)) {
  1511. if (!loadingDiv.offsetParent && this.insert.parentNode) {
  1512. this.insertElement(loadingDiv);
  1513. }
  1514. return false;
  1515. }
  1516. }
  1517. return true;
  1518. }
  1519.  
  1520. runPageBar(pageBar) {
  1521. if (this.curSiteRule.pageBar && this.curSiteRule.pageBar !== 0) {
  1522. try {
  1523. ((typeof this.curSiteRule.pageBar === 'function') ? this.curSiteRule.pageBar : Function("pageBar",'"use strict";' + this.curSiteRule.pageBar))(pageBar);
  1524. } catch(e) {
  1525. debug(e);
  1526. }
  1527. }
  1528. }
  1529.  
  1530. runWait(cb) {
  1531. let checkEval = null, waitTime = 0;
  1532. if (this.curSiteRule.waitElement) {
  1533. checkEval = async doc => {
  1534. return await this.waitElement(doc);
  1535. };
  1536. } else if(this.curSiteRule.wait) {
  1537. if (isNaN(this.curSiteRule.wait)) {
  1538. try {
  1539. checkEval = (typeof this.curSiteRule.wait === 'function') ? this.curSiteRule.wait : new AsyncFunction("doc", '"use strict";' + this.curSiteRule.wait);
  1540. } catch(e) {
  1541. debug(e);
  1542. }
  1543. } else {
  1544. waitTime = this.curSiteRule.wait;
  1545. }
  1546. }
  1547. cb(checkEval, waitTime);
  1548. }
  1549.  
  1550. findNoNext() {
  1551. if (!this.curSiteRule || !this.curSiteRule.smart || this.curSiteRule.nextLink === 0 || this.possibleRule) return;
  1552. let self = this;
  1553. self.curSiteRule.nextLink = 0;
  1554. self.smartRules = self.smartRules.filter(item => {return item && item.url !== self.curSiteRule.url;});
  1555. self.smartRules.unshift(self.curSiteRule);
  1556. storage.setItem("smartRules", self.smartRules);
  1557. }
  1558.  
  1559. async getRule(callback) {
  1560. var href = location.href.slice(0, 500);
  1561. if(noRuleTest) {
  1562. this.curSiteRule = {};
  1563. this.curSiteRule.url = href;
  1564. this.curSiteRule.smart = true;
  1565. callback();
  1566. return;
  1567. }
  1568. if (_unsafeWindow.pagetualRule) {
  1569. this.curSiteRule = _unsafeWindow.pagetualRule;
  1570. if (!this.curSiteRule.url) this.curSiteRule.url = ".";
  1571. this.curSiteRule.isScript = true;
  1572. }
  1573. if (this.curSiteRule && this.curSiteRule.url && !this.curSiteRule.smart) {
  1574. let urlReg = new RegExp(this.curSiteRule.url, "i");
  1575. if (urlReg.test(href) && this.ruleMatch(this.curSiteRule)) {
  1576. return callback();
  1577. }
  1578. }
  1579. if (this.possibleRule) {
  1580. let urlReg = new RegExp(this.possibleRule.url, "i");
  1581. if (urlReg.test(href) && this.ruleMatch(this.possibleRule)) {
  1582. this.curSiteRule = this.possibleRule;
  1583. debug(this.curSiteRule, 'Match');
  1584. return callback();
  1585. }
  1586. }
  1587. this.curSiteRule = {};
  1588. var self = this;
  1589.  
  1590. function setRule(r) {
  1591. if (self.preSiteRule) {
  1592. href = location.href.slice(0, 500);
  1593. let urlReg = new RegExp(self.preSiteRule.url, "i");
  1594. if (urlReg.test(href) && self.ruleMatch(self.preSiteRule)) {
  1595. self.curSiteRule = self.preSiteRule;
  1596. return callback();
  1597. }
  1598. }
  1599. if (r.from === 2) {
  1600. delete r.autoLoadNum;
  1601. delete r.history;
  1602. delete r.sideController;
  1603. if (r.pageBar === 0) delete r.pageBar;
  1604. }
  1605. if (!r.smart) {
  1606. self.insert = null;
  1607. self.curSiteRule = r;
  1608. self.preSiteRule = r;
  1609. if (r.enable !== 0) debug(r, 'Match');
  1610. } else if (!self.curSiteRule || !self.curSiteRule.smart) self.curSiteRule = r;
  1611. callback();
  1612. }
  1613.  
  1614. function checkRule(r) {
  1615. if (r.from === 1 && r.url.length <= 13) return false;
  1616. let urlReg = new RegExp(r.url, "i");
  1617. if (urlReg.test(href)) {
  1618. if (!self.ruleMatchPre(r)) return false;
  1619. if (r.url.length > 15 && r.from !== 1) {
  1620. self.possibleRule = r;
  1621. }
  1622. if (r.waitElement) {
  1623. let waitTime = 500;
  1624. let checkReady = () => {
  1625. setTimeout(() => {
  1626. if (!self.waitElement(document, r.waitElement) || !self.ruleMatchReady(r)) {
  1627. checkReady();
  1628. } else {
  1629. setRule(r);
  1630. }
  1631. }, parseInt(waitTime));
  1632. };
  1633. checkReady();
  1634. debug(r, 'Wait for');
  1635. return true;
  1636. } else if (r.wait) {
  1637. let waitTime = 500, checkEval, maxCheckTimes = 50;
  1638. if (isNaN(r.wait)) {
  1639. try {
  1640. checkEval = (typeof r.wait === 'function') ? r.wait : AsyncFunction("doc",'"use strict";' + r.wait);
  1641. } catch(e) {
  1642. debug(e, 'Error when checkeval');
  1643. }
  1644. } else {
  1645. waitTime = r.wait;
  1646. }
  1647. let checkReady = () => {
  1648. if (maxCheckTimes-- <= 0) {
  1649. debug("Wait for rule ready but failed");
  1650. setRule(r);
  1651. return;
  1652. }
  1653. setTimeout(async() => {
  1654. if (!self.ruleMatchReady(r) || (checkEval && !await checkEval(document))) {
  1655. checkReady();
  1656. } else {
  1657. setRule(r);
  1658. }
  1659. }, parseInt(waitTime));
  1660. };
  1661. checkReady();
  1662. debug(r, 'Wait for');
  1663. return true;
  1664. }
  1665. if (r.pinUrl) {
  1666. setRule(r);
  1667. return true;
  1668. }
  1669. if (!self.ruleMatchReady(r)) {
  1670. return false;
  1671. }
  1672. setRule(r);
  1673. return true;
  1674. }
  1675. return false;
  1676. }
  1677.  
  1678. function checkHpRules() {
  1679. for (let i in self.hpRules) {
  1680. let rule = self.hpRules[i];
  1681. if (!rule || !rule.url || rule.smart) continue;
  1682. if (checkRule(rule)) return true;
  1683. }
  1684. return false;
  1685. }
  1686.  
  1687. function checkCustomRules() {
  1688. for (let i in self.customRules) {
  1689. let rule = self.customRules[i];
  1690. if (!rule || !rule.url) continue;
  1691. if (checkRule(rule)) return true;
  1692. }
  1693. return false;
  1694. }
  1695.  
  1696. if (rulesData.customFirst) {
  1697. if (checkCustomRules()) return;
  1698. await sleep(1);
  1699. if (checkHpRules()) return;
  1700. } else {
  1701. if (checkHpRules()) return;
  1702. await sleep(1);
  1703. if (checkCustomRules()) return;
  1704. }
  1705. await sleep(1);
  1706.  
  1707. for (let i in this.smartRules) {
  1708. let rule = this.smartRules[i];
  1709. if (!rule || !rule.url || !rule.smart) continue;
  1710. if (href == rule.url) {
  1711. setRule(rule);
  1712. return;
  1713. }
  1714. }
  1715. let r = 0;
  1716. async function searchByTime() {
  1717. while (document.hidden) {
  1718. await sleep(1000);
  1719. }
  1720. setTimeout(() => {
  1721. let end = r + 20;
  1722. end = end > self.rules.length ? self.rules.length : end;
  1723. for (; r < end; r++) {
  1724. let rule = self.rules[r];
  1725. if (checkRule(rule)) return;
  1726. }
  1727. if (end >= self.rules.length) {
  1728. setRule({url: href, smart: true});
  1729. return;
  1730. } else {
  1731. searchByTime();
  1732. }
  1733. }, 1);
  1734. }
  1735. searchByTime();
  1736. }
  1737.  
  1738. addToHpRules(instead) {
  1739. try {
  1740. if (this.curSiteRule.isScript) return;
  1741. if (!this.hpRules) this.hpRules = [];
  1742. let url = this.curSiteRule && this.curSiteRule.url, self = this;
  1743. let href = location.href.slice(0, 500);
  1744. let matchedRules = this.hpRules.filter(rule => rule != self.curSiteRule && new RegExp(rule.url, "i").test(href) && self.ruleMatch(rule));
  1745. if (url) matchedRules.unshift(this.curSiteRule);
  1746. matchedRules.sort((a, b) => {
  1747. if ((a.include || a.exclude) && (!b.include && !b.exclude)) {
  1748. return -1;
  1749. } else if ((b.include || b.exclude) && (!a.include && !a.exclude)) {
  1750. return 1;
  1751. } else {
  1752. if ((a.nextLink || a.pageElement) && (!b.nextLink && !b.pageElement)) {
  1753. return -1;
  1754. } else if ((b.nextLink || b.pageElement) && (!a.nextLink && !a.pageElement)) {
  1755. return 1;
  1756. } else {
  1757. if (a.url.length > b.url.length) {
  1758. return -1;
  1759. } else if (a.url.length < b.url.length) {
  1760. return 1;
  1761. } else {
  1762. return 0;
  1763. }
  1764. }
  1765. }
  1766. });
  1767. this.hpRules = this.hpRules.filter(item => {
  1768. return item && !matchedRules.find(rule => item.url == rule.url && JSON.stringify(item) == JSON.stringify(rule));
  1769. });
  1770. if (instead) {
  1771. if (url) {
  1772. this.hpRules.unshift(this.curSiteRule);
  1773. matchedRules = [];
  1774. }
  1775. } else {
  1776. this.hpRules = matchedRules.concat(this.hpRules);
  1777. }
  1778. if (matchedRules && matchedRules.length) this.curSiteRule = matchedRules[0];
  1779. if (this.hpRules.length > 30) {
  1780. this.hpRules.pop();
  1781. }
  1782. if (!rulesData.sort) rulesData.sort = [1];
  1783. this.hpRules.sort((a, b) => {
  1784. let aSort = -1, bSort = -1;
  1785. for (let s = 0; s < rulesData.sort.length; s++) {
  1786. if (a.from == rulesData.sort[s]) aSort = s;
  1787. if (b.from == rulesData.sort[s]) bSort = s;
  1788. if (aSort > -1 && bSort > -1) break;
  1789. }
  1790. return aSort - bSort;
  1791. });
  1792. storage.setItem("hpRules", this.hpRules);
  1793. } catch (e) {
  1794. debug(e);
  1795. }
  1796. }
  1797.  
  1798. replaceElement(doc) {
  1799. if (!doc || doc === document) return;
  1800. let replaceElementSel = this.curSiteRule.replaceElement;
  1801. if (replaceElementSel) {
  1802. if (!Array.isArray(replaceElementSel)) {
  1803. replaceElementSel = [replaceElementSel];
  1804. }
  1805. replaceElementSel.forEach(sel => {
  1806. let pageEles = getAllElements(sel, document);
  1807. let replaceEles = getAllElements(sel, doc);
  1808. for (let i = 0; i < pageEles.length; i++) {
  1809. let replaceEle = replaceEles[i];
  1810. let pageEle = pageEles[i];
  1811. if (replaceEle) {
  1812. pageEle.parentNode.replaceChild(replaceEle.cloneNode(true), pageEle);
  1813. } else break;
  1814. }
  1815. });
  1816. }
  1817. }
  1818.  
  1819. refreshByClick() {
  1820. let refreshByClickSel = this.curSiteRule.refreshByClick;
  1821. if (refreshByClickSel) {
  1822. let self = this;
  1823. if (!this.refreshByClickHandler) {
  1824. this.refreshByClickHandler = e => {
  1825. if (!self.refreshing) {
  1826. self.refreshing = true;
  1827. setTimeout(() => {
  1828. self.refreshing = false;
  1829. let checkEles = getAllElements(refreshByClickSel, document);
  1830. for (let i = 0; i < checkEles.length; i++) {
  1831. let curEle = checkEles[i];
  1832. if (curEle === e.target || curEle.contains(e.target)) {
  1833. ruleParser.urlChanged();
  1834. isPause = true;
  1835. if (!ruleParser.nextLinkHref) isLoading = false;
  1836. break;
  1837. }
  1838. }
  1839. }, 300);
  1840. }
  1841. }
  1842. }
  1843. document.removeEventListener("click", this.refreshByClickHandler);
  1844. document.addEventListener("click", this.refreshByClickHandler);
  1845. }
  1846. }
  1847.  
  1848. getValidSize(ele, win) {
  1849. if (!win) return {h: 0, w: 0};
  1850. let eleStyle = win.getComputedStyle(ele);
  1851. if (!ele.offsetParent && (eleStyle.position !== "fixed" || eleStyle.opacity === 0)) {
  1852. return {h: 0, w: 0};
  1853. }
  1854. if (ele.children && ele.children.length === 1 && (ele.offsetWidth === 0 || ele.offsetHeight === 0)) {
  1855. ele = ele.children[0];
  1856. }
  1857. let h = ele.scrollHeight, w;
  1858. if (eleStyle.overflow === "hidden") {
  1859. h = ele.offsetHeight;
  1860. w = ele.offsetWidth;
  1861. } else w = parseInt(ele.offsetWidth || ele.scrollWidth);
  1862. if (h === 0 && ele.parentNode && ele.parentNode.children.length === 1) {
  1863. h = ele.parentNode.scrollHeight;
  1864. }
  1865. while (h === 0 && ele.children && ele.children.length === 1) {
  1866. ele = ele.children[0];
  1867. h = ele.scrollHeight;
  1868. }
  1869. if (h === 0 && ele.children && ele.children.length) {
  1870. let maxChildSize = {h: 0}, self = this;
  1871. [].forEach.call(ele.children, el => {
  1872. let childSize = self.getValidSize(el, win);
  1873. if (childSize.h > maxChildSize.h) maxChildSize = childSize;
  1874. });
  1875. if (maxChildSize.h !== 0) return maxChildSize;
  1876. }
  1877. const maxNum = 2147483647;
  1878. let moreChild = ele.children[0], minOffsetTop = maxNum;
  1879. while (moreChild) {
  1880. if ((moreChild.offsetParent === ele || moreChild.offsetParent === ele.offsetParent)) {
  1881. let curOffsetTop = moreChild.offsetParent === ele.offsetParent ? moreChild.offsetTop - ele.offsetTop : moreChild.offsetTop;
  1882. if (curOffsetTop < minOffsetTop) {
  1883. minOffsetTop = curOffsetTop;
  1884. }
  1885. }
  1886. moreChild = moreChild.nextElementSibling;
  1887. }
  1888. if (h && minOffsetTop !== maxNum && minOffsetTop > 0) {
  1889. h -= minOffsetTop;
  1890. }
  1891. return {h: h, w: w};
  1892. }
  1893.  
  1894. checkTargetChildren(ele, curWin, articleNum, curHeight) {
  1895. let pf = false;
  1896. if (ele.parentNode) {
  1897. let paStyle = curWin.getComputedStyle(ele.parentNode);
  1898. let paDisplay = paStyle.display;
  1899. let paOverflow = paStyle.overflow;
  1900. pf = (paDisplay.indexOf('flex') !== -1 && paStyle.flexDirection.indexOf("row") === 0 && paStyle.flexWrap !== "wrap") || compareNodeName(ele.parentNode, ["ul"]) || paDisplay.indexOf('grid') !== -1 || paOverflow === "hidden";
  1901. }
  1902. let curStyle = curWin.getComputedStyle(ele);
  1903. if (ele.children.length > 1) {
  1904. if (articleNum > 1) {
  1905. return ">article";
  1906. } else {
  1907. let hasText = false;
  1908. for (let i in ele.childNodes) {
  1909. let child = ele.childNodes[i];
  1910. if (child.nodeType === 3 && child.nodeValue.trim() !== '') {
  1911. hasText = true;
  1912. break;
  1913. }
  1914. }
  1915. let gridArea = curStyle.gridArea;
  1916. if (gridArea && gridArea !== "auto" && gridArea !== "auto / auto / auto / auto") {
  1917. return ">*";
  1918. } else {
  1919. let middleChild = ele.children[parseInt(ele.children.length / 2)];
  1920. if ((curStyle.display === 'flex' && curStyle.flexDirection.indexOf("row") === 0 && curStyle.flexWrap !== "wrap") || (curStyle.float === "none" && curStyle.display !== "table-cell" && (rulesData.opacity !== 0 || hasText) && !pf)) {
  1921. return "";
  1922. } else if ((middleChild.style && middleChild.style.position === "absolute" && middleChild.style.left && middleChild.style.top) || compareNodeName(ele, ["ul"]) || curHeight === 0) {
  1923. return "";
  1924. } else {
  1925. return ">*";
  1926. }
  1927. }
  1928. }
  1929. } else if (pf || curStyle.position === "absolute") {
  1930. return ">*";
  1931. }
  1932. return "";
  1933. }
  1934.  
  1935. getPageElement(doc, curWin, dontFind) {
  1936. if (doc === document && this.docElementValid()) {
  1937. return this.docPageElement;
  1938. }
  1939. let pageElement = null;
  1940. let self = this;
  1941. let body = getBody(doc);
  1942. if (this.curSiteRule.pageElement) {
  1943. let pageElementSel = this.curSiteRule.pageElement;
  1944. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  1945. pageElementSel = pageElementSel[nextIndex < pageElementSel.length ? nextIndex : 0];
  1946. }
  1947. pageElement = getAllElements(pageElementSel, doc);
  1948. if (this.curSiteRule.smart && (!pageElement || pageElement.length === 0)) {
  1949. const childSelMatch = />\s*\*$/;
  1950. const targetChild = childSelMatch.test(pageElementSel);
  1951. if (targetChild) pageElementSel = pageElementSel.replace(childSelMatch, "");
  1952. let pageElementSelSplit = pageElementSel.split(">");
  1953. while(pageElementSelSplit && pageElementSelSplit.length > 5) {
  1954. pageElementSelSplit.shift();
  1955. let tempSel = pageElementSelSplit.join(">");
  1956. pageElement = getAllElements(tempSel, doc);
  1957. if (pageElement && pageElement.length === 1) {
  1958. if (targetChild) {
  1959. pageElement = pageElement.children;
  1960. }
  1961. this.curSiteRule.pageElement = tempSel + (targetChild ? ">*" : "");
  1962. break;
  1963. }
  1964. }
  1965. if (!pageElement || pageElement.length === 0) {
  1966. pageElementSel = pageElementSel.replace(/:nth-of-type\(\d+\)/g, "");
  1967. pageElement = getAllElements(pageElementSel, doc);
  1968. if (pageElement && pageElement.length === 1) {
  1969. if (targetChild) {
  1970. pageElement = pageElement.children;
  1971. }
  1972. this.curSiteRule.pageElement = pageElementSel + (targetChild ? ">*" : "");
  1973. }
  1974. }
  1975. }
  1976. if (this.curSiteRule.smart && pageElement && pageElement.length && curWin && curWin !== _unsafeWindow) {
  1977. let parent = pageElement[0].parentNode;
  1978. let loading = parent.querySelector('[class*=loading]');
  1979. if (loading && loading.offsetParent && loading.offsetHeight > parent.offsetHeight>>2) {
  1980. pageElement = null;
  1981. }
  1982. }
  1983. }
  1984. if (pageElement && pageElement.length === 1 && pageElement[0].style.display === 'none') {
  1985. pageElement = [body];
  1986. }
  1987. if (this.curSiteRule.smart && pageElement && pageElement.length > 0 && compareNodeName(pageElement[0], ["tr"])) {
  1988. let mainTr = this.insert.parentNode.querySelectorAll('tr'), mainTdNum = 0, newTdNum = 0;
  1989. mainTr = mainTr[mainTr.length - 1];
  1990. [].forEach.call(mainTr.children, el => {
  1991. if (compareNodeName(el, ["td", "th"])) {
  1992. mainTdNum += el.colSpan || 1;
  1993. }
  1994. });
  1995. [].forEach.call(pageElement[0].children, el => {
  1996. if (compareNodeName(el, ["td", "th"])) {
  1997. newTdNum += el.colSpan || 1;
  1998. }
  1999. });
  2000. if (mainTdNum !== newTdNum) {
  2001. this.curSiteRule.pageElement = this.curSiteRule.pageElement.replace(/> *table.*/, ">table");
  2002. this.getInsert(true);
  2003. return this.getPageElement(doc, curWin, dontFind);
  2004. }
  2005. }
  2006. if ((this.curSiteRule.smart || !this.curSiteRule.pageElement) && (!pageElement || pageElement.length == 0) && curWin && !dontFind) {
  2007. if (!body) return null;
  2008. let bodyHeight = parseInt(body.offsetHeight || body.scrollHeight);
  2009. let curHeight = bodyHeight, curWidth = 0;
  2010. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  2011. let windowWidth = window.innerWidth || document.documentElement.clientWidth;
  2012. let needCheckNext = (doc == document && this.initNext), nextLeftPos = 0;
  2013. if (needCheckNext && this.initNext.getBoundingClientRect) {
  2014. nextLeftPos = this.initNext.getBoundingClientRect().left;
  2015. }
  2016. function checkElement(ele) {
  2017. if (compareNodeName(ele, ["pre", "code"])) {
  2018. self.curSiteRule.pageElement = geneSelector(ele.parentNode);
  2019. debug(self.curSiteRule.pageElement, 'Page element');
  2020. return [ele.parentNode];
  2021. }
  2022. if (ele.children && ele.children.length === 1) {
  2023. let hasText = false;
  2024. for (let i in ele.childNodes) {
  2025. let child = ele.childNodes[i];
  2026. if (child.nodeType === 3 && child.nodeValue.trim() !== '') {
  2027. hasText = true;
  2028. break;
  2029. }
  2030. }
  2031. if (!hasText) {
  2032. ele = ele.children[0];
  2033. let validSize = self.getValidSize(ele, curWin);
  2034. curHeight = validSize.h;
  2035. curWidth = validSize.w;
  2036. }
  2037. }
  2038. if (compareNodeName(ele, ["picture"]) || !ele.innerText || ele.innerText.trim() === '') {
  2039. self.curSiteRule.pageElement = geneSelector(ele.parentNode) + ">" + ele.nodeName.toLowerCase();
  2040. debug(self.curSiteRule.pageElement, 'Page element');
  2041. let eles = [];
  2042. for (let i = 0; i < ele.parentNode.children.length; i++) {
  2043. let curNode = ele.parentNode.children[i];
  2044. if (curNode.nodeName === ele.nodeName && curNode.id === ele.id && curNode.className === ele.className) {
  2045. eles.push(curNode);
  2046. }
  2047. }
  2048. return eles;
  2049. }
  2050. if (compareNodeName(ele, ["form"]) && ele.parentNode !== getBody(document)) {
  2051. self.curSiteRule.pageElement = geneSelector(ele) + ">*";
  2052. debug(self.curSiteRule.pageElement, 'Page element');
  2053. return ele.children;
  2054. }
  2055. if (ele.children.length === 0 && !self.curSiteRule.pageElement) {
  2056. if (compareNodeName(ele.parentNode, ["p"])) ele = ele.parentNode;
  2057. self.curSiteRule.pageElement = geneSelector(ele.parentNode) + ">" + ele.nodeName.toLowerCase();
  2058. debug(self.curSiteRule.pageElement, 'Page element');
  2059. return getAllElements(self.curSiteRule.pageElement, doc);
  2060. }
  2061. let i, minHeight = curHeight * 0.52, curMaxEle = null, curMaxArea = 0, minWidth = Math.min(curWidth * 0.38, 500);
  2062. let isHori, preOffsetTop = -1;
  2063. let articleNum = 0;
  2064. for (i = 0; i < ele.children.length; i++) {
  2065. let curNode = ele.children[i];
  2066. if (ele !== body && /^H\d$/i.test(curNode.nodeName) && curNode.offsetParent) {
  2067. curMaxEle = null;
  2068. break;
  2069. }
  2070. if (compareNodeName(curNode, ["canvas", "nav"])) continue;
  2071. let curStyle = curWin.getComputedStyle(curNode);
  2072. if (!curNode.offsetParent && (curStyle.position !== "fixed" || curStyle.opacity === 0)) {
  2073. continue;
  2074. }
  2075. if (!compareNodeName(curNode, ["img"]) && curNode.querySelector('img') === null && /^\s*$/.test(curNode.innerText)) continue;
  2076. if (needCheckNext && !curNode.contains(self.initNext) && getElementTop(curNode) > windowHeight) {
  2077. continue;
  2078. }
  2079. if (compareNodeName(curNode, ["article"])) articleNum++;
  2080. let validSize = self.getValidSize(curNode, curWin);
  2081. let h = validSize.h;
  2082. let w = validSize.w;
  2083. if (isNaN(h) || isNaN(w) || !h || !w) continue;
  2084. isHori = Math.abs(preOffsetTop - curNode.offsetTop) <= 20 ? true : (preOffsetTop === -1 && curNode.nextElementSibling && curNode.nextElementSibling.offsetTop === curNode.offsetTop);
  2085. if (isHori && h <= 50) continue;
  2086. /*if (isHori && nextLeftPos && curMaxEle && curWidth > 500 && curHeight > 500) {
  2087. let curRect = curNode.getBoundingClientRect();
  2088. if (curRect.left > windowWidth>>2 && curRect.left <= nextLeftPos && curRect.right > nextLeftPos) {
  2089. continue;
  2090. }
  2091. }*/
  2092. let a = h * w, moreChild = curNode.children[0];
  2093. while (moreChild) {
  2094. let validSize = self.getValidSize(moreChild, curWin);
  2095. let ch = validSize.h;
  2096. let cw = validSize.w;
  2097. if (h < ch) {
  2098. h = ch;
  2099. }
  2100. if (moreChild.innerText !== "" && ch && cw) {
  2101. a += ch * cw;
  2102. }
  2103. moreChild = moreChild.nextElementSibling;
  2104. }
  2105. let isMax = false;
  2106. if (isHori) {
  2107. if (curMaxEle) {
  2108. if (w > curWidth && (windowWidth>>1) > curWidth) {
  2109. isMax = true;
  2110. } else if (w + 300 > curWidth && a > curMaxArea) {
  2111. isMax = true;
  2112. }
  2113. }
  2114. } else {
  2115. if (curMaxEle && curMaxEle.offsetParent === curNode.offsetParent && curMaxEle.offsetTop === curNode.offsetTop) {
  2116. if (curMaxArea * 2 > a) continue;
  2117. }
  2118. isMax = curMaxArea < a;
  2119. }
  2120. if (curMaxEle === null || isMax) {
  2121. if (isHori) {
  2122. if (w < minWidth) {
  2123. continue;
  2124. }
  2125. }
  2126. if (h < minHeight) {
  2127. if (!needCheckNext || h < (windowHeight>>1) || !ele.contains(self.initNext)) {
  2128. continue;
  2129. }
  2130. }
  2131. curHeight = h;
  2132. curMaxArea = a;
  2133. curWidth = w;
  2134. curMaxEle = curNode;
  2135. preOffsetTop = curNode.offsetTop;
  2136. }
  2137. }
  2138. let curHeightPercent = curHeight / bodyHeight;
  2139. if (curMaxEle && curHeightPercent <= 0.18) {
  2140. let article;
  2141. for (let i = 0; i < mainSel.length; i++) {
  2142. article = doc.querySelectorAll(mainSel[i]);
  2143. if (article && article.length === 1) break;
  2144. }
  2145. if (article && article.length === 1) {
  2146. article = article[0];
  2147. let childrenEnd = self.checkTargetChildren(article, curWin, articleNum, curHeight);
  2148. self.curSiteRule.pageElement = article.nodeName.toLowerCase() + (article.id ? "#" + article.id : "") + (article.className ? "." + article.className.replace(/ /g, ".") : "") + childrenEnd;
  2149. debug(self.curSiteRule.pageElement, 'Page element');
  2150. return childrenEnd ? article.children : [article];
  2151. }
  2152. curMaxEle = null;
  2153. }
  2154. if (curMaxEle && (!compareNodeName(curMaxEle, ["ul"]) || curHeightPercent > 0.8)) {
  2155. let sameClassNum = 0, hasDifferent = false;
  2156. if (curMaxEle.className) {
  2157. for(i = 0; i < ele.children.length; i++) {
  2158. let curNode = ele.children[i];
  2159. if (curMaxEle !== curNode && curNode.style.display !== 'none' && curMaxEle.className === curNode.className && curMaxEle.nodeName === curNode.nodeName){
  2160. sameClassNum++;
  2161. } else if (curMaxEle.className !== curNode.className) {
  2162. hasDifferent = true;
  2163. }
  2164. }
  2165. }
  2166. if (sameClassNum < 2 || (sameClassNum < 5 && hasDifferent)) {
  2167. return checkElement(curMaxEle);
  2168. }
  2169. }
  2170. if (ele.nodeName === "APP-ROOT") {
  2171. isPause = true;
  2172. debug(ele, "Angular root");
  2173. return null;
  2174. }
  2175. while (compareNodeName(ele, ["p", "br", "td"])) {
  2176. ele = ele.parentNode;
  2177. }
  2178. if (compareNodeName(ele, ["tbody"])) {
  2179. self.curSiteRule.pageElement = geneSelector(ele) + ">*";
  2180. if (ele.children.length > 0 && ele.children[0].querySelector("th")) {
  2181. self.curSiteRule.pageElement += ":not(:first-child)";
  2182. }
  2183. debug(self.curSiteRule.pageElement, 'Page element');
  2184. return ele.children;
  2185. }
  2186. let imgs = ele.querySelectorAll('img');
  2187. if (imgs.length === 1) {
  2188. let img = imgs[0];
  2189. if (img.offsetWidth > ele.offsetWidth / 3 * 2 && img.offsetHeight > ele.offsetHeight / 2) {
  2190. ele = img;
  2191. }
  2192. }
  2193. self.curSiteRule.pageElement = geneSelector(ele);
  2194. let childrenEnd = self.checkTargetChildren(ele, curWin, articleNum, curHeight);
  2195. if (childrenEnd) {
  2196. self.curSiteRule.pageElement += childrenEnd;
  2197. ele = ele.children;
  2198. } else {
  2199. ele = [ele];
  2200. }
  2201. debug(self.curSiteRule.pageElement, 'Page element');
  2202. return ele;
  2203. }
  2204. pageElement = checkElement(body);
  2205. if (pageElement && pageElement.length > 0 && self.initNext) {
  2206. let posEle = pageElement[pageElement.length - 1];
  2207. while (posEle && !posEle.offsetParent) {
  2208. posEle = posEle.previousElementSibling || posEle.parentNode;
  2209. }
  2210. let lastBottom = forceState !== 2 && forceState !== 3 && posEle && getElementBottom(posEle);
  2211. if (lastBottom && getElementTop(self.initNext) - lastBottom > 1000) {
  2212. debug("Stop as too long between next & page element, try to enable Force-Join mode.");
  2213. isPause = true;
  2214. pageElement = [];
  2215. sideController.remove();
  2216. } else {
  2217. if (pageElement.length === 1 && compareNodeName(pageElement[0], ["img"])) {
  2218. self.curSiteRule.pageBar = 0;
  2219. }
  2220. }
  2221. }
  2222. //if(pageElement)this.saveCurSiteRule();
  2223. }
  2224.  
  2225. if (doc !== document) {
  2226. this.setPageElementCss(pageElement);
  2227. this.lazyImgAction(pageElement, doc);
  2228. this.filterEles(doc, pageElement);
  2229. } else if (!this.docPageElement) {
  2230. this.setPageElementCss(pageElement, true);
  2231. this.docPageElement = pageElement;
  2232. this.filterEles(doc, pageElement);
  2233. if (this.nextLinkHref) {
  2234. this.openInNewTab(pageElement);
  2235. }
  2236. }
  2237. return pageElement;
  2238. }
  2239.  
  2240. showAddedElements() {
  2241. if (!this.addedElementsIsHide) return;
  2242. if (this.addedElePool && this.addedElePool.length) {
  2243. this.addedElePool.forEach(ele => {
  2244. ele.classList && ele.classList.remove("pagetual-hide");
  2245. });
  2246. }
  2247. this.addedElementsIsHide = false;
  2248. }
  2249.  
  2250. hideAddedElements() {
  2251. if (this.addedElePool && this.addedElePool.length) {
  2252. this.addedElePool.forEach(ele => {
  2253. ele.classList && ele.classList.add("pagetual-hide");
  2254. });
  2255. }
  2256. this.addedElementsIsHide = true;
  2257. }
  2258.  
  2259. toggleAddedElements() {
  2260. if (this.addedElementsIsHide) {
  2261. this.showAddedElements();
  2262. } else {
  2263. this.hideAddedElements();
  2264. }
  2265. }
  2266.  
  2267. changeVisibility() {
  2268. let contentVisibility = this.curSiteRule.contentVisibility || rulesData.contentVisibility;
  2269. if (!contentVisibility) return;
  2270. if (!this.changingVisibility) {
  2271. clearTimeout(this.changeVisibilityTimer);
  2272. this.changeVisibilityTimer = setTimeout(() => {
  2273. this.changingVisibility = true;
  2274. this.changeVisibility();
  2275. }, 300);
  2276. return;
  2277. }
  2278. this.changingVisibility = false;
  2279. if (!this.visibilityItems || !this.visibilityItems.length || this.visibleIndex < 0) return;
  2280. let tempIndex = this.visibleIndex, findVisible = false, lastVisible = 0;
  2281. let viewPortHeight = window.innerHeight || document.documentElement.clientHeight || getBody(document).clientHeight;
  2282. let checkItem = this.visibilityItems[tempIndex];
  2283. while(checkItem) {
  2284. if (checkItem.offsetParent) {
  2285. if (!checkItem.style.containIntrinsicSize) return;
  2286. let clientRect = checkItem.getBoundingClientRect();
  2287. let top = clientRect && clientRect.top;
  2288. let bottom = clientRect && clientRect.bottom;
  2289. if (bottom > 0 && top < viewPortHeight) {
  2290. if (!findVisible) {
  2291. findVisible = true;
  2292. lastVisible = tempIndex;
  2293. }
  2294. checkItem.style.contentVisibility = "visible";
  2295. } else {
  2296. if (top < viewPortHeight && checkItem.style.contentVisibility === "auto") {
  2297. break;
  2298. } else checkItem.style.contentVisibility = "auto";
  2299. }
  2300. }
  2301. if (tempIndex === 0) break;
  2302. tempIndex--;
  2303. checkItem = this.visibilityItems[tempIndex];
  2304. }
  2305. tempIndex = this.visibleIndex + 1;
  2306. if (findVisible) {
  2307. this.visibleIndex = lastVisible;
  2308. }
  2309. checkItem = this.visibilityItems[tempIndex];
  2310. while(checkItem) {
  2311. if (checkItem.offsetParent) {
  2312. if (!checkItem.style.containIntrinsicSize) return;
  2313. let clientRect = checkItem.getBoundingClientRect();
  2314. let top = clientRect && clientRect.top;
  2315. let bottom = clientRect && clientRect.bottom;
  2316. if (bottom > 0 && top < viewPortHeight) {
  2317. findVisible = true;
  2318. lastVisible = tempIndex;
  2319. checkItem.style.contentVisibility = "visible";
  2320. } else {
  2321. if (findVisible && checkItem.style.contentVisibility === "auto") {
  2322. break;
  2323. } else checkItem.style.contentVisibility = "auto";
  2324. }
  2325. }
  2326. if (tempIndex === this.visibilityItems.length - 1) break;
  2327. tempIndex++;
  2328. checkItem = this.visibilityItems[tempIndex];
  2329. }
  2330. if (findVisible) {
  2331. this.visibleIndex = lastVisible;
  2332. }
  2333. }
  2334.  
  2335. setPageElementCss(pageElement, init) {
  2336. let self = this;
  2337. if (pageElement && pageElement.length > 0) {
  2338. let pageElementCss = this.curSiteRule.pageElementCss || rulesData.pageElementCss;
  2339. if (!pageElementCss && init && !this.nextLinkHref) return;
  2340. let contentVisibility = this.curSiteRule.contentVisibility || rulesData.contentVisibility;
  2341. if (!contentVisibility && !pageElementCss) return;
  2342. [].forEach.call(pageElement, (ele, i) => {
  2343. if (!compareNodeName(ele, ["link", "meta", "style", "script"])) {
  2344. if (pageElementCss) {
  2345. if (pageElementCss !== '0' && !ele.dataset.pagetualPageElement) {
  2346. ele.style.cssText = (ele.style.cssText || '') + pageElementCss;
  2347. ele.dataset.pagetualPageElement = 1;
  2348. }
  2349. }
  2350. if (contentVisibility) {
  2351. ele.style.containIntrinsicSize = `auto ${ele.offsetHeight || self.preVisibleHeight || 100}px`;
  2352. if (ele.style.containIntrinsicSize) {
  2353. if (ele.offsetHeight) self.preVisibleHeight = ele.offsetHeight;
  2354. if (init) {
  2355. ele.style.contentVisibility = "visible";
  2356. self.visibilityItems.push(ele);
  2357. self.visibleIndex++;
  2358. } else {
  2359. ele.style.contentVisibility = emuIframe ? "visible" : "auto";
  2360. }
  2361. }
  2362. }
  2363. }
  2364. });
  2365. }
  2366. }
  2367.  
  2368. clearAddedElements() {
  2369. if (this.addedElePool && this.addedElePool.length) {
  2370. this.addedElePool.forEach(ele => {
  2371. if (ele.parentNode) ele.parentNode.removeChild(ele);
  2372. });
  2373. }
  2374. this.addedElePool = [];
  2375. sideController.remove();
  2376. }
  2377.  
  2378. linkHasHref(link) {
  2379. return link.href && link.href.replace && !this.hrefIsJs(link.href);
  2380. }
  2381.  
  2382. hrefIsJs(href) {
  2383. return /^(javascript|#|$)/.test(href.trim().replace("#p{", "").replace(location.href, ""));
  2384. }
  2385.  
  2386. async querySelectorList(source, list, defaultView) {
  2387. for (let i = 0; i < list.length; i++) {
  2388. await sleep(1);
  2389. let sel = list[i];
  2390. let result = source.querySelectorAll(sel);
  2391. if (result.length > 0) {
  2392. if (defaultView) {
  2393. for (let i = result.length - 1; i >= 0; i--) {
  2394. let ele = result[i];
  2395. if (isVisible(ele, defaultView)) return ele;
  2396. }
  2397. }
  2398. return result[result.length - 1];
  2399. }
  2400. }
  2401. return null;
  2402. }
  2403.  
  2404. verifyElement(ele) {
  2405. let verifyHandler = e => {
  2406. if (e.nodeType == 9) return true;
  2407. if (e.style.display === "none" || e.getAttribute("aria-disabled") === "true") {
  2408. return false;
  2409. }
  2410. if (e.className) {
  2411. if (/slick|slide|gallery|disabled\s*$/i.test(e.className)) {
  2412. return false;
  2413. } else if (e.classList) {
  2414. if (e.classList.contains('disabled') || e.classList.contains('active')) {
  2415. return false;
  2416. }
  2417. }
  2418. }
  2419. let ariaLabel = e.getAttribute("aria-label");
  2420. if (ariaLabel && /slick|slide|gallery/i.test(ariaLabel)) return false;
  2421. return true;
  2422. };
  2423. if (!ele) return false;
  2424. let i = 0;
  2425. while (ele && i++ < 6) {
  2426. if (!verifyHandler(ele)) return false;
  2427. ele = ele.parentNode;
  2428. }
  2429. return true;
  2430. }
  2431.  
  2432. async getPage(doc, exist) {
  2433. if (document.documentElement.className.indexOf && document.documentElement.className.indexOf('discourse') !== -1) return {};
  2434. let body = getBody(doc);
  2435. let canSave = false;//發現頁碼選擇器在其他頁對不上,還是別保存了
  2436. let url = this.curUrl.slice(0, 250).replace("index.php?", "?");
  2437. let _url = url.replace(/\.s?html?$/i, "").toLowerCase();
  2438. let pageNum = 1, preStr = "", afterStr = "";
  2439. let pageTwoReg = /^[\/\?&]?[_-]?(p|page)?=?\/?2(\/[^\/]*$|\?|&|$)/i;
  2440. let pageMatch1 = url.match(/(.*[\?&]p(?:age)?=)(\d+)($|[#&].*)/i);
  2441. let doubtTextReg = /^\s*(»|>>)\s*$/;
  2442. if (pageMatch1) {
  2443. preStr = pageMatch1[1];
  2444. pageNum = parseInt(pageMatch1[2]);
  2445. afterStr = pageMatch1[3];
  2446. } else {
  2447. let pageMatch2 = url.match(/(.*[a-z\/\-_](?:p|page)?\/?)(\d+)(\.s?html?$|\/?$)/i);
  2448. if (pageMatch2) {
  2449. preStr = pageMatch2[1];
  2450. pageNum = parseInt(pageMatch2[2]);
  2451. afterStr = pageMatch2[3];
  2452. if (/^\/?$/.test(afterStr) && !/(p(age)?|_|\-|\/)$/.test(preStr)) {
  2453. preStr = "";
  2454. afterStr = "";
  2455. }
  2456. }
  2457. }
  2458. if (pageNum > 999) {
  2459. pageNum = 1;
  2460. preStr = "";
  2461. afterStr = "";
  2462. }
  2463. let curPage = doc, i, cur, jsNext;
  2464. let next1, next2, next3, next4, nextJs1, nextJs2;
  2465. let selectorList = [
  2466. ".page-next>a",
  2467. "a.next_page",
  2468. "#next_page",
  2469. ".curPage+a",
  2470. ".nextPage",
  2471. ".pagination-next>a",
  2472. "a[data-pagination=next]",
  2473. ".pageButtonsCurrent+a",
  2474. "a[class*=nextpage]",
  2475. "li.page-current+li>a",
  2476. "[class^=pag] a[rel=next]",
  2477. "[class^=Pag] [aria-label=next]",
  2478. "[aria-label='Next Page']",
  2479. "[aria-label='Next page']",
  2480. "[aria-label='next page']",
  2481. ".pagination-nav__item--next>a",
  2482. "a.pageright",
  2483. ".page-numbers.current+a",
  2484. "a.page-numbers.next",
  2485. "body [class*=pagination] li.active+span+li>a",
  2486. "body [class*=pagination] li.active+li>a",
  2487. "body [class^=pag] .current+a",
  2488. ".page_current+a",
  2489. "input[value='next']",
  2490. "input[value='Next page']",
  2491. "input[value='下一页']",
  2492. "input[value='下一頁']",
  2493. "a#pb_next",
  2494. "a#rightFix",
  2495. "a#btnPreGn",
  2496. "a.page-next",
  2497. "a.pages-next",
  2498. "a.page.right",
  2499. ".paging>.active+.item",
  2500. "a#next",
  2501. ".next>a",
  2502. ".next>button",
  2503. "a[alt=next]",
  2504. ".pg_area>em+a",
  2505. "button.next:not([disabled])",
  2506. ".btn_next:not([disabled])",
  2507. ".btn-next:not([disabled])",
  2508. "a#linkNext",
  2509. "a[class*=page__next]",
  2510. "[class*=pager]>a.next",
  2511. "[class*=pagination-next]>a",
  2512. "[class*=pagination-next]>button",
  2513. "[class*=page--current]+li>a",
  2514. "[class*=Pages]>.curr+a"
  2515. ];
  2516. let next = await this.querySelectorList(body, selectorList, doc.defaultView);
  2517. if (!next) {
  2518. await sleep(1);
  2519. let nexts = body.querySelectorAll("a.next");
  2520. const prevReg = /^\s*([上前首尾]|previous)/i;
  2521. for (i = 0; i < nexts.length; i++) {
  2522. let n = nexts[i];
  2523. if (this.verifyElement(n) && this.linkHasHref(n) && !prevReg.test(n.innerText.trim())) {
  2524. next = n;
  2525. break;
  2526. }
  2527. }
  2528. }
  2529. if (next) {
  2530. let innerText = next.innerText;
  2531. let isJs = !this.linkHasHref(next);
  2532. if (innerText && nextTextReg2.test(innerText.trim())) {
  2533. if (isJs) {
  2534. if (this.verifyElement(next)) {
  2535. nextJs2 = next;
  2536. }
  2537. } else {
  2538. next2 = next;
  2539. }
  2540. next = null;
  2541. } else {
  2542. if (isJs) {
  2543. if (this.verifyElement(next)) {
  2544. jsNext = next;
  2545. }
  2546. next = null;
  2547. }
  2548. }
  2549. }
  2550. if (!next) {
  2551. await sleep(1);
  2552. next = body.querySelector("a.curr+a") ||
  2553. body.querySelector("div.wp-pagenavi>span.current+a,div.page-nav>span.current+a,div.article-paging>span+a") ||
  2554. body.querySelector(".number>ul>li.active+li>a");
  2555. }
  2556. if (!next) {
  2557. await sleep(1);
  2558. let pageDiv = body.querySelector(".pages>ul,.page_no>ul");
  2559. if (pageDiv) {
  2560. cur = pageDiv.querySelector("li>b,li>strong");
  2561. if (cur) next = cur.parentNode.nextElementSibling;
  2562. if (next) next = next.querySelector("a");
  2563. }
  2564. }
  2565. if (!next) {
  2566. await sleep(1);
  2567. next = body.querySelector(".pages>a[href='javascript:;']+a");
  2568. if (next && (next.href === "javascript:;" || next.getAttribute("href") === "#")) next = null;
  2569. }
  2570. if (!next) {
  2571. await sleep(1);
  2572. let pageDiv = body.querySelector(".pagination");
  2573. if (pageDiv) {
  2574. cur = pageDiv.querySelector("[class*=current],.page-selected");
  2575. if (cur) next = cur.parentNode.nextElementSibling;
  2576. if (next) next = next.querySelector("a");
  2577. }
  2578. }
  2579. if (!next) {
  2580. await sleep(1);
  2581. let pageDivs = body.querySelectorAll("[class*=pagination],[class*=Pagination]");
  2582. if (pageDivs && pageDivs.length) {
  2583. for (let i = pageDivs.length - 1; i >= 0; i--) {
  2584. let p = pageDivs[i];
  2585. if (/(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)/i.test(p.title || p.value || '')) {
  2586. next = p.querySelector("a,button,[type='button']") || p;
  2587. break;
  2588. } else if (/^(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)$/i.test((p.innerText || '').trim())) {
  2589. next = p.querySelector("a,button,[type='button']") || p;
  2590. break;
  2591. }
  2592. }
  2593. if (next && !this.linkHasHref(next)) {
  2594. if (!jsNext) jsNext = next;
  2595. next = null;
  2596. }
  2597. }
  2598. }
  2599. if (!next) {
  2600. let isApp = !!body.querySelector("main#app");
  2601. let aTags = body.querySelectorAll("a,button,[type='button']");
  2602. for (i = aTags.length - 1; i >= 0; i--) {
  2603. if (next1) break;
  2604. if (i % 100 === 0) {
  2605. await sleep(1);
  2606. }
  2607. let aTag = aTags[i];
  2608. let title = aTag.title || "";
  2609. let value = aTag.value || "";
  2610. let innerText = aTag.innerText || "";
  2611. if (innerText === "" || (title !== "" && title.length < innerText.length)) {
  2612. innerText = title;
  2613. }
  2614. if (innerText === "" || (value !== "" && value.length < innerText.length)) {
  2615. innerText = value;
  2616. }
  2617. if (innerText !== "") {
  2618. if (innerText === "§") continue;
  2619. innerText = innerText.trim();
  2620. if (innerText.length > 80) continue;
  2621. }
  2622. if (!this.verifyElement(aTag)) continue;
  2623. if (aTag.dataset && aTag.dataset.preview) continue;
  2624. let availableHref = aTag.href && aTag.href.length < 250 && /^http/.test(aTag.href);
  2625. if (availableHref && /next\-?(page)?$|\/video\/|\/vod\/play\//i.test(aTag.href)) continue;
  2626. if (compareNodeName(aTag.parentNode, ["blockquote"])) continue;
  2627. if (aTag.previousElementSibling && /\b(play|volume)\b/.test(aTag.previousElementSibling.className)) continue;
  2628. if (aTag.nextElementSibling && /\b(play|volume)\b/.test(aTag.nextElementSibling.className)) continue;
  2629. let isJs = !this.linkHasHref(aTag);
  2630. if (exist && isJs && !aTag.offsetParent) continue;
  2631. if (innerText) {
  2632. innerText = innerText.split(/\n/)[0].replace(/ /g, '');
  2633. if (isJs && /^(»|>>|>|›|→|❯)$/.test(innerText)) continue;
  2634. if (innerText && innerText.length <= 25) {
  2635. if (!next1) {
  2636. if (nextTextReg1.test(innerText)) {
  2637. if (isJs) {
  2638. if (!nextJs1) nextJs1 = aTag;
  2639. } else {
  2640. next1 = aTag;
  2641. }
  2642. }
  2643. }
  2644. if (!next4) {
  2645. if (!next2) {
  2646. if (nextTextReg2.test(innerText) || /nextpage|pager\-older/i.test(aTag.className) || /^(»|>>)$/.test(innerText)) {
  2647. if (isJs) {
  2648. if (!nextJs2) nextJs2 = aTag;
  2649. } else {
  2650. next2 = aTag;
  2651. }
  2652. }
  2653. }
  2654. if (!isApp && !next3 && !isJs) {
  2655. if (/^(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)$/i.test(aTag.textContent) && aTag.parentNode.hasAttribute && !aTag.parentNode.hasAttribute("jsaction")) {
  2656. next3 = aTag;
  2657. }
  2658. }
  2659. }
  2660. }
  2661. }
  2662. if (isJs) continue;
  2663. if (!next4) {
  2664. let prevEle = aTag.previousElementSibling;
  2665. if (prevEle && compareNodeName(prevEle, ["b", "span", "strong"])) {
  2666. if (/^\d+$/.test(aTag.innerText.trim()) && /^\d+$/.test(prevEle.innerText.trim()) && parseInt(aTag.innerText) === parseInt(prevEle.innerText) + 1) {
  2667. next4 = aTag;
  2668. }
  2669. }
  2670. }
  2671. if (urlWillChange) continue;
  2672. if (!next4 && availableHref) {
  2673. if (aTag.href.indexOf(location.hostname) === -1) continue;
  2674. let _aHref = aTag.href.replace("?&", "?").replace("index.php?", "?").toLowerCase();
  2675. if (preStr || afterStr) {
  2676. let _aHrefTrim = _aHref;
  2677. if (preStr) _aHrefTrim = _aHrefTrim.replace(preStr, "");
  2678. if (afterStr) _aHrefTrim = _aHrefTrim.replace(afterStr, "");
  2679. if (_aHrefTrim == pageNum + 1) {
  2680. next4 = aTag;
  2681. }
  2682. } else if (this.curUrl !== aTag.href) {
  2683. _aHref = _aHref.replace(/\.s?html?$/i, "");
  2684. if (_aHref.indexOf(_url) !== -1) {
  2685. let pageTwoMatch = _aHref.replace(_url, "").match(pageTwoReg);
  2686. if (pageTwoMatch) {
  2687. afterStr = pageTwoMatch[2];
  2688. next4 = aTag;
  2689. }
  2690. }
  2691. }
  2692. if (next4 && !/page/.test(next4.href)) {
  2693. let curHref = next4.getAttribute("href");
  2694. let curPageReg = new RegExp("(.*)" + (pageNum + 1) + afterStr.replace(/([\.\?])/g, '\\$1'));
  2695. let otherPageHref = curHref.replace(curPageReg, `$1${pageNum}${afterStr}`);
  2696. let otherPageEle = body.querySelector(`a[href='${otherPageHref}']`);
  2697. if (!otherPageEle) {
  2698. otherPageHref = curHref.replace(curPageReg, `$1${pageNum + 2}${afterStr}`);
  2699. otherPageEle = body.querySelector(`a[href='${otherPageHref}']`);
  2700. }
  2701. if (otherPageEle) {
  2702. let parent = otherPageEle.parentNode;
  2703. if (parent && parent.parentNode) {
  2704. parent = parent.parentNode;
  2705. if (parent.parentNode) {
  2706. parent = parent.parentNode;
  2707. }
  2708. }
  2709. if (parent && parent.contains(next4) && !/^\d+$/.test(next4.innerText.trim())) {
  2710. next4 = null;
  2711. }
  2712. }
  2713. }
  2714. }
  2715. }
  2716. if (next2 && doubtTextReg.test(next2.innerText)) {
  2717. next2 = this.verifyNext(next2, doc, false);
  2718. }
  2719. if (nextJs2 && doubtTextReg.test(nextJs2.innerText)) {
  2720. nextJs2 = this.verifyNext(nextJs2, doc, true);
  2721. }
  2722. if (next3) {
  2723. next3 = this.verifyNext(next3, doc, false);
  2724. }
  2725. }
  2726. if (!next) next = next1 || next4 || next3 || next2;
  2727. if (!next && location.pathname + location.search !== "/") {
  2728. next = jsNext || nextJs1 || nextJs2;
  2729. if (next && next.parentNode.className && next.parentNode.className.indexOf && next.parentNode.className.indexOf('tab') !== -1) next = null;
  2730. }
  2731. if (next && next.classList && (next.classList.contains("results-more") || next.classList.contains("no"))) next = null;
  2732. if (next && next.hasAttribute && next.hasAttribute("disabled")) next = null;
  2733. if (next && next.parentNode.href && compareNodeName(next.parentNode, ["a"])) next = next.parentNode;
  2734. return {next:next, canSave:canSave};
  2735. }
  2736.  
  2737. verifyNext(next, doc, isJs) {
  2738. if (!next) return null;
  2739. if (!isJs) {
  2740. let href = next.getAttribute("href");
  2741. if (href && !/\d/.test(next.getAttribute("href"))) {
  2742. return null;
  2743. }
  2744. }
  2745. if (next.previousElementSibling && compareNodeName(next.previousElementSibling, ["br"])) return null;
  2746. let eles = [];
  2747. if (next.innerText && next.innerText.indexOf("\n") === -1) {
  2748. eles = getAllElements(`//${next.nodeName}[text()='${next.innerText}']`, doc);
  2749. }
  2750. if (eles.length >= 2 && eles[0].href !== eles[1].href) {
  2751. next = null;
  2752. } else if (doc === document) {
  2753. let left = getElementLeft(next);
  2754. if (left < 20 || (document.documentElement.scrollWidth > 500 && left < 250)) {
  2755. next = null;
  2756. } else {
  2757. let top = getElementTop(next);
  2758. if (top < 20 || (left < window.innerWidth / 3 && top < window.innerHeight / 3)) {
  2759. next = null;
  2760. } else {
  2761. let bottom = top + next.offsetHeight || 0;
  2762. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  2763. if (scrollH - bottom < 10) next = null;
  2764. }
  2765. }
  2766. }
  2767. return next;
  2768. }
  2769.  
  2770. canonicalUri(src) {
  2771. if (!src) {
  2772. return "";
  2773. }
  2774. if (src.charAt(0) === "#") return this.curUrl + src;
  2775. if (src.charAt(0) === "?") return this.curUrl.replace(/^([^\?#]+).*/, "$1" + src);
  2776. let origin = location.protocol + '//' + location.host;
  2777. let url = this.basePath || origin;
  2778. url = url.replace(/(\?|#).*/, "");
  2779. if (/https?:\/\/[^\/]+$/.test(url)) url = url + '/';
  2780. if (url.indexOf("http") !== 0) url = origin + url;
  2781. var root_page = /^[^\?#]*\//.exec(url)[0],
  2782. root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  2783. absolute_regex = /^\w+\:\/\//;
  2784. this.updateUrl = false;
  2785. while (src.indexOf("../") === 0) {
  2786. src = src.substr(3);
  2787. root_page = root_page.replace(/\/[^\/]+\/$/, "/");
  2788. this.updateUrl = true;
  2789. }
  2790. src = src.replace(/\.\//, "");
  2791. if (/^\/\/\/?/.test(src)) {
  2792. src = location.protocol + src;
  2793. }
  2794. return (absolute_regex.test(src) ? src : ((src.charAt(0) === "/" ? root_domain : root_page) + src));
  2795. }
  2796.  
  2797. getLinkByPage(url, pageNum) {
  2798. if (!url) return null;
  2799. if (this.curSiteRule.pageNum) {
  2800. let result = this.curSiteRule.pageNum;
  2801. let strMatch = result.match(/\{.*?}/);
  2802. if (!strMatch) return null;
  2803. let urlReg = new RegExp("(" + result.replace(strMatch[0], ")\\d+(") + ")", "i");
  2804. let code = strMatch[0].replace(/^{/, "").replace(/}$/, "").replace(/\$p/g, pageNum);
  2805. if (code === pageNum) {
  2806. result = url.replace(urlReg, "$1" + code + "$2");
  2807. } else {
  2808. try {
  2809. code = Function('"use strict";return ' + code)();
  2810. if (code && code % 1 == 0) {
  2811. result = url.replace(urlReg, "$1" + code + "$2");
  2812. } else return null;
  2813. } catch(e) {
  2814. debug(e);
  2815. }
  2816. }
  2817. if (result != url) {
  2818. return result;
  2819. }
  2820. }
  2821. return url.replace(/([&\/\?](p=|page[=\/_-]?))\d+/i, "$1" + pageNum).replace(/([_-])\d+\./i, "$1" + pageNum + ".");
  2822. }
  2823.  
  2824. getPageNumFromUrl(url, defaultPage) {
  2825. if (!url) return defaultPage;
  2826. if (this.curSiteRule.pageNum) {
  2827. let result = this.curSiteRule.pageNum;
  2828. let strMatch = result.match(/\{.*?}/);
  2829. if (!strMatch) return defaultPage;
  2830. let urlReg = new RegExp(".*" + result.replace(strMatch[0], "(\\d+)") + ".*", "i");
  2831. let curShowNum = url.replace(urlReg, "$1");
  2832. if (curShowNum !== url) {
  2833. let code = strMatch[0].replace(/^{/, "").replace(/}$/, "");
  2834. if (code === "$p") {
  2835. return curShowNum;
  2836. } else {
  2837. try {
  2838. let page1 = parseInt(Function('"use strict";return ' + code.replace("$p", "0"))());
  2839. let page2 = parseInt(Function('"use strict";return ' + code.replace("$p", "1"))());
  2840. let numGap = page2 - page1;
  2841. let _page = (parseInt(curShowNum) - page1) / numGap;
  2842. if (_page && _page % 1 === 0) return _page;
  2843. else {
  2844. this.curSiteRule.pageNum = null;
  2845. return defaultPage;
  2846. }
  2847. } catch(e) {
  2848. debug(e);
  2849. }
  2850. }
  2851. } else {
  2852. return defaultPage;
  2853. }
  2854. }
  2855. let pageNum = url.replace(/.*[&\/\?](p=|page[=\/_-]?)(\d+).*/i, "$2");
  2856. return pageNum === url ? defaultPage : (pageNum.length > 4 ? defaultPage : pageNum);
  2857. }
  2858.  
  2859. async getNextLink(doc, exist) {
  2860. let nextLink = null, page, href;
  2861. let getNextLinkByForm = (form, submitBtn, n) => {
  2862. let params = [];
  2863. let formData = new FormData(form);
  2864. if (submitBtn && submitBtn.getAttribute) {
  2865. let btnValue, btnName;
  2866. btnName = submitBtn.getAttribute("name");
  2867. btnValue = submitBtn.getAttribute("value");
  2868. if (btnName && btnValue) params = [btnName + "=" + encodeURIComponent(btnValue)];
  2869. }
  2870. for (let [key, value] of formData) {
  2871. if (n && /^(p|page)$/i.test(key)) {
  2872. params.push(key + '=' + n);
  2873. } else {
  2874. params.push(key + '=' + encodeURIComponent(value));
  2875. }
  2876. }
  2877. params = params.join('&');
  2878. return form.action + (form.action.indexOf('?') === -1 ? '?' : '&') + params + (form.method === 'post' ? '#p{' + params + '}' : '');
  2879. };
  2880. if (this.curSiteRule.pageElementByJs) {
  2881. this.nextLinkHref = "#";
  2882. return true;
  2883. } else if (this.curSiteRule.nextLinkByJs) {
  2884. try {
  2885. let over = _url => {};
  2886. let targetUrl = await ((typeof this.curSiteRule.nextLinkByJs === 'function') ? this.curSiteRule.nextLinkByJs : new AsyncFunction("doc", '"use strict";' + this.curSiteRule.nextLinkByJs))(doc);
  2887. if (targetUrl) nextLink = {href: targetUrl};
  2888. } catch(e) {
  2889. debug(e);
  2890. }
  2891. } else if (this.curSiteRule.nextLinkByUrl) {
  2892. let targetUrl = this.curUrl.replace(new RegExp(this.curSiteRule.nextLinkByUrl[0], "i"), this.curSiteRule.nextLinkByUrl[1]);
  2893. if (targetUrl !== this.curUrl) {
  2894. let includeSel = this.curSiteRule.nextLinkByUrl[2];
  2895. let excludeSel = this.curSiteRule.nextLinkByUrl[3];
  2896. if (includeSel) {
  2897. includeSel = includeSel.trim();
  2898. if (!getElement(includeSel, doc)) {
  2899. this.nextLinkHref=false;
  2900. return null;
  2901. }
  2902. }
  2903. if (excludeSel) {
  2904. excludeSel = excludeSel.trim();
  2905. if (getElement(excludeSel, doc)) {
  2906. this.nextLinkHref=false;
  2907. return null;
  2908. }
  2909. }
  2910. let reps = targetUrl.match(/{.*?}/g);
  2911. if (reps) {
  2912. reps.forEach(rep => {
  2913. let code = rep.replace("{", "").replace("}", "").replace(/\(\)/g, "0");
  2914. let result = code.match(/^(\d*)\+1$/);
  2915. if (result) {
  2916. result = parseInt(result[1] || 1) + 1;
  2917. } else {
  2918. try {
  2919. result = Function('"use strict";return ' + code)();
  2920. } catch(e) {
  2921. debug(e);
  2922. }
  2923. }
  2924. targetUrl = targetUrl.replace(rep, result);
  2925. });
  2926. }
  2927. }
  2928. nextLink = {href: targetUrl};
  2929. } else if (typeof this.curSiteRule.nextLink !== 'undefined') {
  2930. let nextLinkSel = this.curSiteRule.nextLink;
  2931. if (nextLinkSel != 0) {
  2932. if (Array && Array.isArray && Array.isArray(nextLinkSel)) {
  2933. nextLink = getElement(nextLinkSel[nextIndex], doc, null, true);
  2934. if (!nextLink && curPage === 1 && nextIndex !== 0) {
  2935. nextIndex = 0;
  2936. nextLink = getElement(nextLinkSel[nextIndex], doc, null, true);
  2937. }
  2938. } else nextLink = getElement(nextLinkSel, doc, null, true);
  2939. }
  2940. if (nextLink && (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2)) {
  2941. let form = doc.querySelector('#search-form');
  2942. if (!nextLink.href && nextLink.hasAttribute && nextLink.hasAttribute("onclick") && form) {
  2943. if (/^\d+$/.test(nextLink.innerText)) {
  2944. nextLink.href = getNextLinkByForm(form, nextLink, nextLink.innerText);
  2945. }
  2946. } else if (compareNodeName(nextLink, ["input"]) || nextLink.type === "submit") {
  2947. form = nextLink.parentNode;
  2948. while (form) {
  2949. if (compareNodeName(form, ["form"])) break;
  2950. else form = form.parentNode;
  2951. }
  2952. if (form) {
  2953. nextLink.href = getNextLinkByForm(form, nextLink);
  2954. }
  2955. }
  2956. if (nextLink.href && this.curSiteRule.action != 0) {
  2957. nextLink.href = nextLink.href.replace(/#p{.*/, "");
  2958. }
  2959. }
  2960. } else {
  2961. page = await this.getPage(doc, exist);
  2962. nextLink = page.next;
  2963. if (nextLink) {
  2964. if (compareNodeName(nextLink, ["input"]) || nextLink.type === "submit") {
  2965. if (!/next/i.test(nextLink.getAttribute("onclick"))) {
  2966. let form = nextLink.parentNode;
  2967. while (form) {
  2968. if (compareNodeName(form, ["form"])) break;
  2969. else form = form.parentNode;
  2970. }
  2971. if (form) {
  2972. nextLink.href = getNextLinkByForm(form, nextLink);
  2973. }
  2974. }
  2975. }
  2976. let parent = nextLink;
  2977. while (parent && !compareNodeName(parent, ["body"])) {
  2978. if (parent.hasAttribute && parent.hasAttribute("disabled")) {
  2979. this.nextLinkHref = false;
  2980. return null;
  2981. }
  2982. if (parent.className && parent.classList) {
  2983. if (parent.classList.contains("noClick") || parent.classList.contains("no-pages") || parent.classList.contains("disabled")) {
  2984. this.nextLinkHref = false;
  2985. return null;
  2986. }
  2987. }
  2988. if (parent.style && parent.style.display === "none") {
  2989. this.nextLinkHref = false;
  2990. return null;
  2991. }
  2992. parent = parent.parentNode;
  2993. }
  2994. if (doc === document) {
  2995. if (!this.linkHasHref(nextLink)) {
  2996. if ((clickedSth && this.curSiteRule.smart) || !isVisible(nextLink, _unsafeWindow)) {
  2997. this.nextLinkHref = false;
  2998. return null;
  2999. }
  3000. let video = document.querySelector("video,iframe[id*=play],[id*=play]>iframe,iframe[src*=player],iframe[src*=m3u8]");
  3001. if (video) {
  3002. if (video.offsetParent && video.name !== 'pagetual-iframe') {
  3003. let scrollWidth = video.scrollWidth || video.offsetWidth;
  3004. let scrollHeight = video.scrollHeight || video.offsetHeight;
  3005. if (compareNodeName(video, ["iframe"])) {
  3006. } else if (scrollWidth > 100 && scrollHeight > 100) {
  3007. let winWidth = window.innerWidth || document.documentElement.clientWidth;
  3008. let winHeight = window.innerHeight || document.documentElement.clientHeight;
  3009. if (scrollWidth > winWidth>>1 && scrollHeight > winHeight>>1) {
  3010. debug("Disable when large media found");
  3011. } else {
  3012. video = null;
  3013. }
  3014. } else {
  3015. video = null;
  3016. }
  3017. } else {
  3018. video = null;
  3019. }
  3020. }
  3021. if (video) {
  3022. isPause = true;
  3023. this.clearAddedElements();
  3024. this.nextLinkHref = false;
  3025. return null;
  3026. }
  3027. }
  3028.  
  3029. let nextLinkCs = _unsafeWindow.getComputedStyle(nextLink);
  3030. if (nextLinkCs.cursor === "not-allowed") {
  3031. this.nextLinkHref = false;
  3032. return null;
  3033. }
  3034. this.initNext = nextLink;
  3035. }
  3036. let form = doc.querySelector('#search-form');
  3037. if (!nextLink.href && nextLink.hasAttribute("onclick") && form) {
  3038. if (form && /^\d+$/.test(nextLink.innerText)) {
  3039. href = getNextLinkByForm(form, nextLink, nextLink.innerText);
  3040. }
  3041. }
  3042. }
  3043. }
  3044. if (nextLink) {
  3045. if (!this.checkStopSign(nextLink, doc)) {
  3046. if (curPage > 1 && rulesData.lastPageTips) showTips(i18n("lastPage"), "", 800);
  3047. return null;
  3048. }
  3049. if (this.curSiteRule.action == 3) {
  3050. if (doc == document) debug(nextLink, 'Next link');
  3051. this.nextLinkHref = '#';
  3052. } else {
  3053. let needUrl = (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2);
  3054. if (!href) href = nextLink.href;
  3055. if (href && nextLink.getAttribute) {
  3056. let _href = nextLink.getAttribute("href");
  3057. if (_href) {
  3058. if (_href.charAt(0) === "#" || _href === "?"){
  3059. href = "#";
  3060. } else {
  3061. href = _href;
  3062. }
  3063. } else if (_href === "") {
  3064. href = _href;
  3065. }
  3066. }
  3067.  
  3068. if (needUrl && (href === "" || href === null)) {
  3069. this.nextLinkHref = false;
  3070. } else if (needUrl && /^(javascript:|#)/.test(href)) {
  3071. this.nextLinkHref = false;
  3072. } else {
  3073. this.nextLinkHref = (href && !/^(javascript:|#)/.test(href)) ? this.canonicalUri(href) : "#";
  3074. let tempUrl = this.nextLinkHref;
  3075. 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 + "#"))) {
  3076. this.nextLinkHref = false;
  3077. } else if (doc === document) {
  3078. debug(nextLink, 'Next link');
  3079. }
  3080. }
  3081. }
  3082. } else {
  3083. this.nextLinkHref = false;
  3084. }
  3085. this.nextLinkEle = nextLink;
  3086. this.preload();
  3087. return nextLink;
  3088. }
  3089.  
  3090. compareUrl(url1, url2) {
  3091. if (url1 === url2) return true;
  3092. if (!url1 || !url2) return false;
  3093. let url1Arr = url1.split("?");
  3094. let url2Arr = url2.split("?");
  3095. if (url1Arr[0] != url2Arr[0]) return false;
  3096. if (!url1Arr[1] || !url2Arr[1]) return false;
  3097. url1Arr = url1Arr[1].split("&").sort().join("&");
  3098. url2Arr = url2Arr[1].split("&").sort().join("&");
  3099. return url1Arr === url2Arr;
  3100. }
  3101.  
  3102. filterEles(doc, eles) {
  3103. let filter = this.curSiteRule.filter;
  3104. if (!filter || !eles || eles.length === 0) return;
  3105. if (eles.length === 1) {
  3106. eles = eles[0].children;
  3107. if (eles.length === 1) {
  3108. eles = eles[0].children;
  3109. }
  3110. }
  3111. if (typeof filter === "string") {
  3112. if (/^\d+$/.test(filter)) {
  3113. filter = {count: parseInt(filter)};
  3114. } else filter = {words: filter};
  3115. }
  3116. [].forEach.call(eles, ele => {
  3117. if (!ele.parentNode) return;
  3118. let canKeep = (() => {
  3119. let innerText = (ele.innerText && ele.innerText.trim()) || "";
  3120. if (filter.count) {
  3121. if (innerText.length < filter.count) return false;
  3122. }
  3123. if (filter.words) {
  3124. let wordsRegExp = new RegExp(filter.words, "i");
  3125. if (innerText && wordsRegExp.test(innerText)) return false;
  3126. }
  3127. if (filter.link) {
  3128. let linkRegExp = new RegExp(filter.link, "i");
  3129. if (compareNodeName(ele, ["a"]) && linkRegExp.test(ele.href)) return false;
  3130. let aChildren = ele.querySelectorAll("a");
  3131. for (let i = 0; i < aChildren.length; i++) {
  3132. let child = aChildren[i];
  3133. if (linkRegExp.test(child.href)) return false;
  3134. }
  3135. }
  3136. if (filter.selector) {
  3137. if (getElement(filter.selector, doc, ele)) return false;
  3138. }
  3139. return true;
  3140. })();
  3141. if (!canKeep) {
  3142. ele.parentNode.removeChild(ele);
  3143. }
  3144. });
  3145. }
  3146.  
  3147. checkStopSign(nextLink, doc) {
  3148. if (this.curSiteRule.stopSign) {
  3149. let typeArray = Array && Array.isArray && Array.isArray(this.curSiteRule.stopSign);
  3150. let typeObject = !typeArray && (this.curSiteRule.stopSign.include || this.curSiteRule.stopSign.exclude || this.curSiteRule.stopSign.pageNum);
  3151. if (typeArray || typeObject) {
  3152. let includeSel, excludeSel, curSign, maxSign;
  3153. if (typeArray) {
  3154. includeSel = this.curSiteRule.stopSign[0];
  3155. excludeSel = this.curSiteRule.stopSign[1];
  3156. curSign = this.curSiteRule.stopSign[2];
  3157. maxSign = this.curSiteRule.stopSign[3];
  3158. if (Array && Array.isArray && Array.isArray(includeSel) && !curSign) {
  3159. curSign = includeSel;
  3160. includeSel = false;
  3161. }
  3162. if (excludeSel && Array && Array.isArray && Array.isArray(excludeSel) && !maxSign) {
  3163. maxSign = excludeSel;
  3164. excludeSel = false;
  3165. }
  3166. } else {
  3167. includeSel = this.curSiteRule.stopSign.include;
  3168. excludeSel = this.curSiteRule.stopSign.exclude;
  3169. curSign = this.curSiteRule.stopSign.pageNum;
  3170. }
  3171. if (includeSel) {
  3172. includeSel = includeSel.trim();
  3173. if (!getElement(includeSel, doc)) {
  3174. isPause = true;
  3175. this.nextLinkHref = false;
  3176. return false;
  3177. }
  3178. }
  3179. if (excludeSel) {
  3180. excludeSel = excludeSel.trim();
  3181. if (getElement(excludeSel, doc)) {
  3182. isPause = true;
  3183. this.nextLinkHref = false;
  3184. return false;
  3185. }
  3186. }
  3187. if (curSign) {
  3188. if (!maxSign) maxSign = curSign.slice(2);
  3189. let currentEle = getElement(curSign[0], doc);
  3190. let maxEle = getElement(maxSign[0], doc);
  3191. if (currentEle && maxEle) {
  3192. let currentSignNum, maxSignNum;
  3193. if (/\(.*\)/.test(curSign[1])) {
  3194. currentSignNum = currentEle.innerText.match(new RegExp(curSign[1]));
  3195. if (currentSignNum) currentSignNum = currentSignNum[1];
  3196. } else if (currentEle.getAttribute) {
  3197. currentSignNum = currentEle.getAttribute(curSign[1]);
  3198. }
  3199. if (/\(.*\)/.test(maxSign[1])) {
  3200. maxSignNum = maxEle.innerText.match(new RegExp(maxSign[1]));
  3201. if (maxSignNum) maxSignNum = maxSignNum[1];
  3202. } else if (maxEle.getAttribute) {
  3203. maxSignNum = maxEle.getAttribute(maxSign[1]);
  3204. }
  3205. if (currentSignNum && maxSignNum && currentSignNum == maxSignNum) {
  3206. isPause = true;
  3207. this.nextLinkHref = false;
  3208. return false;
  3209. }
  3210. }
  3211. }
  3212. } else {
  3213. try {
  3214. let stopSign = ((typeof this.curSiteRule.stopSign === 'function') ? this.curSiteRule.stopSign : Function("doc", "nextLink", '"use strict";' + this.curSiteRule.stopSign))(doc, nextLink);
  3215. if (stopSign) {
  3216. isPause = true;
  3217. this.nextLinkHref = false;
  3218. return false;
  3219. }
  3220. } catch(e) {
  3221. debug(e);
  3222. }
  3223. }
  3224. }
  3225. return true;
  3226. }
  3227.  
  3228. preloadImageHandler() {
  3229. if (this.preloadingImage || !this.unCheckedImgs.length) return;
  3230. this.preloadingImage = true;
  3231. setTimeout(() => {
  3232. this.preloadingImage = false;
  3233. this.preloadImageHandler();
  3234. }, 10);
  3235. let iSrc = this.unCheckedImgs.shift();
  3236. let img = document.createElement('img');
  3237. img.src = iSrc;
  3238. this.preloadDiv.appendChild(img);
  3239. }
  3240.  
  3241. preload() {
  3242. if (!rulesData.preload) return;
  3243. if (this.curSiteRule.preload === 0) return;
  3244. if (!this.nextLinkHref || this.nextLinkHref == "#") return;
  3245. if (this.readyStateUnComplete) return;
  3246. if (document.readyState !== 'complete') {
  3247. this.readyStateUnComplete = true;
  3248. let self = this;
  3249. window.addEventListener("load", e => {
  3250. self.readyStateUnComplete = false;
  3251. self.preload();
  3252. });
  3253. return;
  3254. }
  3255. let self = this, url = this.nextLinkHref;
  3256. let postParams = url.match(/#p{(.*)}$/);
  3257. if (postParams) {
  3258. postParams = postParams[1];
  3259. url = url.replace(/#p{.*/, "");
  3260. }
  3261. _GM_xmlhttpRequest({
  3262. url: url,
  3263. method: postParams ? 'POST' : 'GET',
  3264. data: postParams,
  3265. overrideMimeType: 'text/html;charset=' + charset,
  3266. headers: {
  3267. 'Referer': location.href,
  3268. 'User-Agent': navigator.userAgent,
  3269. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + charset,
  3270. },
  3271. timeout: 10000,
  3272. onload: function(res) {
  3273. var doc = null;
  3274. try {
  3275. doc = document.implementation.createHTMLDocument('');
  3276. doc.documentElement.innerHTML = createHTML(res.response);
  3277. var body = getBody(doc);
  3278. if (!self.preloadDiv) {
  3279. self.preloadDiv = document.createElement('div');
  3280. self.preloadDiv.id = "pagetual-preload";
  3281. self.preloadDiv.style.cssText = 'display:none!important;';
  3282. getBody(document).appendChild(self.preloadDiv);
  3283. self.checkedImgs = {};
  3284. self.unCheckedImgs = [];
  3285. }
  3286. let code = self.curSiteRule.preloadImages;
  3287. if (code) {
  3288. let imgSrcArr = new Function("doc", '"use strict";' + code)(doc);
  3289. if (imgSrcArr && imgSrcArr.length) {
  3290. imgSrcArr.forEach(imgSrc => {
  3291. if (imgSrc && !self.checkedImgs[imgSrc]) {
  3292. self.checkedImgs[imgSrc] = true;
  3293. self.unCheckedImgs.push(imgSrc);
  3294. }
  3295. });
  3296. }
  3297. self.preloadImageHandler();
  3298. } else if (code !== 0 && code !== false) {
  3299. if (body && body.firstChild) {
  3300. self.lazyImgAction(body.children, doc);
  3301. }
  3302. [].forEach.call(doc.images, i => {
  3303. let iSrc = i.src;
  3304. if (iSrc && !self.checkedImgs[iSrc]) {
  3305. self.checkedImgs[iSrc] = true;
  3306. self.unCheckedImgs.push(iSrc);
  3307. }
  3308. });
  3309. self.preloadImageHandler();
  3310. }
  3311. }
  3312. catch(e) {
  3313. debug(e);
  3314. return;
  3315. }
  3316. }
  3317. });
  3318. }
  3319.  
  3320. getInsert(refresh) {
  3321. if (refresh) {
  3322. this.insert = null;
  3323. }
  3324. if (this.insert && this.insert.parentNode && document.documentElement.contains(this.insert)) {
  3325. return this.insert;
  3326. }
  3327. if (this.curSiteRule.insert) {
  3328. let insertSel = this.curSiteRule.insert;
  3329. if (Array && Array.isArray && Array.isArray(insertSel)) {
  3330. insertSel = insertSel[nextIndex < insertSel.length ? nextIndex : 0];
  3331. }
  3332. this.insert = getElement(insertSel, document, null, true);
  3333. } else {
  3334. this.docPageElement = null;
  3335. let pageElement = this.getPageElement(document, _unsafeWindow);
  3336. if (this.curSiteRule.smart && this.nextLinkHref == "#" && this.curSiteRule.pageElement === 'body') {
  3337. debug("Stop as jsNext & whole body");
  3338. isPause = true;
  3339. return null;
  3340. }
  3341. if (pageElement && pageElement.length > 0) {
  3342. let pEIndex = pageElement.length - 1;
  3343. let pELast = pageElement[pEIndex];
  3344. while(pELast && compareNodeName(pELast, ["link", "meta", "style", "script"])) {
  3345. pEIndex--;
  3346. pELast = pageElement[pEIndex];
  3347. }
  3348. this.insert = pELast.nextSibling ? pELast.nextSibling : pELast.parentNode.appendChild(document.createTextNode(' '));
  3349. }
  3350. }
  3351. return this.insert;
  3352. }
  3353.  
  3354. pageInit(doc, eles) {
  3355. let code = this.curSiteRule.pageInit;
  3356. if (code) {
  3357. let initFunc = ((typeof code == 'function') ? code : Function("doc", "eles", '"use strict";' + code));
  3358. let checkInit = (resolve) => {
  3359. try {
  3360. if (initFunc(doc, eles) === false) {
  3361. setTimeout(() => {
  3362. checkInit(resolve);
  3363. }, 100);
  3364. } else {
  3365. resolve(true);
  3366. }
  3367. } catch(e) {
  3368. resolve(false);
  3369. debug(e);
  3370. }
  3371. };
  3372. return new Promise((resolve) => {
  3373. checkInit(function(e) {
  3374. resolve(e)
  3375. });
  3376. })
  3377. }
  3378. }
  3379.  
  3380. pageAction(doc, eles) {
  3381. let code = this.curSiteRule.pageAction;
  3382. if (code) {
  3383. try {
  3384. ((typeof code == 'function') ? code : Function("doc", "eles", '"use strict";' + code))(doc, eles);
  3385. } catch(e) {
  3386. debug(e);
  3387. }
  3388. }
  3389. this.openInNewTab(eles);
  3390. this.replaceElement(doc);
  3391. }
  3392.  
  3393. openInNewTab(eles) {
  3394. if (openInNewTab) {
  3395. [].forEach.call(eles, ele => {
  3396. if (compareNodeName(ele, ["a"]) && ele.href && !/^(mailto:|javascript:)|#/.test(ele.href)) {
  3397. ele.setAttribute('target', openInNewTab == 1 ? '_blank' : '_self');
  3398. } else {
  3399. [].forEach.call(ele.querySelectorAll('a[href]:not([href^="mailto:"]):not([href^="javascript:"]):not([href^="#"])'), a => {
  3400. if (openInNewTab == 1) {
  3401. a.setAttribute('target', '_blank');
  3402. if (a.getAttribute('onclick') == 'atarget(this)') {
  3403. a.removeAttribute('onclick');
  3404. }
  3405. } else a.setAttribute('target', '_self');
  3406. });
  3407. }
  3408. });
  3409. }
  3410. }
  3411.  
  3412. lazyImgAction(eles, doc) {
  3413. if (!eles || eles.length == 0) return;
  3414. let lazyImgSrc = this.curSiteRule.lazyImgSrc;
  3415. if (lazyImgSrc === 0 || lazyImgSrc === '0') return;
  3416. let imgLazyAttrs = [];
  3417. 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"];
  3418. let removeProps = [];
  3419. let setLazyImg = img => {
  3420. let realSrc;
  3421. imgLazyAttrs.forEach(attr => {
  3422. realSrc = img.getAttribute(lazyImgSrc[0]);
  3423. if (realSrc) {
  3424. removeProps.forEach(prop => {
  3425. img.removeAttribute(prop.trim());
  3426. });
  3427. img.src = realSrc;
  3428. return;
  3429. }
  3430. })
  3431. if (!realSrc) {
  3432. let lazyAttr = "";
  3433. if (img.getAttribute("_src") && !img.src) {
  3434. lazyAttr = "_src";
  3435. realSrc = img.getAttribute(lazyAttr);
  3436. } else {
  3437. for (let i in lazyImgAttr) {
  3438. lazyAttr = lazyImgAttr[i];
  3439. let attrValue = img.getAttribute(lazyAttr);
  3440. if (attrValue) {
  3441. realSrc = attrValue;
  3442. break;
  3443. }
  3444. }
  3445. }
  3446. if (!realSrc && img._lazyrias && img._lazyrias.srcset) {
  3447. realSrc = img._lazyrias.srcset[img._lazyrias.srcset.length - 1];
  3448. lazyAttr = "_lazyrias";
  3449. }
  3450. if (!realSrc && img.srcset) {
  3451. lazyAttr = "srcset";
  3452. var srcs = img.srcset.split(/[xw],/i), largeSize = 0;
  3453. srcs.forEach(srci => {
  3454. let srcInfo = srci.trim().split(" "), curSize = parseInt(srcInfo[1]);
  3455. if (srcInfo[1] && curSize > largeSize) {
  3456. largeSize = curSize;
  3457. realSrc = srcInfo[0];
  3458. }
  3459. });
  3460. }
  3461. if (realSrc) {
  3462. img.src = realSrc;
  3463. img.removeAttribute("srcset");
  3464. img.removeAttribute(lazyAttr);
  3465. if (img.classList && img.classList.contains && img.classList.contains("lazy")) {
  3466. img.classList.remove("lazy");
  3467. }
  3468. if (img.style.display == "none") {
  3469. img.style.display = "";
  3470. }
  3471. if (img.style.visibility == "hidden") {
  3472. img.style.visibility = "";
  3473. }
  3474. if (img.style.opacity == 0) {
  3475. img.style.opacity = "";
  3476. }
  3477. }
  3478. }
  3479. };
  3480. if (lazyImgSrc) {
  3481. if (!Array.isArray(lazyImgSrc)) {
  3482. lazyAttrs = lazyImgSrc.split(",");
  3483. } else {
  3484. lazyAttrs = lazyImgSrc[0].split(",");
  3485. removeProps = lazyImgSrc[1].split(",");
  3486. }
  3487. }
  3488. lazyAttrs.forEach(attr => {
  3489. let attrArr = attr.split("|");
  3490. if (attrArr.length !== 2) {
  3491. imgLazyAttrs.push(attr.trim());
  3492. } else {
  3493. let selector = attrArr[0].trim();
  3494. let lazyAttr = attrArr[1].trim();
  3495. if (selector == "img") {
  3496. imgLazyAttrs.push(lazyAttr);
  3497. } else {
  3498. selector += "[" + lazyAttr + "]";
  3499. [].forEach.call(doc.querySelectorAll(selector), ele => {
  3500. ele.style.setProperty("background-image", "url(" + ele.getAttribute(lazyAttr) + ")", "important");
  3501. removeProps.forEach(prop => {
  3502. ele.removeAttribute(prop.trim());
  3503. });
  3504. });
  3505. }
  3506. }
  3507. });
  3508. [].forEach.call(doc.querySelectorAll("img,picture>source"), img => {
  3509. setLazyImg(img);
  3510. });
  3511. }
  3512.  
  3513. canListenUrlChange() {
  3514. if (this.curSiteRule && typeof this.curSiteRule.listenUrlChange === 'undefined' && this.docElementValid()) {
  3515. return false;
  3516. }
  3517. return true;
  3518. }
  3519.  
  3520. docElementValid() {
  3521. return (this.docPageElement && document.documentElement.contains(this.docPageElement[0]));
  3522. }
  3523.  
  3524. urlChanged() {
  3525. urlChanged = true;
  3526. this.clearAddedElements();
  3527. }
  3528.  
  3529. initPage(callback) {
  3530. let self = this;
  3531. if (self.initing) return;
  3532. self.initing = true;
  3533. setTimeout(() => {
  3534. self.initing = false;
  3535. }, 100);
  3536. curPage = 1;
  3537. urlChanged = false;
  3538. tryTimes = 0;
  3539. this.clearAddedElements();
  3540. this.insert = null;
  3541. this.visibilityItems = [];
  3542. this.visibleIndex = -1;
  3543. this.pageDoc = document;
  3544. this.nextLinkHref = null;
  3545. this.curUrl = location.href;
  3546. this.oldUrl = "";
  3547. this.initUrl = location.href;
  3548. this.historyUrl = "";
  3549. this.possibleCheck = 0;
  3550. let base = document.querySelector("base");
  3551. this.basePath = base ? base.href : location.href;
  3552. this.getRule(async () => {
  3553. if (self.curSiteRule.sideController === true || (self.curSiteRule.sideController !== false && rulesData.sideController)) {
  3554. isPause = manualPause;
  3555. }
  3556. if (typeof(self.curSiteRule.rate) !== "undefined") {
  3557. rate = self.curSiteRule.rate;
  3558. }
  3559. if (self.curSiteRule.enable == 0) {
  3560. debug("Stop as rule disable");
  3561. isPause = true;
  3562. _GM_registerMenuCommand(i18n("enable"), () => {
  3563. showTips(i18n("enableSiteTips"));
  3564. if(!self.customRules) {
  3565. self.customRules = [];
  3566. }
  3567. for (let i in self.customRules) {
  3568. if (self.customRules[i].url == self.curSiteRule.url) {
  3569. self.customRules.splice(i, 1);
  3570. break;
  3571. }
  3572. }
  3573. self.curSiteRule.enable = 1;
  3574. self.customRules.unshift(self.curSiteRule);
  3575. storage.setItem("customRules", self.customRules);
  3576. location.reload();
  3577. });
  3578. return;
  3579. }
  3580. if (rulesData.sideControllerAlways) {
  3581. sideController.setup();
  3582. }
  3583. //若是再亂匹配就不緩存wedata,或者只在找完本地規則之後再考慮wedata的緩存
  3584. if (self.curSiteRule.smart) {
  3585. delete self.curSiteRule.pageElement;
  3586. if (!self.possibleRule) {
  3587. self.smartRules = self.smartRules.filter(item => {return item && item.url != self.curSiteRule.url});
  3588. self.smartRules.unshift(self.curSiteRule);
  3589. if (self.smartRules.length > 100) {
  3590. self.smartRules.pop();
  3591. }
  3592. storage.setItem("smartRules", self.smartRules);
  3593. }
  3594. } else if (self.curSiteRule && self.curSiteRule.url.length > 13) {
  3595. self.addToHpRules();
  3596. }
  3597. let css = self.curSiteRule.css || rulesData.customCss;
  3598. if (css) {
  3599. let cssArr = css.split("inIframe:");
  3600. if (cssArr && cssArr.length) {
  3601. _GM_addStyle(cssArr[0]);
  3602. }
  3603. }
  3604. if (/sidesearch=(1|true)$/.test(self.curUrl)) {
  3605. openInNewTab = 0;
  3606. } else if (typeof self.curSiteRule.openInNewTab !== 'undefined') {
  3607. openInNewTab = self.curSiteRule.openInNewTab ? 1 : 2;
  3608. }
  3609. let autoClick = self.curSiteRule.autoClick;
  3610. if (autoClick) {
  3611. let autoClickBtn;
  3612. autoClickBtn = getElement(autoClick, document, null, true);
  3613. if (autoClickBtn) {
  3614. emuClick(autoClickBtn);
  3615. }
  3616. }
  3617. let code = self.curSiteRule.init;
  3618. if (code) {
  3619. try {
  3620. 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)});
  3621. } catch(e) {
  3622. debug(e);
  3623. }
  3624. }
  3625. await self.getNextLink(document, true);
  3626. if (self.curSiteRule.pageNum && self.nextLinkHref && self.nextLinkHref != "#") {
  3627. let num1st = self.getPageNumFromUrl(location.href, 1);
  3628. let num2nd = self.getPageNumFromUrl(self.nextLinkHref, 1);
  3629. if (num2nd != num1st + 1) {
  3630. self.curSiteRule.pageNum = null;
  3631. }
  3632. }
  3633. if (self.curSiteRule.smart && self.nextLinkHref == false && self.possibleRule) {
  3634. let urlReg = new RegExp(self.possibleRule.url, "i");
  3635. function checkPossible () {
  3636. if (self.possibleCheck++ < 3) {
  3637. setTimeout(() => {
  3638. if (self.curSiteRule.smart) {
  3639. var href = location.href.slice(0, 500);
  3640. if (urlReg.test(href) && self.ruleMatch(self.possibleRule)) {
  3641. self.initPage(() => {});
  3642. } else checkPossible();
  3643. }
  3644. }, 3000);
  3645. }
  3646. }
  3647. checkPossible();
  3648. }
  3649. self.refreshByClick();
  3650. if (emuIframe && emuIframe.parentNode) {
  3651. emuIframe.parentNode.removeChild(emuIframe);
  3652. emuIframe = null;
  3653. }
  3654.  
  3655. let pageElementCss = self.curSiteRule.pageElementCss || rulesData.pageElementCss;
  3656. if (pageElementCss && pageElementCss !== '0') {
  3657. self.getPageElement(document, _unsafeWindow);
  3658. }
  3659. callback();
  3660. let initRun = typeof self.curSiteRule.initRun == 'undefined' ? rulesData.initRun : self.curSiteRule.initRun;
  3661. if (self.nextLinkHref) {
  3662. sideController.setup();
  3663. if (initRun && initRun != false) {
  3664. setTimeout(() => {
  3665. nextPage();
  3666. }, 300);
  3667. }
  3668. }
  3669. });
  3670. }
  3671.  
  3672. async hookUrlSetEle(ele, doc) {
  3673. let self = this;
  3674. return new Promise((resolve) => {
  3675. let catchUrl = e => {
  3676. ele.dataset.url = self.catchedUrl;
  3677. ele.setAttribute('onclick', 'window.open(this.dataset.url)');
  3678. window.removeEventListener('pagetual_openUrl', catchUrl);
  3679. resolve();
  3680. };
  3681. window.addEventListener('pagetual_openUrl', catchUrl);
  3682. emuClick(ele, doc);
  3683. });
  3684. }
  3685.  
  3686. async hookUrl(doc) {
  3687. let sel = this.curSiteRule.hookUrl;
  3688. if (!sel) return;
  3689. let self = this;
  3690. if (!this.initHook) {
  3691. this.initHook = true;
  3692. Object.defineProperty(doc.defaultView, 'open', {
  3693. get: function () {
  3694. return (s) => {
  3695. self.catchedUrl = s;
  3696. var e = new CustomEvent('pagetual_openUrl');
  3697. window.dispatchEvent(e);
  3698. }
  3699. }
  3700. });
  3701. }
  3702. let eles = getAllElements(sel, doc);
  3703. for (let i = 0; i < eles.length; i++) {
  3704. await sleep(1);
  3705. let ele = eles[i];
  3706. if (!ele.dataset.url) {
  3707. await this.hookUrlSetEle(ele, doc);
  3708. }
  3709. }
  3710. }
  3711.  
  3712. beginLoading() {
  3713. isLoading = true;
  3714. if (targetY >= 0) {
  3715. window.scrollTo({ top: targetY, behavior: 'instant'});
  3716. targetY = -1;
  3717. }
  3718. let lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3719. ruleParser.insertElement(loadingDiv);
  3720. if (forceState == 2) {
  3721. getBody(document).appendChild(loadingDiv);
  3722. } else {
  3723. let parent = loadingDiv.parentNode;
  3724. if (compareNodeName(parent, ["tbody"])) {
  3725. parent = parent.parentNode;
  3726. }
  3727. if (compareNodeName(parent, ["table"])) {
  3728. parent.parentNode.appendChild(loadingDiv);
  3729. }
  3730. }
  3731. getBody(document).scrollTop = lastScrollTop;
  3732. document.documentElement.scrollTop = lastScrollTop;
  3733. }
  3734.  
  3735. insertElement(ele) {
  3736. if (!this.insert || !this.insert.parentNode) {
  3737. this.getInsert();
  3738. }
  3739. if (this.insert && this.insert.parentNode) {
  3740. let self = this;
  3741. if (ele.nodeName == "#document-fragment") {
  3742. [].forEach.call(ele.children, el => {
  3743. self.addedElePool.push(el);
  3744. });
  3745. } else {
  3746. this.addedElePool.push(ele);
  3747. }
  3748. if (this.curSiteRule.insertPos == 2 || this.curSiteRule.insertPos == "in") {
  3749. this.insert.appendChild(ele);
  3750. } else {
  3751. this.insert.parentNode.insertBefore(ele, this.insert);
  3752. }
  3753. }
  3754. }
  3755.  
  3756. noValidContent(url) {
  3757. if (!this.curSiteRule.nextLinkByUrl) showTips(i18n("noValidContent"), url);
  3758. }
  3759.  
  3760. async insertPage(doc, eles, url, callback, tried) {
  3761. this.oldUrl = this.curUrl;
  3762. let oldTitle = document.title;
  3763. try {
  3764. let oldTitle = this.pageDoc.title;
  3765. } catch (e) {}
  3766. this.pageDoc = doc;
  3767. this.curUrl = url;
  3768. isLoading = true;
  3769. let nextLink = await this.getNextLink(doc);
  3770. this.nextTitle = "";
  3771. if (this.curSiteRule.pageBarText) {
  3772. if (this.curSiteRule.pageBarText == 1 || this.curSiteRule.pageBarText == true) {
  3773. this.nextTitle = doc.title;
  3774. } else {
  3775. try {
  3776. this.nextTitle = ((typeof this.curSiteRule.pageBarText == 'function') ? this.curSiteRule.pageBarText : Function("doc",'"use strict";' + this.curSiteRule.pageBarText))(doc);
  3777. } catch(e) {
  3778. debug(e);
  3779. }
  3780. }
  3781. }
  3782. if (curPage == 1 && !tried && !nextLink && this.curSiteRule.smart && this.curSiteRule.pageElement && this.curSiteRule.action != 0) {
  3783. this.curSiteRule.action = 1;
  3784. this.curUrl = location.href;
  3785. isLoading = false;
  3786. return false;
  3787. }
  3788.  
  3789. if (targetY >= 0) {
  3790. window.scrollTo({ top: targetY, behavior: 'instant'});
  3791. targetY = -1;
  3792. }
  3793. let lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3794. this.getInsert();
  3795. await this.pageInit(doc, eles);
  3796. var self = this, newEles = [];
  3797. if (!eles || eles.length == 0 || !self.insert || !self.insert.parentNode) {
  3798. if (callback) callback(eles);
  3799. loadPageOver();
  3800. } else {
  3801. if (callback) callback(eles);
  3802. loadPageOver();
  3803. const collection = document.createDocumentFragment();
  3804. [].forEach.call(eles, ele => {
  3805. let newEle = ele.cloneNode(true);
  3806. let oldCanvass = ele.querySelectorAll("canvas");
  3807. let newCanvass = newEle.querySelectorAll("canvas");
  3808. if (self.updateUrl) {
  3809. [].forEach.call(newEle.querySelectorAll("img"), img => {
  3810. if (img.getAttribute("src")) img.src = self.canonicalUri(img.getAttribute("src"));
  3811. });
  3812. [].forEach.call(newEle.querySelectorAll("a"), a => {
  3813. if (a.getAttribute("href")) a.href = self.canonicalUri(a.getAttribute("href"));
  3814. });
  3815. }
  3816. for (let i = 0; i < oldCanvass.length; i++) {
  3817. let oldCanvas = oldCanvass[i];
  3818. let newCanvas = newCanvass[i];
  3819. newCanvas.getContext('2d').drawImage(oldCanvas, 0, 0);
  3820. }
  3821. if (!compareNodeName(newEle, ["style", "script"])) self.visibilityItems.push(newEle);
  3822. collection.appendChild(newEle)
  3823. newEles.push(newEle);
  3824. });
  3825. self.insertElement(collection);
  3826. }
  3827. getBody(document).scrollTop = lastScrollTop;
  3828. document.documentElement.scrollTop = lastScrollTop;
  3829. this.pageAction(doc, newEles);
  3830. let enableHistory = this.curSiteRule.history;
  3831. let enableHistoryAfterInsert = false;
  3832. if (enableHistory == 1) {
  3833. enableHistory = true;
  3834. } else if (enableHistory == 2) {
  3835. enableHistory = true;
  3836. enableHistoryAfterInsert = true;
  3837. } else if (enableHistory == 0) {
  3838. enableHistory = false;
  3839. } else {
  3840. enableHistory = rulesData.enableHistory;
  3841. enableHistoryAfterInsert = rulesData.enableHistoryAfterInsert;
  3842. }
  3843. if (enableHistory) {
  3844. this.historyUrl = enableHistoryAfterInsert ? this.curUrl : this.oldUrl;
  3845. if(this.historyUrl != location.href) {
  3846. let isJs = this.hrefIsJs(this.historyUrl);
  3847. if (!isJs) {
  3848. let historyTitle = enableHistoryAfterInsert ? doc.title : oldTitle;
  3849. _unsafeWindow.history.replaceState(undefined, historyTitle, this.historyUrl);
  3850. document.title = historyTitle;
  3851. }
  3852. }
  3853. }
  3854. isLoading = false;
  3855. return true;
  3856. }
  3857. }
  3858. var ruleParser = new RuleParser();
  3859.  
  3860. class SideController {
  3861. //static controller;
  3862. constructor() {
  3863. this.inited = false;
  3864. }
  3865.  
  3866. /*static getInstance() {
  3867. if (!SideController.controller) {
  3868. SideController.controller = new SideController();
  3869. }
  3870. return SideController.controller;
  3871. }*/
  3872.  
  3873. setup() {
  3874. if (ruleParser.curSiteRule.sideController === false) return;
  3875. if (!rulesData.sideController && !ruleParser.curSiteRule.sideController) return;
  3876. this.addToStage();
  3877. }
  3878.  
  3879. init() {
  3880. if (this.inited) return;
  3881. this.inited = true;
  3882. let self = this;
  3883. this.cssText = `
  3884. #pagetual-sideController {
  3885. position: fixed;
  3886. top: calc(50% - 83px);
  3887. left: calc(99% - 40px);
  3888. width: 40px;
  3889. border-radius: 20px;
  3890. box-shadow: rgb(0 0 0) 0px 0px 10px;
  3891. text-align: center;
  3892. background: #ffffffd0!important;
  3893. user-select: none;
  3894. z-index: 2147483646!important;
  3895. padding: 0!important;
  3896. opacity: 0.35;
  3897. transition: opacity .5s ease, background .5s, box-shadow .5s;
  3898. }
  3899. #pagetual-sideController * {
  3900. font-weight: bold;
  3901. font-family: arial;
  3902. font-style: normal;
  3903. font-size: 20px!important;
  3904. color: black!important;
  3905. line-height: normal;
  3906. float: none;
  3907. text-align: center;
  3908. }
  3909. #pagetual-sideController.stop {
  3910. -webkit-filter: invert(100%);
  3911. filter: invert(100%);
  3912. }
  3913. .pagetual-sideController-btn {
  3914. padding: 5px 0;
  3915. cursor: pointer;
  3916. transition: transform .15s ease-in-out, opacity .3s ease;
  3917. }
  3918. #pagetual-sideController .pagetual-sideController-btn:hover {
  3919. transform: scale(1.5);
  3920. color: red!important;
  3921. }
  3922. #pagetual-sideController #pagetual-sideController-move > svg {
  3923. transition: transform .3s ease;
  3924. }
  3925. #pagetual-sideController #pagetual-sideController-move > svg:hover {
  3926. transform: scale(1.2);
  3927. }
  3928. #pagetual-sideController.minSize #pagetual-sideController-move > svg {
  3929. background: white;
  3930. opacity: 0;
  3931. }
  3932. #pagetual-sideController #pagetual-sideController-move > img,
  3933. #pagetual-sideController #pagetual-sideController-move > span {
  3934. width: 35px;
  3935. height: 35px;
  3936. cursor: pointer;
  3937. }
  3938. #pagetual-sideController.minSize #pagetual-sideController-move > img,
  3939. #pagetual-sideController.minSize #pagetual-sideController-move > span {
  3940. border-radius: 50px;
  3941. text-shadow: rgb(255 255 255) 0px 0px 10px;
  3942. }
  3943. #pagetual-sideController #pagetual-sideController-pagenum {
  3944. font-size: 15px!important;
  3945. line-height: 30px;
  3946. text-align: center;
  3947. position: absolute;
  3948. right: calc(50% - 15px);
  3949. top: calc(50% - 15px);
  3950. border: 1px solid #00000099;
  3951. display: inline-block;
  3952. width: 30px;
  3953. height: 30px;
  3954. box-sizing: border-box;
  3955. border-radius: 50%;
  3956. background: white;
  3957. opacity: 0;
  3958. transition: opacity .5s ease;
  3959. pointer-events: none;
  3960. }
  3961. #pagetual-sideController.minSize #pagetual-sideController-pagenum {
  3962. opacity: 0.8;
  3963. }
  3964. #pagetual-sideController:hover {
  3965. opacity: 1;
  3966. }
  3967. #pagetual-sideController>.extra {
  3968. bottom: 170px;
  3969. left: 0px;
  3970. width: 40px;
  3971. position: absolute;
  3972. }
  3973. #pagetual-sideController>.extra>svg {
  3974. width: 40px;
  3975. height: 30px;
  3976. opacity: 0.1;
  3977. cursor: pointer;
  3978. margin: 0 0 5px 0;
  3979. transition: opacity .3s ease;
  3980. }
  3981. #pagetual-sideController.minSize>.extra>svg {
  3982. opacity: 0;
  3983. }
  3984. #pagetual-sideController>.extra>svg:hover {
  3985. opacity: 1;
  3986. }
  3987. #pagetual-sideController.minSize {
  3988. box-shadow: rgb(0 0 0 / 0%) 0px 0px 0px;
  3989. background: #00000000!important;
  3990. pointer-events: none;
  3991. }
  3992. #pagetual-sideController.minSize #pagetual-sideController-move {
  3993. pointer-events: all;
  3994. }
  3995. #pagetual-sideController.minSize .pagetual-sideController-btn {
  3996. opacity: 0;
  3997. }
  3998. `;
  3999. let frame = document.createElement("div");
  4000. frame.id = "pagetual-sideController";
  4001. frame.innerHTML = createHTML(`
  4002. <div class="extra">
  4003. <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>
  4004. <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>
  4005. </div>
  4006. <div id="pagetual-sideController-top" class="pagetual-sideController-btn">⊼</div>
  4007. <div>
  4008. <div id="pagetual-sideController-pre" class="pagetual-sideController-btn">∧</div>
  4009. <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>
  4010. <div id="pagetual-sideController-next" class="pagetual-sideController-btn">∨</div>
  4011. </div>
  4012. <div id="pagetual-sideController-bottom" class="pagetual-sideController-btn">⊻</div>
  4013. `);
  4014. frame.classList.add("stop");
  4015. let top = frame.querySelector("#pagetual-sideController-top");
  4016. let pre = frame.querySelector("#pagetual-sideController-pre");
  4017. let move = frame.querySelector("#pagetual-sideController-move");
  4018. let next = frame.querySelector("#pagetual-sideController-next");
  4019. let bottom = frame.querySelector("#pagetual-sideController-bottom");
  4020. let pagenum = frame.querySelector("#pagetual-sideController-pagenum");
  4021. let scroll = frame.querySelector("#scroll");
  4022. let loadNow = frame.querySelector("#loadNow");
  4023. if (rulesData.sideControllerScroll === false) {
  4024. scroll.style.display = "none";
  4025. }
  4026. if (rulesData.sideControllerLoadNow === false) {
  4027. loadNow.style.display = "none";
  4028. }
  4029. if (sideControllerIcon) move.innerHTML = sideControllerIcon;
  4030.  
  4031. frame.addEventListener("dblclick", e => {
  4032. e.preventDefault();
  4033. e.stopPropagation();
  4034. });
  4035.  
  4036. frame.addEventListener("mouseenter", e => {
  4037. clearTimeout(self.hideTimer);
  4038. frame.classList.remove("minSize");
  4039. });
  4040.  
  4041. frame.addEventListener("mouseleave", e => {
  4042. clearTimeout(self.hideTimer);
  4043. self.hideTimer = setTimeout(() => {
  4044. frame.classList.add("minSize");
  4045. }, 800);
  4046. });
  4047.  
  4048. document.body.addEventListener('touchstart', e => {
  4049. if (e.target === frame || frame.contains(e.target)) {
  4050. frame.classList.remove("minSize");
  4051. } else {
  4052. frame.classList.add("minSize");
  4053. }
  4054. });
  4055.  
  4056. scroll.addEventListener("click", e => {
  4057. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  4058. autoScroll = parseInt(autoScroll) || 0;
  4059. if (autoScroll < 0) autoScroll = 0;
  4060. if (autoScroll && autoScroll != autoScrollRate) {
  4061. autoScrollRate = autoScroll;
  4062. storage.setItem("autoScrollRate", autoScrollRate);
  4063. }
  4064. setListData("autoScroll", location.host + location.pathname, autoScroll);
  4065. startAutoScroll();
  4066. }, true);
  4067.  
  4068. loadNow.addEventListener("click", e => {
  4069. if (autoLoadNum != -1) {
  4070. autoLoadNum = -1;
  4071. return;
  4072. }
  4073. let loadNum = window.prompt(i18n("loadConfirm"), loadNowNum);
  4074. if (loadNum === "" || loadNum === null) return;
  4075. loadNum = Math.abs(parseInt(loadNum)) || 0;
  4076. if (loadNowNum != loadNum) {
  4077. loadNowNum = loadNum;
  4078. storage.setItem("loadNowNum", loadNowNum);
  4079. }
  4080. autoLoadNum = loadNum;
  4081. nextPage();
  4082. }, true);
  4083.  
  4084. pre.addEventListener("click", e => {
  4085. let prePageBar = getPageBar().preBar;
  4086. if (prePageBar) {
  4087. scrollToPageBar(prePageBar);
  4088. } else {
  4089. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  4090. targetY = scrollTop - (window.innerHeight || document.documentElement.clientHeight);
  4091. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4092. }
  4093. }, true);
  4094.  
  4095. next.addEventListener("click", e => {
  4096. let pageBarObj = getPageBar();
  4097. let nextPageBar = pageBarObj.nextBar;
  4098. if (nextPageBar) {
  4099. scrollToPageBar(nextPageBar);
  4100. } else {
  4101. if (pageBarObj.preBar) {
  4102. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  4103. targetY = scrollH || 9999999;
  4104. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4105. } else {
  4106. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  4107. targetY = scrollTop + (window.innerHeight || document.documentElement.clientHeight);
  4108. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4109. }
  4110. }
  4111. }, true);
  4112.  
  4113. top.addEventListener("click", e => {
  4114. getBody(document).scrollTop=0;
  4115. document.documentElement.scrollTop=0;
  4116. e.preventDefault();
  4117. e.stopPropagation();
  4118. }, true);
  4119.  
  4120. bottom.addEventListener("click", e => {
  4121. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  4122. changeStop(true);
  4123. }
  4124. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  4125. getBody(document).scrollTop = scrollH || 9999999;
  4126. document.documentElement.scrollTop = scrollH || 9999999;
  4127. e.preventDefault();
  4128. e.stopPropagation();
  4129. }, true);
  4130.  
  4131. let initX, initY, moving = false;
  4132. let removeTimer;
  4133. move.addEventListener("click", e => {
  4134. if (!moving) {
  4135. changeStop(!isPause);
  4136. }
  4137. }, true);
  4138. move.addEventListener("dblclick", e => {
  4139. clearTimeout(removeTimer);
  4140. document.removeEventListener("mousemove", mouseMoveHandler, true);
  4141. document.removeEventListener("mouseup", mouseUpHandler, true);
  4142. changeStop(!isPause);
  4143. if (isPause) {
  4144. ruleParser.hideAddedElements();
  4145. } else {
  4146. ruleParser.showAddedElements();
  4147. }
  4148. }, true);
  4149.  
  4150. move.oncontextmenu = e => {
  4151. e.preventDefault();
  4152. picker.start();
  4153. };
  4154.  
  4155. let clientX = e => {
  4156. if (e.type.indexOf('mouse') === 0) {
  4157. return e.clientX;
  4158. } else {
  4159. return e.changedTouches[0].clientX;
  4160. }
  4161. };
  4162.  
  4163. let clientY = e => {
  4164. if (e.type.indexOf('mouse') === 0) {
  4165. return e.clientY;
  4166. } else {
  4167. return e.changedTouches[0].clientY;
  4168. }
  4169. };
  4170.  
  4171. let mouseMoveHandler = e => {
  4172. if (moving) {
  4173. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  4174. let windowWidth = window.innerWidth || document.documentElement.clientWidth;
  4175. initX = (clientX(e) - 10 + 40) / windowWidth * 100;
  4176. initY = (clientY(e) - 83 + 83) / windowHeight * 100;
  4177. this.frame.style.top = `calc(${initY}% - 83px)`;
  4178. this.frame.style.left = `calc(${initX}% - 40px)`;
  4179. } else if (Math.abs(clientX(e) - initX) + Math.abs(clientY(e) - initY) > 20) {
  4180. moving = true;
  4181. clearTimeout(removeTimer);
  4182. }
  4183. };
  4184. let mouseUpHandler = e => {
  4185. clearTimeout(removeTimer);
  4186. document.removeEventListener("mousemove", mouseMoveHandler, true);
  4187. document.removeEventListener("mouseup", mouseUpHandler, true);
  4188. document.removeEventListener("touchmove", mouseMoveHandler, true);
  4189. document.removeEventListener("touchend", mouseUpHandler, true);
  4190. if (moving) {
  4191. rulesData.sideControllerPos = {x: parseInt(initX), y: parseInt(initY)};
  4192. storage.setItem("rulesData", rulesData);
  4193. }
  4194. };
  4195. let mouseDownHandler = e => {
  4196. initX = clientX(e);
  4197. initY = clientY(e);
  4198. moving = false;
  4199. clearTimeout(removeTimer);
  4200. removeTimer = setTimeout(() => {
  4201. if (e.type === "touchstart") {
  4202. picker.start();
  4203. } else {
  4204. self.remove();
  4205. }
  4206. }, 1500);
  4207. document.addEventListener("mousemove", mouseMoveHandler, true);
  4208. document.addEventListener("mouseup", mouseUpHandler, true);
  4209. document.addEventListener("touchmove", mouseMoveHandler, true);
  4210. document.addEventListener("touchend", mouseUpHandler, true);
  4211. e.stopPropagation();
  4212. e.preventDefault();
  4213. };
  4214.  
  4215. move.addEventListener("mousedown", mouseDownHandler, true);
  4216. move.addEventListener("touchstart", mouseDownHandler, { passive: false, capture: true });
  4217.  
  4218. this.frame = frame;
  4219. this.pagenum = pagenum;
  4220. if (rulesData.sideControllerPos) {
  4221. this.frame.style.top = `calc(${rulesData.sideControllerPos.y}% - 83px)`;
  4222. this.frame.style.left = `calc(${rulesData.sideControllerPos.x}% - 40px)`;
  4223. }
  4224. }
  4225.  
  4226. addToStage() {
  4227. this.init();
  4228. if (!this.styleEle || !this.styleEle.parentNode) {
  4229. this.styleEle = _GM_addStyle(this.cssText);
  4230. }
  4231. if (!isPause) {
  4232. this.frame.classList.remove("stop");
  4233. }
  4234. this.pagenum.innerHTML = createHTML(curPage);
  4235. this.frame.title = i18n("page") + curPage;
  4236. if (this.frame.parentNode) return;
  4237. getBody(document).appendChild(this.frame);
  4238. clearTimeout(this.hideTimer);
  4239. this.frame.classList.add("minSize");
  4240. }
  4241.  
  4242. remove() {
  4243. if (this.frame && this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  4244. }
  4245. }
  4246. const sideController = new SideController();
  4247.  
  4248. class NextSwitch {
  4249. //static nextSwitch;
  4250. constructor() {
  4251. this.inited = false;
  4252. }
  4253.  
  4254. /*static getInstance() {
  4255. if (!NextSwitch.nextSwitch) {
  4256. NextSwitch.nextSwitch = new NextSwitch();
  4257. }
  4258. return NextSwitch.nextSwitch;
  4259. }*/
  4260.  
  4261. init() {
  4262. if (this.inited) return;
  4263. this.inited = true;
  4264. let self = this;
  4265. this.cssText = `
  4266. #pagetual-nextSwitch {
  4267. position: fixed;
  4268. top: 10px;
  4269. left: calc(50% - 160px);
  4270. background: aliceblue;
  4271. padding: 10px;
  4272. border-radius: 5px;
  4273. text-align: center;
  4274. opacity: 0.95;
  4275. color: #161616;
  4276. z-index: 2147483647;
  4277. font-size: 16px;
  4278. box-shadow: rgb(0 0 0) 0px 0px 10px;
  4279. }
  4280. #pagetual-nextSwitch>.title {
  4281. margin: -5px 45px 10px 45px;
  4282. font-size: 20px;
  4283. font-weight: bold;
  4284. border-bottom: 1px solid black;
  4285. user-select: none;
  4286. color: orangered;
  4287. }
  4288. #pagetual-nextSwitch>.group {
  4289. display: flex;
  4290. flex-direction: column;
  4291. }
  4292. #pagetual-nextSwitch>.group>span {
  4293. color: #161616;
  4294. cursor: pointer;
  4295. margin: 3px;
  4296. font-size: larger;
  4297. }
  4298. #pagetual-nextSwitch>.group>span:hover {
  4299. color: red;
  4300. }
  4301. #pagetual-nextSwitch>.group>span.current {
  4302. border: 2px dotted red;
  4303. border-radius: 10px;
  4304. }
  4305. #pagetual-nextSwitch>.closeSwitch {
  4306. position: absolute;
  4307. top: 3px;
  4308. right: 10px;
  4309. background: none;
  4310. border: none;
  4311. vertical-align: top;
  4312. transition: transform .15s ease-in-out;
  4313. float: right;
  4314. cursor: pointer;
  4315. }
  4316. #pagetual-nextSwitch svg {
  4317. width: 30px;
  4318. height: 30px;
  4319. vertical-align: middle;
  4320. fill: #161616;
  4321. overflow: hidden;
  4322. }
  4323. #pagetual-nextSwitch button:hover {
  4324. transform: scale(1.2);
  4325. }
  4326. `;
  4327. let frame = document.createElement("div");
  4328. frame.id = "pagetual-nextSwitch";
  4329. frame.innerHTML = createHTML(`
  4330. <div class="title">${i18n("nextSwitch")}</div>
  4331. <button type="button" class="closeSwitch">
  4332. <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2754">
  4333. <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">
  4334. </path>
  4335. </svg>
  4336. </button>
  4337. <div class="group"></div>
  4338. `);
  4339. let group = frame.querySelector(".group");
  4340. let closeBtn = frame.querySelector(".closeSwitch");
  4341. closeBtn.addEventListener("click", e => {
  4342. self.close();
  4343. }, true);
  4344. this.frame = frame;
  4345. let currentSpan;
  4346. ruleParser.curSiteRule.nextLink.forEach((link, i) => {
  4347. let span = document.createElement("span");
  4348. let target = getElement(link, document);
  4349. let index = "<b>" + (i + 1) + "</b>: ";
  4350. if (target) {
  4351. let targetInner = target.innerText.trim();
  4352. span.innerHTML = index + (targetInner || link);
  4353. } else {
  4354. span.innerHTML = index + "Not Found";
  4355. }
  4356. span.title = link;
  4357. span.addEventListener("click", e => {
  4358. if (currentSpan) currentSpan.classList.remove("current");
  4359. span.classList.add("current");
  4360. currentSpan = span;
  4361. nextIndex = i;
  4362. setListData("nextSwitch", location.host, nextIndex === 0 ? "" : nextIndex);
  4363. ruleParser.curUrl += "#pagetual";
  4364. ruleParser.oldUrl = ruleParser.curUrl;
  4365. autoLoadNum = -1;
  4366. if (!ruleParser.nextLinkHref) {
  4367. isLoading = false;
  4368. }
  4369. ruleParser.getNextLink(ruleParser.pageDoc || document);
  4370. self.close();
  4371. }, true);
  4372. if (i == nextIndex) {
  4373. span.classList.add("current");
  4374. currentSpan = span;
  4375. }
  4376. group.appendChild(span);
  4377. });
  4378. }
  4379.  
  4380. start() {
  4381. this.init();
  4382. if (!this.styleEle || !this.styleEle.parentNode) {
  4383. this.styleEle = _GM_addStyle(this.cssText);
  4384. }
  4385. document.documentElement.appendChild(this.frame);
  4386. }
  4387.  
  4388. close() {
  4389. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  4390. }
  4391. }
  4392. const nextSwitch = new NextSwitch();
  4393.  
  4394. class Picker {
  4395. //static picker;
  4396. constructor() {
  4397. this.inited = false;
  4398. }
  4399.  
  4400. /*static getInstance() {
  4401. if (!Picker.picker) {
  4402. Picker.picker = new Picker();
  4403. }
  4404. return Picker.picker;
  4405. }*/
  4406.  
  4407. init() {
  4408. if (this.inited) return;
  4409. this.inited = true;
  4410. let self = this;
  4411. this.signList = [];
  4412. this.cssText = `
  4413. body.pagetual-picker,
  4414. body.pagetual-picker *:hover,
  4415. body.pagetual-picker a:hover {
  4416. cursor: crosshair !important;
  4417. }
  4418. #pagetual-picker {
  4419. position: fixed;
  4420. top: 10px;
  4421. left: calc(50% - 178px);
  4422. background: aliceblue;
  4423. padding: 10px;
  4424. border-radius: 5px;
  4425. text-align: center;
  4426. opacity: 0.95;
  4427. color: #161616;
  4428. z-index: 2147483646;
  4429. font-size: 16px;
  4430. overflow: hidden;
  4431. box-shadow: rgb(0 0 0) 0px 0px 10px;
  4432. }
  4433. #pagetual-picker * {
  4434. margin: 0;
  4435. padding: 0;
  4436. font-family: Times New Roman;
  4437. overflow: initial;
  4438. user-select: none;
  4439. line-height: unset;
  4440. min-width: unset;
  4441. min-height: unset;
  4442. }
  4443. #pagetual-picker>.title {
  4444. margin: -5px 45px 10px 45px;
  4445. font-size: 20px;
  4446. font-weight: bold;
  4447. cursor: pointer;
  4448. border-bottom: 1px solid black;
  4449. user-select: none;
  4450. color: orangered;
  4451. height: initial;
  4452. width: initial;
  4453. position: initial;
  4454. transition: transform .3s ease;
  4455. }
  4456. #pagetual-picker>.title:hover {
  4457. transform: scale(1.1);
  4458. }
  4459. #pagetual-picker button {
  4460. background: none;
  4461. border: none;
  4462. vertical-align: top;
  4463. transition: transform .15s ease-in-out;
  4464. float: right;
  4465. cursor: pointer;
  4466. overflow: hidden;
  4467. background-color: unset!important;
  4468. }
  4469. #pagetual-picker button:hover {
  4470. transform: scale(1.2);
  4471. }
  4472. #pagetual-picker>.closePicker {
  4473. position: absolute;
  4474. top: 3px;
  4475. right: 10px;
  4476. }
  4477. #pagetual-picker>.logoIcon {
  4478. position: absolute;
  4479. top: 3px;
  4480. left: 10px;
  4481. }
  4482. #pagetual-picker>.logoIcon.showSign>svg>path {
  4483. fill: gray!important;
  4484. }
  4485. #pagetual-picker textarea{
  4486. display: inline-block;
  4487. width: calc(100% - 65px);
  4488. height: 20px;
  4489. min-width: 250px;
  4490. max-width: calc(65vw - 50px);
  4491. min-height: unset;
  4492. max-height: unset;
  4493. padding: 6px 12px;
  4494. font-size: 16px;
  4495. font-weight: 400;
  4496. line-height: 1.5;
  4497. color: #495057;
  4498. background-color: #fff;
  4499. background-clip: padding-box;
  4500. border: 1px solid #ced4da;
  4501. border-radius: 4px;
  4502. transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
  4503. box-sizing: content-box;
  4504. margin-right: 5px;
  4505. resize: both;
  4506. box-shadow: 0 1px 5px 1px #ddd;
  4507. overflow-wrap: anywhere;
  4508. }
  4509. #pagetual-picker textarea:focus {
  4510. color: black;
  4511. background-color: #fff;
  4512. border-color: #80bdff;
  4513. outline: 0;
  4514. box-shadow: 0 0 0 3.2px rgb(0 123 255 / 25%);
  4515. }
  4516. #pagetual-picker [type=checkbox],
  4517. #pagetual-picker [type=radio] {
  4518. line-height: 20px;
  4519. height: 25px;
  4520. width: 25px;
  4521. margin-left: 5px;
  4522. vertical-align: middle;
  4523. appearance: auto;
  4524. display: inline-block;
  4525. position: initial;
  4526. }
  4527. #pagetual-picker [type=checkbox]:after,
  4528. #pagetual-picker [type=radio]:after,
  4529. #pagetual-picker [type=checkbox]:before,
  4530. #pagetual-picker [type=radio]:before {
  4531. border: none;
  4532. background: none;
  4533. }
  4534. #pagetual-picker label {
  4535. font-size: 18px;
  4536. line-height: 25px;
  4537. vertical-align: middle;
  4538. display: inline-block;
  4539. color: black;
  4540. position: initial;
  4541. cursor: pointer;
  4542. }
  4543. #pagetual-picker .bottom {
  4544. text-align: left;
  4545. margin: 10px 0;
  4546. width: 100%;
  4547. }
  4548. #pagetual-picker .bottom>button {
  4549. float: right;
  4550. }
  4551. #pagetual-picker svg {
  4552. width: 30px;
  4553. height: 30px;
  4554. vertical-align: middle;
  4555. fill: #161616;
  4556. overflow: hidden;
  4557. }
  4558. #pagetual-picker svg * {
  4559. pointer-events: none;
  4560. }
  4561. #pagetual-picker .allpath {
  4562. font-size: 18px;
  4563. margin: 10px auto;
  4564. max-width: 330px;
  4565. word-break: break-all;
  4566. cursor: context-menu;
  4567. overflow: hidden;
  4568. max-height: 42px;
  4569. -moz-transition:max-height 1s ease-in;
  4570. -webkit-transition:max-height 1s ease-in;
  4571. transition:max-height 1s ease-in;
  4572. color: black;
  4573. }
  4574. #pagetual-picker .allpath:hover {
  4575. max-height: calc(100vh - 130px);
  4576. overflow: auto;
  4577. }
  4578. #pagetual-picker .allpath>span.path {
  4579. cursor: pointer;
  4580. }
  4581. #pagetual-picker .allpath>span.path:hover {
  4582. opacity: 0.6;
  4583. }
  4584. #pagetual-picker .allpath>span.path:hover,
  4585. #pagetual-picker .allpath>span.path.checked {
  4586. color: orangered;
  4587. }
  4588. #pagetual-picker .moreConfig {
  4589. display: flex;
  4590. justify-content: space-between;
  4591. border-top: 1px solid;
  4592. padding-top: 10px;
  4593. width: 100%;
  4594. }
  4595. #pagetual-picker .command {
  4596. width: 100%;
  4597. color: black!important;
  4598. text-align: center;
  4599. font-size: large;
  4600. margin-top: 10px;
  4601. box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.12);
  4602. border-radius: 5px;
  4603. }
  4604. #pagetual-picker .command:hover {
  4605. color: orangered;
  4606. }
  4607. #pagetual-picker #showDetail {
  4608. float: initial;
  4609. margin-top: 10px;
  4610. }
  4611. #pagetual-picker.showDetail #showDetail {
  4612. float: right;
  4613. }
  4614. #pagetual-picker #showDetail>svg {
  4615. -moz-transition:transform 0.3s ease;
  4616. -webkit-transition:transform 0.3s ease;
  4617. transition:transform 0.3 ease;
  4618. }
  4619. #pagetual-picker.showDetail #showDetail>svg {
  4620. transform: rotate(180deg);
  4621. }
  4622. #pagetual-picker .tempRule {
  4623. display: none;
  4624. margin-top: 10px;
  4625. height: 300px;
  4626. min-height: 150px;
  4627. }
  4628. #pagetual-picker.showDetail .tempRule {
  4629. display: inline-block;
  4630. word-break: break-all;
  4631. }
  4632. #pagetual-picker #saveDetail {
  4633. display: none;
  4634. position: absolute;
  4635. bottom: 10px;
  4636. right: 8px;
  4637. }
  4638. #pagetual-picker.showDetail #saveDetail {
  4639. display: inline-block;
  4640. }
  4641. #pagetual-picker #saveDetail svg {
  4642. width: 35px;
  4643. height: 35px;
  4644. }
  4645. #pagetual-picker .addProp {
  4646. display: none;
  4647. flex-direction: column;
  4648. position: absolute;
  4649. bottom: 45px;
  4650. right: 12px;
  4651. }
  4652. #pagetual-picker.showDetail .addProp {
  4653. display: flex;
  4654. }
  4655. #pagetual-picker .addProp>button {
  4656. font-size: 30px;
  4657. font-family: Arial,sans-serif;
  4658. line-height: 35px;
  4659. color: #161616;
  4660. }
  4661. #pagetual-picker #edit{
  4662. -webkit-animation: jumpAnimation .6s 5;
  4663. animation: jumpAnimation .6s 5;
  4664. }
  4665. @keyframes jumpAnimation {
  4666. 0% {
  4667. transform: scale(1) translateY(0);
  4668. animation-timing-function: ease-out;
  4669. }
  4670. 50% {
  4671. transform: scale(1.2) translateY(-5px);
  4672. animation-timing-function: ease-in;
  4673. }
  4674. 100% {
  4675. transform: scale(1) translateY(0);
  4676. animation-timing-function: ease-out;
  4677. }
  4678. }
  4679. @-webkit-keyframes jumpAnimation {
  4680. 0% {
  4681. -webkit-transform: scale(1) translateY(0);
  4682. animation-timing-function: ease-out;
  4683. }
  4684. 50% {
  4685. -webkit-transform: scale(1.2) translateY(-5px);
  4686. animation-timing-function: ease-in;
  4687. }
  4688. 100% {
  4689. -webkit-transform: scale(1) translateY(0);
  4690. animation-timing-function: ease-out;
  4691. }
  4692. }
  4693. `;
  4694. this.mainSignDiv = this.createSignDiv();
  4695. this.allSignDiv = [];
  4696. let frame = document.createElement("div");
  4697. frame.id = "pagetual-picker";
  4698. frame.innerHTML = createHTML(`
  4699. <button title="Pagetual" type="button" class="logoIcon">
  4700. <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>
  4701. </button>
  4702. <div class="title" title="${i18n("configure")}">${i18n("picker")}</div>
  4703. <button title="${i18n("closePicker")}" type="button" class="closePicker">
  4704. <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>
  4705. </button>
  4706. <div class="allpath" title="${i18n("switchSelector")}"></div>
  4707. <div>
  4708. <textarea class="selector" spellcheck="false" name="selector" placeholder="${i18n("pickerPlaceholder")}"></textarea>
  4709. <button id="check" title="${i18n("pickerCheck")}" type="button">
  4710. <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>
  4711. </button>
  4712. </div>
  4713. <div class="bottom">
  4714. <input name="xpath" id="checkbox_id" type="checkbox" />
  4715. <label for="checkbox_id">XPath</label>
  4716. <button id="edit" title="${i18n("gotoEdit")}" type="button">
  4717. <svg viewBox="0 0 1024 1024" style="color: orangered;fill: orangered;" version="1.1" xmlns="http://www.w3.org/2000/svg">
  4718. <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">
  4719. </path>
  4720. </svg>
  4721. </button>
  4722. </div>
  4723. <div class="moreConfig">
  4724. <div title="${i18n('forceStateIframe')}">
  4725. <input name="forceState" id="forceStateIframe" type="radio" />
  4726. <label for="forceStateIframe">${i18n('iframe')}</label>
  4727. </div>
  4728. <div title="${i18n('forceStateDynamic')}">
  4729. <input name="forceState" id="forceStateDynamic" type="radio" />
  4730. <label for="forceStateDynamic">${i18n('dynamic')}</label>
  4731. </div>
  4732. <div title="${i18n('forceStateDisable')}">
  4733. <input name="forceState" id="forceStateDisable" type="radio" />
  4734. <label for="forceStateDisable">${i18n('disable')}</label>
  4735. </div>
  4736. </div>
  4737. <button id="nextSwitch" class="command" title="${i18n("nextSwitch")}" type="button">${i18n("nextSwitch")}</button>
  4738. <button id="loadNow" class="command" title="${i18n("loadNow")}" type="button">${i18n("loadNow")}</button>
  4739. <button id="autoScroll" class="command" title="${i18n("toggleAutoScroll")}" type="button"></button>
  4740. <button id="ruleRequest" class="command" title="${i18n("ruleRequest")}" type="button">${i18n("ruleRequest")}</button>
  4741. <div>
  4742. <textarea class="tempRule" spellcheck="false" placeholder="{Rule object}" title="Rule for current site"></textarea>
  4743. <button id="showDetail" title="" type="button">
  4744. <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>
  4745. </button>
  4746. <div class="addProp">
  4747. <button id="addOtherProp" title="${i18n("addOtherProp")}" type="button">+</button>
  4748. <button id="addNextSelector" title="${i18n("addNextSelector")}" type="button">></button>
  4749. <button id="addPageSelector" title="${i18n("addPageSelector")}" type="button">❏</button>
  4750. </div>
  4751. <button id="saveDetail" title="${i18n("save")}" type="button">
  4752. <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>
  4753. </button>
  4754. </div>
  4755. `);
  4756. let forceStateIframe = frame.querySelector("#forceStateIframe");//forceState 1 禁用 2 强嵌 3 动态
  4757. let forceStateDynamic = frame.querySelector("#forceStateDynamic");
  4758. let forceStateDisable = frame.querySelector("#forceStateDisable");
  4759. let clickRadio = e => {
  4760. let radio = e.currentTarget.querySelector('input');
  4761. if (radio.checked) {
  4762. forceState = "";
  4763. } else {
  4764. switch (radio.id) {
  4765. case "forceStateIframe":
  4766. forceState = 2;
  4767. break;
  4768. case "forceStateDynamic":
  4769. forceState = 3;
  4770. break;
  4771. case "forceStateDisable":
  4772. forceState = 1;
  4773. break;
  4774. default:
  4775. return;
  4776. }
  4777. }
  4778. setListData("forceState", location.host, forceState);
  4779. self.close();
  4780. setTimeout(() => {
  4781. location.reload();
  4782. }, 500);
  4783. };
  4784. forceStateIframe.parentNode.addEventListener("mousedown", clickRadio);
  4785. forceStateDynamic.parentNode.addEventListener("mousedown", clickRadio);
  4786. forceStateDisable.parentNode.addEventListener("mousedown", clickRadio);
  4787. if (forceState == 1) forceStateDisable.checked = true;
  4788. else if (forceState == 2) forceStateIframe.checked = true;
  4789. else if (forceState == 3) forceStateDynamic.checked = true;
  4790. let closeBtn = frame.querySelector(".closePicker");
  4791. let logoBtn = frame.querySelector(".logoIcon");
  4792. let title = frame.querySelector(".title");
  4793. let allpath = frame.querySelector(".allpath");
  4794. let selectorInput = frame.querySelector(".selector");
  4795. let xpath = frame.querySelector("#checkbox_id");
  4796. let checkBtn = frame.querySelector("#check");
  4797. let editBtn = frame.querySelector("#edit");
  4798. let nextSwitchBtn = frame.querySelector("#nextSwitch");
  4799. let autoScrollBtn = frame.querySelector("#autoScroll");
  4800. let loadNow = frame.querySelector("#loadNow");
  4801. let tempRule = frame.querySelector(".tempRule");
  4802. let showDetailBtn = frame.querySelector("#showDetail");
  4803. let saveDetailBtn = frame.querySelector("#saveDetail");
  4804. let addOtherProp = frame.querySelector("#addOtherProp");
  4805. let addNextSelector = frame.querySelector("#addNextSelector");
  4806. let addPageSelector = frame.querySelector("#addPageSelector");
  4807. let ruleRequestBtn = frame.querySelector("#ruleRequest");
  4808. ruleRequestBtn.addEventListener("click", e => {
  4809. _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});
  4810. }, true);
  4811. autoScrollBtn.addEventListener("click", e => {
  4812. self.close();
  4813. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  4814. autoScroll = parseInt(autoScroll) || 0;
  4815. if (autoScroll < 0) autoScroll = 0;
  4816. if (autoScroll && autoScroll != autoScrollRate) {
  4817. autoScrollRate = autoScroll;
  4818. storage.setItem("autoScrollRate", autoScrollRate);
  4819. }
  4820. setListData("autoScroll", location.host + location.pathname, autoScroll);
  4821. startAutoScroll();
  4822. }, true);
  4823. addOtherProp.addEventListener("click", e => {
  4824. let propName = prompt(i18n("propName"), "author");
  4825. if (!propName) return;
  4826. let propValue = prompt(i18n("propValue"));
  4827. if (!propValue) return;
  4828. if (propValue === "true") propValue = true;
  4829. else if (propValue === "false") propValue = false;
  4830. else if (/^\d+$/.test(propValue)) propValue = parseInt(propValue);
  4831. if (propName === "author" && propValue) {
  4832. author = propValue;
  4833. storage.setItem("author", propValue);
  4834. }
  4835. let editTemp = self.getTempRule();
  4836. if (!editTemp) return;
  4837. editTemp[propName] = propValue;
  4838. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  4839. }, true);
  4840. addNextSelector.addEventListener("click", e => {
  4841. let editTemp = self.getTempRule();
  4842. if (!editTemp) return;
  4843. let selector = self.selectorInput.value;
  4844. if (selector) {
  4845. editTemp.nextLink = selector;
  4846. }
  4847. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  4848. }, true);
  4849. addPageSelector.addEventListener("click", e => {
  4850. let editTemp = self.getTempRule();
  4851. if (!editTemp) return;
  4852. let selector = self.selectorInput.value;
  4853. if (selector) {
  4854. editTemp.pageElement = selector;
  4855. }
  4856. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  4857. }, true);
  4858. showDetailBtn.addEventListener("click", e => {
  4859. frame.classList.toggle("showDetail");
  4860. }, true);
  4861. saveDetailBtn.addEventListener("click", e => {
  4862. let editTemp = self.getTempRule(true);
  4863. if (tempRule.value && !editTemp) {
  4864. return;
  4865. }
  4866. if(!ruleParser.customRules) {
  4867. ruleParser.customRules = [];
  4868. }
  4869. ruleParser.customRules = ruleParser.customRules.filter(item => {return item.url != editTemp.url || item.name != editTemp.name});
  4870. if (tempRule.value) {
  4871. ruleParser.customRules.unshift(editTemp);
  4872. ruleParser.curSiteRule = editTemp;
  4873. } else {
  4874. ruleParser.curSiteRule = {};
  4875. isPause = true;
  4876. }
  4877. storage.setItem("customRules", ruleParser.customRules);
  4878. if (ruleParser.hpRules && ruleParser.curSiteRule && !ruleParser.curSiteRule.smart) {
  4879. ruleParser.addToHpRules(true);
  4880. }
  4881. if (window.confirm(i18n("reloadPage"))) {
  4882. setTimeout(() => {location.reload()}, 100);
  4883. }
  4884. }, true);
  4885. nextSwitchBtn.addEventListener("click", e => {
  4886. self.close();
  4887. nextSwitch.start();
  4888. }, true);
  4889. loadNow.addEventListener("click", e => {
  4890. self.close();
  4891. let loadNum = window.prompt(i18n("loadConfirm"), "1");
  4892. if (loadNum === "" || loadNum === null) return;
  4893. autoLoadNum = Math.abs(parseInt(loadNum));
  4894. nextPage();
  4895. }, true);
  4896. closeBtn.addEventListener("click", e => {
  4897. self.close();
  4898. }, true);
  4899. this.showSign = true;
  4900. logoBtn.addEventListener("click", e => {
  4901. logoBtn.classList.toggle("showSign");
  4902. self.showSign = !self.showSign;
  4903. getBody(document).classList.toggle("pagetual-picker");
  4904. }, true);
  4905. let moving = false;
  4906. let initX = 0, initY = 0, initPos = {x: 0, y: 0};
  4907. let moveHanlder = e => {
  4908. if (moving) {
  4909. frame.style.left = e.clientX - initX + "px";
  4910. frame.style.top = e.clientY - initY + "px";
  4911. e.stopPropagation();
  4912. e.preventDefault();
  4913. } else if(Math.abs(e.clientX - initPos.x) + Math.abs(e.clientY - initPos.y) > 20) {
  4914. moving = true;
  4915. }
  4916. };
  4917. let upHanlder = e => {
  4918. if (moving) {
  4919. moving = false;
  4920. } else {
  4921. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  4922. }
  4923. document.removeEventListener("mousemove", moveHanlder, true);
  4924. title.removeEventListener("mouseup", upHanlder, true);
  4925. e.stopPropagation();
  4926. e.preventDefault();
  4927. };
  4928. title.addEventListener("mousedown", e => {
  4929. initPos = {x: e.clientX, y: e.clientY};
  4930. initX = e.clientX - parseInt(getComputedStyle(frame).left);
  4931. initY = e.clientY - parseInt(getComputedStyle(frame).top);
  4932. document.addEventListener("mousemove", moveHanlder, true);
  4933. title.addEventListener("mouseup", upHanlder, true);
  4934. });
  4935. frame.addEventListener("mouseenter", e => {
  4936. if (!self.showSign || moving) return;
  4937. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  4938. self.checkInputSelector(false);
  4939. });
  4940. frame.addEventListener("mouseleave", e => {
  4941. if (!self.showSign) {
  4942. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  4943. self.clearSigns();
  4944. return;
  4945. }
  4946. if (moving) return;
  4947. document.documentElement.appendChild(self.mainSignDiv);
  4948. self.clearSigns();
  4949. });
  4950. checkBtn.addEventListener("click", e => {
  4951. self.checkInputSelector();
  4952. if (this.selectorInput.value && self.foundEle) {
  4953. debug(self.foundEle);
  4954. self.foundEle[0].scrollIntoView({ behavior: "smooth" });
  4955. _GM_setClipboard(this.selectorInput.value);
  4956. showTips(i18n("copied"));
  4957. } else showTips("Null");
  4958. });
  4959. xpath.addEventListener("click", e => {
  4960. if (!selectorInput.value) {
  4961. self.setSelectorDiv("");
  4962. return;
  4963. }
  4964. let element = getElement(selectorInput.value, document);
  4965. let selector = self.getSelectorFromEle(element);
  4966. selectorInput.value = selector;
  4967. self.setSelectorDiv(selector);
  4968. });
  4969. editBtn.addEventListener("click", e => {
  4970. rulesData.editTemp = self.getTempRule();
  4971. storage.setItem("rulesData", rulesData);
  4972. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  4973. });
  4974. editBtn.oncontextmenu = e => {
  4975. e.preventDefault();
  4976. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  4977. };
  4978. this.frame = frame;
  4979. this.xpath = xpath;
  4980. this.allpath = allpath;
  4981. this.selectorInput = selectorInput;
  4982. this.nextSwitchBtn = nextSwitchBtn;
  4983. this.autoScrollBtn = autoScrollBtn;
  4984. this.loadNow = loadNow;
  4985. this.tempRule = tempRule;
  4986. this.logoBtn = logoBtn;
  4987. let setTitleTimer;
  4988. this.moveHandler = e => {
  4989. if (!self.showSign || e.target === document) return;
  4990. let target = self.getTarget(e.target);
  4991. self.adjustSignDiv(self.mainSignDiv, target);
  4992. clearTimeout(setTitleTimer);
  4993. setTitleTimer = setTimeout(() => {
  4994. if (self.inPicker && target.hasAttributes()) {
  4995. let title = target.nodeName.toLowerCase() + "\n";
  4996. for (const attr of target.attributes) {
  4997. title += `【${attr.name}】${attr.value ? " ➡️ " + attr.value : ""}\n`;
  4998. }
  4999. getBody(document).title = title;
  5000. }
  5001. }, 100);
  5002. };
  5003. this.clickHandler = e => {
  5004. if (!self.showSign) return;
  5005. if (self.inPicker) {
  5006. e.stopPropagation();
  5007. e.preventDefault();
  5008. }
  5009. let target = self.getTarget(e.target);
  5010. let selector = self.getSelectorFromEle(target);
  5011. selectorInput.value = selector;
  5012. self.setSelectorDiv(selector);
  5013. };
  5014. }
  5015.  
  5016. getTempRule(detail) {
  5017. if (this.tempRule.value) {
  5018. try {
  5019. this.editTemp = JSON.parse(this.tempRule.value);
  5020. } catch (e) {
  5021. this.editTemp = null;
  5022. if (detail) {
  5023. let pos = e && e.message && e.message.match(/position (\d+)/);
  5024. if (pos) {
  5025. pos = parseInt(pos[1]);
  5026. this.tempRule.value = this.tempRule.value.slice(0, pos) + "➡️" + this.tempRule.value.slice(pos);
  5027. }
  5028. showTips(i18n("errorJson"));
  5029. return null;
  5030. }
  5031. }
  5032. }
  5033. if (!this.editTemp) {
  5034. if (ruleParser.curSiteRule.url && !ruleParser.curSiteRule.smart) {
  5035. this.editTemp = ruleParser.curSiteRule;
  5036. } else {
  5037. this.editTemp = {
  5038. name: document.title,
  5039. url: "^" + (location.origin + location.pathname).replace(/[^\/]*$/, "").replace(/^https?/, "https?").replace(/\./g, "\\."),
  5040. example: location.href
  5041. };
  5042. if (author) this.editTemp.author = author;
  5043. }
  5044. delete this.editTemp.from;
  5045. delete this.editTemp.type;
  5046. delete this.editTemp.updatedAt;
  5047. }
  5048. if (this.selectorInput.value && !this.frame.classList.contains("showDetail")) {
  5049. if (this.foundEle && this.foundEle.length === 1) {
  5050. let foundEleRect = this.foundEle[0].getBoundingClientRect();
  5051. if (foundEleRect.height < 100) {
  5052. showTips("Next Link", "", 500);
  5053. this.editTemp.nextLink = this.selectorInput.value;
  5054. return this.editTemp;
  5055. }
  5056. }
  5057. showTips("Page Element", "", 500);
  5058. this.editTemp.pageElement = this.selectorInput.value;
  5059. }
  5060. return this.editTemp;
  5061. }
  5062.  
  5063. getTarget(ele) {
  5064. while (ele.parentNode && (ele.offsetWidth === 0 || ele.offsetHeight === 0)) {
  5065. ele = ele.parentNode;
  5066. }
  5067. return ele;
  5068. }
  5069.  
  5070. close() {
  5071. this.clearSigns();
  5072. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  5073. if (this.mainSignDiv.parentNode) this.mainSignDiv.parentNode.removeChild(this.mainSignDiv);
  5074. getBody(document).classList.remove("pagetual-picker");
  5075. getBody(document).removeEventListener("mousemove", this.moveHandler, true);
  5076. getBody(document).removeEventListener("click", this.clickHandler, true);
  5077. getBody(document).title = "";
  5078. this.inPicker = false;
  5079. }
  5080.  
  5081. setImportant(ele, prop, value) {
  5082. ele.style.setProperty(prop, value, "important");
  5083. }
  5084.  
  5085. createSignDiv() {
  5086. let signDiv = document.createElement("div");
  5087. this.setImportant(signDiv, "position", "absolute");
  5088. this.setImportant(signDiv, "pointer-events", "none");
  5089. this.setImportant(signDiv, "z-index", "2147483645");
  5090. this.setImportant(signDiv, "background", "rgba(120, 170, 210, 0.6)");
  5091. this.setImportant(signDiv, "transition", "all 0.15s ease-out");
  5092. this.setImportant(signDiv, "box-shadow", "rgb(0 0 0) 0px 0px 3px 0px");
  5093. return signDiv;
  5094. }
  5095.  
  5096. adjustSignDiv(div, target) {
  5097. let rect = target.getBoundingClientRect();
  5098. this.setImportant(div, "width", rect.width + "px");
  5099. this.setImportant(div, "height", rect.height + "px");
  5100. this.setImportant(div, "left", rect.left + window.scrollX + "px");
  5101. this.setImportant(div, "top", rect.top + window.scrollY + "px");
  5102. }
  5103.  
  5104. getSelectorFromEle(ele) {
  5105. return this.xpath.checked ? createXPathFromElement(ele) : geneSelector(ele, true);
  5106. }
  5107.  
  5108. fillTempRuleTextarea() {
  5109. if (!this.frame.classList.contains("showDetail")) this.tempRule.value = JSON.stringify(this.getTempRule(), null, 4);
  5110. }
  5111.  
  5112. setSelectorDiv(selector) {
  5113. let self = this;
  5114. this.allpath.innerHTML = createHTML("");
  5115. if (selector) {
  5116. if (this.xpath.checked) {
  5117. let span = document.createElement("span");
  5118. span.innerText = selector;
  5119. span.addEventListener("click", e => {
  5120. self.selectorInput.value = selector;
  5121. self.checkInputSelector();
  5122. }, true);
  5123. this.allpath.appendChild(span);
  5124. } else {
  5125. selector.split(">").forEach((item, index) => self.geneSelectorItem(item, index));
  5126. }
  5127. }
  5128. this.checkInputSelector();
  5129. }
  5130.  
  5131. geneSelectorItem(item, index) {
  5132. let self = this;
  5133. item = item.trim();
  5134. if (!item) return;
  5135. if (index !== 0) {
  5136. let span = document.createElement("span");
  5137. span.innerText = " > ";
  5138. this.allpath.appendChild(span);
  5139. }
  5140. let span = document.createElement("span");
  5141. span.className = "path";
  5142. span.innerText = item;
  5143. span.addEventListener("click", e => {
  5144. let selector = "";
  5145. let target = e.target;
  5146. while (target) {
  5147. selector = target.innerText + selector;
  5148. target = target.previousElementSibling;
  5149. }
  5150. self.selectorInput.value = selector;
  5151. self.checkInputSelector();
  5152. if (self.checkedPath) {
  5153. self.checkedPath.classList.remove("checked");
  5154. }
  5155. span.classList.add("checked");
  5156. self.checkedPath = span;
  5157. }, true);
  5158. this.allpath.appendChild(span);
  5159. }
  5160.  
  5161. checkInputSelector(fill = true) {
  5162. let self = this;
  5163. this.clearSigns();
  5164. if (!this.selectorInput.value) return;
  5165. let eles = getAllElements(this.selectorInput.value, document);
  5166. this.foundEle = null;
  5167. if (eles && eles.length > 0) {
  5168. this.foundEle = eles;
  5169. eles.forEach(ele => {
  5170. let sign = self.createSignDiv();
  5171. document.documentElement.appendChild(sign);
  5172. self.adjustSignDiv(sign, ele);
  5173. self.signList.push(sign);
  5174. });
  5175. if (fill) this.fillTempRuleTextarea();
  5176. }
  5177. }
  5178.  
  5179. clearSigns() {
  5180. this.signList.forEach(sign => {
  5181. if (sign.parentNode) sign.parentNode.removeChild(sign);
  5182. });
  5183. this.signList = [];
  5184. }
  5185.  
  5186. start() {
  5187. this.init();
  5188. if (this.inPicker) return;
  5189. this.inPicker = true;
  5190. if (!this.styleEle || !this.styleEle.parentNode) {
  5191. this.styleEle = _GM_addStyle(this.cssText);
  5192. }
  5193. document.documentElement.appendChild(this.frame);
  5194. document.documentElement.appendChild(this.mainSignDiv);
  5195. getBody(document).classList.add("pagetual-picker");
  5196.  
  5197. this.logoBtn.classList.remove("showSign");
  5198. this.showSign = true;
  5199.  
  5200. getBody(document).addEventListener("mousemove", this.moveHandler, true);
  5201. getBody(document).addEventListener("click", this.clickHandler, true);
  5202. this.xpath.checked = isXPath(ruleParser.curSiteRule.pageElement);
  5203. this.tempRule.value = "";
  5204. this.editTemp = null;
  5205. this.frame.classList.remove("showDetail");
  5206.  
  5207. this.loadNow.style.display = ruleParser.nextLinkHref ? "block" : "none";
  5208. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  5209. this.nextSwitchBtn.style.display = "block";
  5210. } else {
  5211. this.nextSwitchBtn.style.display = "none";
  5212. }
  5213. this.autoScrollBtn.innerText = i18n(autoScroll ? "disableAutoScroll" : "enableAutoScroll");
  5214.  
  5215. let pageElementSel = ruleParser.curSiteRule.pageElement || "";
  5216. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  5217. pageElementSel = pageElementSel[nextIndex < pageElementSel.length ? nextIndex : 0];
  5218. }
  5219. this.setSelectorDiv(pageElementSel);
  5220. this.fillTempRuleTextarea();
  5221. }
  5222. }
  5223. const picker = new Picker();
  5224.  
  5225. var editor, editorChanged = false, customRulesInput;
  5226. function createEdit() {
  5227. var options = {
  5228. mode: 'code',
  5229. modes: ['code', 'tree'],
  5230. templates: [
  5231. {
  5232. text: 'New site',
  5233. title: 'Insert a new site',
  5234. className: 'jsoneditor-type-object',
  5235. field: 'SiteTemplate',
  5236. value: {
  5237. 'name': 'Site name',
  5238. 'url': 'Site url'
  5239. }
  5240. }
  5241. ],
  5242. schema: {
  5243. "title": "Sites data",
  5244. "description": "Object containing site config",
  5245. "type": "array",
  5246. "items": {
  5247. "type": 'object',
  5248. "properties": {
  5249. "name": {
  5250. "title": "Site Name",
  5251. "description": "The site's name.",
  5252. "examples": [
  5253. "Google"
  5254. ],
  5255. "type": "string"
  5256. },
  5257. "url": {
  5258. "title": "Site Url",
  5259. "description": "The Regexp of site's url.",
  5260. "examples": [
  5261. "^https:\/\/yande\\.re\/"
  5262. ],
  5263. "type": "string"
  5264. }
  5265. },
  5266. "required": ["name", "url"]
  5267. }
  5268. },
  5269. onChange: () => {
  5270. editorChanged = true;
  5271. }
  5272. };
  5273. setTimeout(() => {
  5274. var container = document.getElementById("jsoneditor");
  5275. container.style.height = '800px';
  5276. container.innerHTML = "";
  5277. try {
  5278. editor = new _unsafeWindow.JSONEditor(container, options);
  5279. editor.set(ruleParser.customRules);
  5280. } catch (e) {
  5281. editor = null;
  5282. container.style.display = 'none';
  5283. customRulesInput.style.display = "";
  5284. }
  5285. }, 500);
  5286. }
  5287.  
  5288. function checkGuidePage(href) {
  5289. if (guidePage.test(href)) {
  5290. if (typeof _unsafeWindow.JSONEditor !== 'undefined') {
  5291. createEdit();
  5292. } else {
  5293. let timeout = 30;
  5294. let checkEditorReady = setInterval(() => {
  5295. if (typeof _unsafeWindow.JSONEditor !== 'undefined') {
  5296. createEdit();
  5297. clearInterval(checkEditorReady);
  5298. } else if (timeout-- <= 0) {
  5299. editor = null;
  5300. customRulesInput.style.display = "";
  5301. clearInterval(checkEditorReady);
  5302. }
  5303. }, 100);
  5304. }
  5305. return true;
  5306. }
  5307. return false;
  5308. }
  5309.  
  5310. function startAutoScroll() {
  5311. clearInterval(autoScrollInterval);
  5312. if (autoScroll <= 0) return;
  5313. let scrollRange = 1;
  5314. if (autoScroll > 1000) {
  5315. scrollRange = parseInt(autoScroll / 1000)
  5316. }
  5317. autoScrollInterval = setInterval(() => {
  5318. if (isPause) return;
  5319. window.scroll(window.scrollX, window.scrollY + scrollRange);
  5320. }, parseInt(1000 / autoScroll));
  5321. }
  5322.  
  5323. var inUpdate = false;
  5324. var importHandler, configCon;
  5325. function initConfig(href) {
  5326. if (location.hostname === "github.com") {
  5327. 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) {
  5328. let issue_body = document.getElementById("issue_body");
  5329. if (!issue_body) return true;
  5330. issue_body.value = issue_body.value.replace("\n", "\n" + location.hash.slice(1) + "\n");
  5331. let starButton = document.createElement("a");
  5332. starButton.href = "https://github.com/hoothin/UserScripts#star";
  5333. starButton.className = "js-toggler-target rounded-left-2 btn-with-aria-count btn-sm btn";
  5334. 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>');
  5335. starButton.style.float = "right";
  5336. document.querySelector(".Layout-main>h2").appendChild(starButton);
  5337. return true;
  5338. } else if (location.href === "https://github.com/hoothin/UserScripts#star") {
  5339. let starButton = document.querySelector(".starring-container:not(.on)>.unstarred>form>button");
  5340. if (starButton) emuClick(starButton);
  5341. return true;
  5342. }
  5343. }
  5344. let isGuidePage = checkGuidePage(href);
  5345. if (!isGuidePage) {
  5346. if (href.indexOf("PagetualGuide") != -1) return true;
  5347. if (location.hostname === "pagetual.hoothin.com") return true;
  5348. }
  5349.  
  5350. var click2import, importUrlPres;
  5351.  
  5352. let inConfig = isGuidePage;
  5353. if (!inConfig) {
  5354. for (let i = 0; i < configPage.length; i++) {
  5355. if (configPage[i] == location.href) {
  5356. inConfig = true;
  5357. break;
  5358. }
  5359. }
  5360. }
  5361. configCon = document.getElementById("configCon");
  5362. if (configCon) {
  5363. configCon.parentNode.removeChild(configCon);
  5364. }
  5365. if (ruleImportUrlReg.test(href) || inConfig) {
  5366. let importing = false;
  5367. if (!inUpdate && rulesData.uninited) {
  5368. setTimeout(() => {
  5369. if (!inUpdate && !importing) showTips(i18n("firstAlert"));
  5370. }, 3000);
  5371. showTips(i18n("firstAlert"));
  5372. }
  5373. let defaultOption = document.querySelector('#discussion_rating_4');
  5374. if (defaultOption) defaultOption.checked = true;
  5375. let createImportBtn = (pre) => {
  5376. let importBtn = document.createElement("button");
  5377. importBtn.id = "pagetualImport";
  5378. importBtn.innerText = i18n("import");
  5379. importBtn.style.marginTop = "100px";
  5380. importBtn.style.float = "right";
  5381. importBtn.style.position = "relative";
  5382. importBtn.style.display = "block";
  5383. importBtn.style.fontSize = "20px";
  5384. importBtn.addEventListener("click", e => {
  5385. let parentNode = importBtn.parentNode;
  5386. if (!parentNode) return;
  5387. parentNode.removeChild(importBtn);
  5388. try {
  5389. let rules = parentNode.innerText.trim();
  5390. let isContent = /['"]name['"]/i.test(rules);
  5391. if (isContent) {
  5392. let ruleList = JSON.parse(`[${rules}]`);
  5393. for (let i in ruleList) {
  5394. let hasRule = false;
  5395. let r = ruleList[i];
  5396. for (let j in ruleParser.customRules) {
  5397. if (ruleParser.customRules[j].name == r.name) {
  5398. ruleParser.customRules[j] = r;
  5399. hasRule = true;
  5400. break;
  5401. }
  5402. }
  5403. if (!hasRule) ruleParser.customRules.push(r);
  5404. ruleParser.hpRules.unshift(r);
  5405. }
  5406. storage.setItem("customRules", ruleParser.customRules);
  5407. storage.setItem("hpRules", ruleParser.hpRules);
  5408. storage.setItem("smartRules", []);
  5409. showTips(i18n("importSucc"));
  5410. } else {
  5411. rules = rules.split("\n");
  5412. let diff = false;
  5413. for (let c = 0; c < rules.length; c++) {
  5414. let urlArr = rules[c].split("|"), url, type = 1;
  5415. if (urlArr.length == 1) {
  5416. url = urlArr[0].trim();
  5417. if (!/^http/.test(url)) {
  5418. showTips(i18n("errorWrongUrl"));
  5419. return;
  5420. }
  5421. } else if (urlArr.length == 2) {
  5422. type = urlArr[0].trim();
  5423. url = urlArr[1].trim();
  5424. if (!/^http/.test(url)) {
  5425. showTips(i18n("errorWrongUrl"));
  5426. return;
  5427. }
  5428. } else {
  5429. break;
  5430. }
  5431. let maxId = 1, hasUrl = false;
  5432. if (!rulesData.urls) {
  5433. rulesData.urls = [];
  5434. maxId = 1;
  5435. } else {
  5436. rulesData.urls.forEach(u => {
  5437. if (maxId < u.id) {
  5438. maxId = u.id;
  5439. }
  5440. if (u.url == url) {
  5441. hasUrl = true;
  5442. }
  5443. });
  5444. if (hasUrl) break;
  5445. }
  5446. diff = true;
  5447. if (!rulesData.sort) rulesData.sort = [1];
  5448. rulesData.urls.push({id: maxId + 1, url: url, type: type});
  5449. rulesData.sort.unshift(maxId + 1);
  5450. }
  5451. if (!diff) {
  5452. showTips(i18n("errorAlreadyExists"));
  5453. setTimeout(() => {
  5454. showTips(i18n("beginUpdate"), "", 30000);
  5455. updateRules(() => {
  5456. showTips(i18n("updateSucc"));
  5457. location.reload();
  5458. }, (rule, err) => {
  5459. showTips(`Failed to update ${rule.url} rules!`);
  5460. debug(err);
  5461. });
  5462. }, 500);
  5463. return;
  5464. }
  5465. storage.setItem("rulesData", rulesData);
  5466.  
  5467. if (rulesData.urls) ruleUrls = ruleUrls.concat(rulesData.urls);
  5468. if (rulesData.sort) {
  5469. let urls = [];
  5470. rulesData.sort.forEach(id => {
  5471. for (let s = 0; s < ruleUrls.length; s++) {
  5472. if (id == ruleUrls[s].id) {
  5473. urls.push(ruleUrls[s]);
  5474. break;
  5475. }
  5476. }
  5477. });
  5478. ruleUrls = urls;
  5479. }
  5480. showTips(i18n("beginUpdate"), "", 30000);
  5481. updateRules(() => {
  5482. showTips(i18n("updateSucc"));
  5483. location.reload();
  5484. }, (rule, err) => {
  5485. showTips(`Failed to update ${rule.url} rules!`);
  5486. debug(err);
  5487. });
  5488. importing = true;
  5489. }
  5490. } catch (e) {
  5491. _GM_notification(e.toString());
  5492. }
  5493. });
  5494. if (pre) {
  5495. let clientHeight = 35 - pre.clientHeight;
  5496. if (clientHeight > -20) clientHeight = -20;
  5497. importBtn.style.marginTop = `${clientHeight}px`;
  5498. pre.appendChild(importBtn);
  5499. }
  5500. return importBtn;
  5501. };
  5502. [].forEach.call(document.querySelectorAll('pre[name=pagetual],pre[name=user-content-pagetual]'), pre => {
  5503. let importBtn = createImportBtn(pre);
  5504. });
  5505. if (!importHandler) {
  5506. importHandler = e => {
  5507. if (compareNodeName(e.target, ["pre"])) {
  5508. let nameAttr = e.target.getAttribute("name");
  5509. if (nameAttr == "pagetual" || nameAttr == "user-content-pagetual") {
  5510. if (e.target.querySelector('#pagetualImport')) return;
  5511. let importBtn = createImportBtn(e.target);
  5512. }
  5513. }
  5514. };
  5515. }
  5516. document.removeEventListener("mouseover", importHandler);
  5517. document.addEventListener("mouseover", importHandler);
  5518.  
  5519. if (inConfig) {
  5520. if (!inUpdate && _GM_info.script && _GM_info.script.version && _GM_info.script.version !== '1.0.0') {
  5521. let versionEle = document.querySelector('.markdown-body>h1[id],article>h1');
  5522. let latestVer = versionEle && versionEle.innerText.match(/\d[\d\.]+/)[0];
  5523. if (latestVer && latestVer != _GM_info.script.version) {
  5524. showTips(i18n('outOfDate'), "", 3000);
  5525. }
  5526. }
  5527. _GM_addStyle(`
  5528. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  5529. cursor: pointer;
  5530. user-select: none;
  5531. display: inline-block;
  5532. margin-right: 5px;
  5533. -moz-transition:color 0.3s ease, transform 0.3s;
  5534. -webkit-transition:color 0.3s ease, transform 0.3s;
  5535. transition:color 0.3s ease, transform 0.3s;
  5536. }
  5537. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  5538. color:red;
  5539. transform: scale(1.5);
  5540. -webkit-transform: scale(1.5);
  5541. }
  5542. .updateDate{
  5543. cursor: pointer;
  5544. user-select: none;
  5545. -moz-transition:color 0.3s ease, transform 0.3s;
  5546. -webkit-transition:color 0.3s ease, transform 0.3s;
  5547. transition:color 0.3s ease, transform 0.3s;
  5548. transform-origin: left;
  5549. -webkit-transform-origin: left;
  5550. }
  5551. .updateDate:hover{
  5552. color:red;
  5553. transform: scale(1.1);
  5554. -webkit-transform: scale(1.1);
  5555. }
  5556. input[type=number]::-webkit-inner-spin-button,
  5557. input[type=number]::-webkit-outer-spin-button {
  5558. -webkit-appearance: none;
  5559. margin: 0;
  5560. }
  5561. input[type=number] {
  5562. -moz-appearance:textfield;
  5563. }
  5564. table td>h3 {
  5565. margin: 16px!important;
  5566. padding: 0!important;
  5567. }
  5568. table td>h4 {
  5569. padding: 0!important;
  5570. }
  5571. #saveBtn {
  5572. width: 60vw;
  5573. position: fixed;
  5574. z-index: 999;
  5575. bottom: 0;
  5576. left: 20vw;
  5577. font-size: xx-large;
  5578. opacity: 0.6;
  5579. cursor: pointer;
  5580. -moz-transition:all 0.3s ease;
  5581. -webkit-transition:all 0.3s ease;
  5582. transition:all 0.3s ease;
  5583. }
  5584. #configCon #saveBtn:hover {
  5585. opacity: 1;
  5586. margin-bottom: 0px;
  5587. }
  5588. #configCon #saveBtn {
  5589. margin-bottom: -40px;
  5590. }
  5591. #configCon.showSave #saveBtn {
  5592. margin-bottom: 0px;
  5593. }
  5594. `);
  5595. click2import = document.querySelector("[name='user-content-click2import'],[name='click2import']");
  5596. if (click2import) click2import.innerText = i18n("click2ImportRule")
  5597. configCon = document.querySelector(".markdown-body,.theme-default-content");
  5598. if (!configCon) {
  5599. setTimeout(() => {
  5600. location.reload();
  5601. }, 1000);
  5602. return true;
  5603. }
  5604. let insertPos = configCon.querySelector("hr,#jsoneditor");
  5605. configCon = document.createElement("div");
  5606. configCon.id = "configCon";
  5607. insertPos.parentNode.insertBefore(configCon, insertPos);
  5608.  
  5609. importUrlPres = document.querySelectorAll("pre[name='user-content-pagetual'],pre[name='pagetual']");
  5610. if (importUrlPres) {
  5611. [].forEach.call(importUrlPres, importUrlPre => {
  5612. importUrlPre.style.overflow = "hidden";
  5613. importUrlPre.style.display = rulesData.uninited ? "block" : "none";
  5614. });
  5615. }
  5616. if (click2import) click2import.style.display = rulesData.uninited ? "block" : "none";
  5617. let otherconfig = document.querySelector("a[name='user-content-otherconfig'],a[name='otherconfig']");
  5618. if (otherconfig) otherconfig.parentNode.removeChild(otherconfig);
  5619. let rulesExample = document.querySelector("#user-content-rules-example+a,#rules-example>a");
  5620. if (rulesExample) {
  5621. rulesExample.innerText = i18n("rulesExample");
  5622. if (lang == "zh-CN") {
  5623. rulesExample.href = rulesExample.href.replace("en", "cn");
  5624. } else if (lang == "zh-TW" || lang == "zh-HK") {
  5625. rulesExample.href = rulesExample.href.replace("/en", "");
  5626. }
  5627. }
  5628.  
  5629. let newPos, lastPos = 0;
  5630. window.addEventListener('scroll', function(e) {
  5631. newPos = window.scrollY;
  5632. if (newPos > lastPos) {
  5633. configCon.classList.add("showSave");
  5634. } else {
  5635. configCon.classList.remove("showSave");
  5636. }
  5637. lastPos = newPos;
  5638. });
  5639. } else return false;
  5640. } else return false;
  5641. let ruleBarInsertPos = document.createTextNode(' ');
  5642. configCon.appendChild(ruleBarInsertPos);
  5643. class Rulebar {
  5644. init(ruleUrl) {
  5645. let id = ruleUrl.id;
  5646. this.ruleUrl = ruleUrl;
  5647. this.item = document.createElement("p");
  5648. this.item.dataset.id = id;
  5649. let url = document.createElement("a");
  5650. url.href = ruleUrl.url;
  5651. url.innerHTML = ruleUrl.url;
  5652. url.title = ruleUrl.url;
  5653. let up = document.createElement("span");
  5654. up.innerHTML = "↑ ";
  5655. up.title = i18n("sortTitle");
  5656. let down = document.createElement("span");
  5657. down.innerHTML = "↓ ";
  5658. down.title = i18n("sortTitle");
  5659. let del = document.createElement("span");
  5660. del.innerHTML = "× ";
  5661. up.onclick = e => {
  5662. this.moveUp();
  5663. };
  5664. down.onclick = e => {
  5665. this.moveDown();
  5666. };
  5667. del.onclick = e => {
  5668. this.del();
  5669. };
  5670. this.item.appendChild(up);
  5671. this.item.appendChild(down);
  5672. this.item.appendChild(del);
  5673. this.item.appendChild(url);
  5674. if (ruleParser.rules) {
  5675. url.style.maxWidth = "calc(100% - 150px)";
  5676. url.style.overflow = "hidden";
  5677. url.style.display = "inline-block";
  5678. url.style.textOverflow = "ellipsis";
  5679. url.style.verticalAlign = "bottom";
  5680. url.style.whiteSpace = "nowrap";
  5681. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == id ? 1 : 0), 0);
  5682. let idSpan = document.createElement("span");
  5683. idSpan.style.float = "right";
  5684. idSpan.innerHTML = `[rules: ${rulesLength}]`;
  5685. this.item.appendChild(idSpan);
  5686. this.idSpan = idSpan;
  5687. }
  5688. configCon.insertBefore(this.item, ruleBarInsertPos);
  5689. }
  5690. updateNum() {
  5691. if (ruleParser.rules) {
  5692. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == this.item.dataset.id ? 1 : 0), 0);
  5693. this.idSpan.innerHTML = `[rules: ${rulesLength}]`;
  5694. }
  5695. }
  5696. saveSort() {
  5697. let sort = [];
  5698. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i => {
  5699. sort.push(i.dataset.id);
  5700. });
  5701. rulesData.sort = sort;
  5702. let urls = [];
  5703. sort.forEach(id => {
  5704. for (let s = 0; s < ruleUrls.length; s++) {
  5705. if (id == ruleUrls[s].id) {
  5706. urls.push(ruleUrls[s]);
  5707. break;
  5708. }
  5709. }
  5710. });
  5711. ruleUrls = urls;
  5712. storage.setItem("rulesData", rulesData);
  5713. showTips(i18n("sortTitle"));
  5714. }
  5715. moveUp() {
  5716. let preE = this.item.previousElementSibling;
  5717. if (compareNodeName(preE, ["p"]) && preE.children.length > 1) {
  5718. this.item.parentNode.insertBefore(this.item, preE);
  5719. this.saveSort();
  5720. }
  5721. }
  5722. moveDown() {
  5723. let nextE = this.item.nextElementSibling;
  5724. if (compareNodeName(nextE, ["p"]) && nextE.children.length > 1) {
  5725. this.item.parentNode.insertBefore(nextE, this.item);
  5726. this.saveSort();
  5727. }
  5728. }
  5729. del() {
  5730. if (this.ruleUrl.id < 2) {
  5731. showTips(i18n("cantDel"));
  5732. } else if (window.confirm(i18n("confirmDel"))) {
  5733. for (let u = 0; u < rulesData.urls.length; u++) {
  5734. if (this.ruleUrl.id == rulesData.urls[u].id) {
  5735. rulesData.urls.splice(u, 1);
  5736. break;
  5737. }
  5738. }
  5739. for (let u = 0; u < ruleUrls.length; u++) {
  5740. if (this.ruleUrl.id == ruleUrls[u].id) {
  5741. ruleUrls.splice(u, 1);
  5742. break;
  5743. }
  5744. }
  5745. for (let u = 0; u < rulesData.sort.length; u++) {
  5746. if (this.ruleUrl.id == rulesData.sort[u]) {
  5747. rulesData.sort.splice(u, 1);
  5748. break;
  5749. }
  5750. }
  5751. rulesData.ruleVersion = 0;
  5752. storage.setItem("rulesData", rulesData);
  5753. ruleParser.rules = ruleParser.rules.filter(item => {return item.from != this.ruleUrl.id});
  5754. storage.setItem("rules", ruleParser.rules);
  5755. this.item.parentNode.removeChild(this.item);
  5756. //location.reload();
  5757. }
  5758. }
  5759. }
  5760. let langSelect = document.createElement("select");
  5761. langSelect.style.float = "right";
  5762. langSelect.style.position = "relative";
  5763. langSelect.style.zIndex = "1";
  5764. let option = document.createElement("option");
  5765. option.value = "";
  5766. option.innerText = "Language";
  5767. langSelect.appendChild(option);
  5768. for (let key in langList) {
  5769. let option = document.createElement("option");
  5770. option.value = key;
  5771. option.innerText = langList[key];
  5772. langSelect.appendChild(option);
  5773. }
  5774. langSelect.value = rulesData.lang || "";
  5775. configCon.appendChild(langSelect);
  5776.  
  5777. let updateP = document.createElement("p"), i = 0;
  5778. let now = new Date().getTime();
  5779.  
  5780.  
  5781. let pastDate = (new Date(updateDate)).toString(), passStr;
  5782. let passTime = (now - updateDate) / 1000;
  5783. if (isNaN(passTime)) {
  5784. passStr = i18n("firstUpdate");
  5785. } else {
  5786. if (passTime < 60) {
  5787. passStr = i18n("passSec", parseInt(passTime));
  5788. } else if (passTime < 60 * 60) {
  5789. passStr = i18n("passMin", parseInt(passTime / 60));
  5790. } else if (passTime < 60 * 60 * 24) {
  5791. passStr = i18n("passHour", parseInt(passTime / 3600));
  5792. } else {
  5793. passStr = i18n("passDay", parseInt(passTime / 86400));
  5794. }
  5795. passStr += " 🖱 " + i18n("click2update");
  5796. }
  5797.  
  5798. let rulebarList = [], updateFail = false;
  5799. updateP.className = "updateDate";
  5800. updateP.innerHTML = passStr;
  5801. updateP.title = i18n("update") + " - " + pastDate;
  5802. configCon.appendChild(updateP);
  5803. if (ruleUrls) {
  5804. ruleUrls.forEach(ruleUrl => {
  5805. let rulebar = new Rulebar();
  5806. rulebar.init(ruleUrl);
  5807. rulebarList.push(rulebar);
  5808. });
  5809. }
  5810. let customUrlsTitle = document.createElement("h2");
  5811. customUrlsTitle.innerHTML = i18n("customUrls");
  5812. configCon.appendChild(customUrlsTitle);
  5813. let customUrlsInput = document.createElement("textarea");
  5814. customUrlsInput.style.width = "100%";
  5815. customUrlsInput.style.position = "relative";
  5816. customUrlsInput.placeholder = "http://wedata.net/databases/AutoPagerize/items_all.json \nhttps://hoothin.github.io/UserScripts/Pagetual/pagetualRules.json";
  5817. customUrlsInput.spellcheck = false;
  5818. configCon.appendChild(customUrlsInput);
  5819.  
  5820. let btns = document.createElement("div");
  5821. btns.style.display = "flex";
  5822. configCon.appendChild(btns);
  5823. let upBtnImg = document.createElement("div");
  5824. upBtnImg.style.width = "33%";
  5825. let upBtnImgTitle = document.createElement("h2");
  5826. upBtnImgTitle.style.whiteSpace = "nowrap";
  5827. upBtnImgTitle.style.overflow = "auto";
  5828. upBtnImgTitle.innerHTML = i18n("upBtnImg");
  5829. upBtnImg.appendChild(upBtnImgTitle);
  5830. let upBtnImgInput = document.createElement("input");
  5831. upBtnImgInput.style.width = "100%";
  5832. upBtnImgInput.style.position = "relative";
  5833. upBtnImgInput.placeholder = "data:image/png;base64,UpBtn";
  5834. upBtnImgInput.value = rulesData.upBtnImg || '';
  5835. upBtnImgInput.spellcheck = false;
  5836. upBtnImg.appendChild(upBtnImgInput);
  5837. btns.appendChild(upBtnImg);
  5838.  
  5839. let downBtnImg = document.createElement("div");
  5840. downBtnImg.style.width = "33%";
  5841. let downBtnImgTitle = document.createElement("h2");
  5842. downBtnImgTitle.style.whiteSpace = "nowrap";
  5843. downBtnImgTitle.style.overflow = "auto";
  5844. downBtnImgTitle.innerHTML = i18n("downBtnImg");
  5845. downBtnImg.appendChild(downBtnImgTitle);
  5846. let downBtnImgInput = document.createElement("input");
  5847. downBtnImgInput.style.width = "100%";
  5848. downBtnImgInput.style.position = "relative";
  5849. downBtnImgInput.placeholder = "data:image/png;base64,DownBtn";
  5850. downBtnImgInput.value = rulesData.downBtnImg || '';
  5851. downBtnImgInput.spellcheck = false;
  5852. downBtnImg.appendChild(downBtnImgInput);
  5853. btns.appendChild(downBtnImg);
  5854.  
  5855. let sideControllerIconDiv = document.createElement("div");
  5856. sideControllerIconDiv.style.width = "33%";
  5857. let sideControllerIconTitle = document.createElement("h2");
  5858. sideControllerIconTitle.style.whiteSpace = "nowrap";
  5859. sideControllerIconTitle.style.overflow = "auto";
  5860. sideControllerIconTitle.innerHTML = i18n("sideControllerIcon");
  5861. sideControllerIconDiv.appendChild(sideControllerIconTitle);
  5862. let sideControllerIconInput = document.createElement("input");
  5863. sideControllerIconInput.style.width = "100%";
  5864. sideControllerIconInput.style.position = "relative";
  5865. sideControllerIconInput.placeholder = "📄";
  5866. sideControllerIconInput.value = rulesData.sideControllerIcon || '';
  5867. sideControllerIconInput.spellcheck = false;
  5868. sideControllerIconDiv.appendChild(sideControllerIconInput);
  5869. btns.appendChild(sideControllerIconDiv);
  5870.  
  5871. let otherBtns = document.createElement("div");
  5872. otherBtns.style.display = "flex";
  5873. configCon.appendChild(otherBtns);
  5874. let loadingText = document.createElement("div");
  5875. loadingText.style.width = "100%";
  5876. let loadingTextTitle = document.createElement("h2");
  5877. loadingTextTitle.style.whiteSpace = "nowrap";
  5878. loadingTextTitle.style.overflow = "auto";
  5879. loadingTextTitle.innerHTML = i18n("loadingTextTitle");
  5880. loadingText.appendChild(loadingTextTitle);
  5881. let loadingTextInput = document.createElement("input");
  5882. loadingTextInput.value = rulesData.loadingText || '';
  5883. loadingTextInput.placeholder = i18n("loadingText");
  5884. loadingTextInput.style.width = "100%";
  5885. loadingTextInput.style.position = "relative";
  5886. loadingTextInput.style.margin = "0";
  5887. loadingTextInput.spellcheck = false;
  5888. loadingText.appendChild(loadingTextInput);
  5889. otherBtns.appendChild(loadingText);
  5890.  
  5891. let opacity = document.createElement("div");
  5892. let opacityTitle = document.createElement("h2");
  5893. opacityTitle.style.whiteSpace = "nowrap";
  5894. opacityTitle.style.overflow = "visible";
  5895. opacityTitle.innerHTML = i18n("opacity");
  5896. opacity.appendChild(opacityTitle);
  5897. let opacityInput = document.createElement("input");
  5898. opacityInput.value = rulesData.opacity * 100;
  5899. opacityInput.type = "number";
  5900. opacityInput.min = 0;
  5901. opacityInput.max = 100;
  5902. opacityInput.style.width = "110px";
  5903. opacityInput.style.position = "relative";
  5904. opacityInput.style.margin = "0";
  5905. opacityInput.placeholder = i18n("opacityPlaceholder");
  5906. opacityInput.spellcheck = false;
  5907. opacityInput.oninput = e => {
  5908. if (opacityInput.value > 100) opacityInput.value = 100;
  5909. else if (opacityInput.value < 0) opacityInput.value = 0;
  5910. };
  5911. opacity.appendChild(opacityInput);
  5912. otherBtns.appendChild(opacity);
  5913.  
  5914. let pageElementCss = document.createElement("div");
  5915. pageElementCss.style.marginBottom = "30px";
  5916. let pageElementCssTitle = document.createElement("h2");
  5917. pageElementCssTitle.innerHTML = i18n("pageElementCss");
  5918. pageElementCss.appendChild(pageElementCssTitle);
  5919. let pageElementCssInput = document.createElement("input");
  5920. pageElementCssInput.value = rulesData.pageElementCss || '';
  5921. pageElementCssInput.style.width = "100%";
  5922. pageElementCssInput.style.position = "relative";
  5923. pageElementCssInput.style.margin = "0";
  5924. pageElementCssInput.placeholder = "font-size: xx-large;";
  5925. pageElementCssInput.spellcheck = false;
  5926. pageElementCss.appendChild(pageElementCssInput);
  5927. configCon.appendChild(pageElementCss);
  5928.  
  5929. let customCss = document.createElement("div");
  5930. customCss.style.marginBottom = "50px";
  5931. let customCssTitle = document.createElement("h2");
  5932. customCssTitle.innerHTML = i18n("customCss");
  5933. customCss.appendChild(customCssTitle);
  5934. let customCssInput = document.createElement("textarea");
  5935. customCssInput.value = rulesData.customCss || '';
  5936. customCssInput.style.width = "100%";
  5937. customCssInput.style.position = "relative";
  5938. customCssInput.style.margin = "0";
  5939. customCssInput.placeholder = ".pagetual {\n}";
  5940. customCssInput.spellcheck = false;
  5941. customCss.appendChild(customCssInput);
  5942. configCon.appendChild(customCss);
  5943.  
  5944. let configTable = document.createElement("table");
  5945. configTable.style.width = "100%";
  5946. let configTbody = document.createElement("tbody");
  5947. configTbody.style.width = "99%";
  5948. configTbody.style.display = "inline-table";
  5949. configTable.appendChild(configTbody);
  5950. configCon.appendChild(configTable);
  5951. function createCheckbox(innerText, val, tag, parentCheck, otherType, alwaysShow) {
  5952. if (typeof val == 'undefined') val = "";
  5953. let title = document.createElement(tag || "h3");
  5954. title.innerHTML = innerText;
  5955. title.style.overflowWrap = "normal";
  5956. let input = document.createElement("input");
  5957. if (otherType === 'key') {
  5958. input.type = 'text';
  5959. input.setAttribute('readOnly', 'readonly');
  5960. input.addEventListener("keydown", e => {
  5961. if (e.key === 'Escape' || e.key === 'Backspace') input.value = '';
  5962. else input.value = e.key;
  5963. e.stopPropagation();
  5964. e.preventDefault();
  5965. });
  5966. } else {
  5967. input.type = otherType || "checkbox";
  5968. }
  5969. input.style.width = "35px";
  5970. input.style.height = "20px";
  5971. input.style.float = "left";
  5972. input.style.margin = "0 2px";
  5973. input.value = val;
  5974. input.checked = val;
  5975. let td = document.createElement("td");
  5976. td.appendChild(input);
  5977. if (parentCheck) {
  5978. title.appendChild(input);
  5979. title.style.margin = "0";
  5980. td.appendChild(title);
  5981. let parent = parentCheck.parentNode.nextElementSibling;
  5982. let tr = parent.querySelector("tr");
  5983. if (!tr) {
  5984. tr = document.createElement("tr");
  5985. parent.appendChild(tr);
  5986. }
  5987. tr.appendChild(td);
  5988. if (!alwaysShow) {
  5989. if (!parentCheck.checked) {
  5990. td.style.display = "none";
  5991. }
  5992. parentCheck.addEventListener("click", e => {
  5993. td.style.display = parentCheck.checked ? "" : "none";
  5994. });
  5995. }
  5996. } else {
  5997. let tr = document.createElement("tr");
  5998. tr.appendChild(td);
  5999. td = document.createElement("td");
  6000. td.appendChild(title);
  6001. tr.appendChild(td);
  6002. configTable.children[0].appendChild(tr);
  6003. }
  6004. let xNodePos = innerText.indexOf('【X】');
  6005. if (xNodePos !== -1) {
  6006. input.style.float = "";
  6007. let xNode = title.firstChild.splitText(xNodePos);
  6008. xNode.splitText(3);
  6009. xNode.parentNode.replaceChild(input, xNode);
  6010. }
  6011. return input;
  6012. }
  6013.  
  6014. let setConfigPageInput = createCheckbox(i18n("setConfigPage"), false);
  6015. let enableWhiteListInput = createCheckbox(i18n("autoRun"), rulesData.enableWhiteList != true);
  6016. let sideControllerInput = createCheckbox(i18n("sideController"), rulesData.sideController);
  6017. let sideControllerAlwaysInput = createCheckbox(i18n("sideControllerAlways"), rulesData.sideControllerAlways, "h4", sideControllerInput);
  6018. let sideControllerScrollInput = createCheckbox(i18n("sideControllerScroll"), rulesData.sideControllerScroll !== false, "h4", sideControllerInput);
  6019. let sideControllerLoadNowInput = createCheckbox(i18n("loadNow"), rulesData.sideControllerLoadNow !== false, "h4", sideControllerInput);
  6020. let enableDebugInput = createCheckbox(i18n("enableDebug"), rulesData.enableDebug != false);
  6021. let enableHistoryInput = createCheckbox(i18n("enableHistory"), rulesData.enableHistory === true);
  6022. let enableHistoryAfterInsertInput = createCheckbox(i18n("enableHistoryAfterInsert"), rulesData.enableHistoryAfterInsert === true, "h4", enableHistoryInput);
  6023. let openInNewTabInput = createCheckbox(i18n("openInNewTab"), rulesData.openInNewTab != false);
  6024. let hidePageBarInput = createCheckbox(i18n("hideBarTips"), rulesData.opacity == 0);
  6025. let hidePageBarArrowInput = createCheckbox(i18n("hideBarArrow"), rulesData.hideBarArrow);
  6026. let hideLoadingIconInput = createCheckbox(i18n("hideLoadingIcon"), rulesData.hideLoadingIcon != false);
  6027. let initRunInput = createCheckbox(i18n("initRun"), rulesData.initRun != false);
  6028. let autoLoadNumInput = createCheckbox(i18n("autoLoadNum"), rulesData.autoLoadNum, "h4", initRunInput, "number");
  6029. let preloadInput = createCheckbox(i18n("preload"), rulesData.preload != false);
  6030. let rateInput = createCheckbox(i18n("turnRate"), rulesData.rate, "h4", preloadInput, "number", true);
  6031. let dbClick2StopInput = createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  6032. let manualModeInput = createCheckbox(i18n("manualMode"), rulesData.manualMode);
  6033. let clickModeInput = createCheckbox(i18n("clickMode"), rulesData.clickMode);
  6034. let pageBarMenuInput = createCheckbox(i18n("pageBarMenu"), rulesData.pageBarMenu != false);
  6035. let arrowToScrollInput = createCheckbox(i18n("arrowToScroll"), rulesData.arrowToScroll);
  6036. let contentVisibilityInput = createCheckbox(i18n("contentVisibility"), rulesData.contentVisibility);
  6037. let wedata2githubInput = createCheckbox(i18n("wedata2github"), rulesData.wedata2github);
  6038. let customFirstInput = createCheckbox(i18n("customFirst"), rulesData.customFirst);
  6039. let lastPageTipsInput = createCheckbox(i18n("lastPageTips"), rulesData.lastPageTips);
  6040. let updateNotificationInput = createCheckbox(i18n("updateNotification"), rulesData.updateNotification != false);
  6041.  
  6042. let hideBarInput = createCheckbox(i18n("hideBar"), rulesData.hideBar && !rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  6043. hideBarInput.name = 'hideBar';
  6044. let hideBarButNoStopInput = createCheckbox(i18n("hideBarButNoStop"), rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  6045. hideBarButNoStopInput.name = 'hideBar';
  6046. hideBarInput.addEventListener('mouseup', e => {
  6047. if (hideBarInput.checked) {
  6048. setTimeout(() => {hideBarInput.checked = false}, 0);
  6049. }
  6050. });
  6051. hideBarButNoStopInput.addEventListener('mouseup', e => {
  6052. if (hideBarButNoStopInput.checked) {
  6053. setTimeout(() => {hideBarButNoStopInput.checked = false}, 0);
  6054. }
  6055. });
  6056. hidePageBarInput.addEventListener('click', e => {
  6057. opacityInput.value = hidePageBarInput.checked ? 0 : 100;
  6058. });
  6059.  
  6060. let dbClick2StopCtrlInput = createCheckbox(i18n("dbClick2StopCtrl"), rulesData.dbClick2StopCtrl, "h4", dbClick2StopInput);
  6061. let dbClick2StopAltInput = createCheckbox(i18n("dbClick2StopAlt"), rulesData.dbClick2StopAlt, "h4", dbClick2StopInput);
  6062. let dbClick2StopShiftInput = createCheckbox(i18n("dbClick2StopShift"), rulesData.dbClick2StopShift, "h4", dbClick2StopInput);
  6063. let dbClick2StopMetaInput = createCheckbox(i18n("dbClick2StopMeta"), rulesData.dbClick2StopMeta, "h4", dbClick2StopInput);
  6064. let dbClick2StopKeyInput = createCheckbox(i18n("dbClick2StopKey"), rulesData.dbClick2StopKey, "h4", dbClick2StopInput, "key");
  6065.  
  6066. let otherConfigPage = (rulesData.configPage || configPage[0]) != location.href;
  6067. if (!otherConfigPage) {
  6068. setConfigPageInput.parentNode.parentNode.style.display = "none";
  6069. }
  6070.  
  6071. updateP.onclick = e => {
  6072. updateFail = false;
  6073. //ruleParser.rules = [];
  6074. showTips(i18n("beginUpdate"), "", 30000);
  6075. updateRules(() => {
  6076. if (!updateFail) {
  6077. showTips(i18n("updateSucc"));
  6078. if (importUrlPres) {
  6079. [].forEach.call(importUrlPres, importUrlPre => {
  6080. importUrlPre.style.display = "none";
  6081. });
  6082. }
  6083. if (click2import) click2import.style.display = "none";
  6084. }
  6085. updateP.innerHTML = i18n("passSec", 0);
  6086. updateP.title = i18n("update");
  6087. rulebarList.forEach(rulebar => {
  6088. rulebar.updateNum();
  6089. });
  6090. }, (rule, err) => {
  6091. if (rule.id == 1) {
  6092. showTips(`Failed to update wedata rules! Try to switch to wedata mirror!`);
  6093. wedata2githubInput.scrollIntoView({ behavior: "smooth" });
  6094. } else {
  6095. showTips(`Failed to update ${rule.url} rules!`);
  6096. }
  6097. debug(err);
  6098. updateFail = true;
  6099. });
  6100. };
  6101. let customRulesTitle = document.createElement("h2");
  6102. 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');
  6103. configCon.appendChild(customRulesTitle);
  6104. customRulesInput = document.createElement("textarea");
  6105. customRulesInput.spellcheck = false;
  6106. configCon.appendChild(customRulesInput);
  6107. if (rulesData.editTemp) {
  6108. if (!ruleParser.customRules) {
  6109. ruleParser.customRules = [];
  6110. }
  6111. for (let i in ruleParser.customRules) {
  6112. if (ruleParser.customRules[i].url == rulesData.editTemp.url) {
  6113. ruleParser.customRules.splice(i, 1);
  6114. break;
  6115. }
  6116. }
  6117. ruleParser.customRules.unshift(rulesData.editTemp);
  6118. rulesData.editTemp = null;
  6119. storage.setItem("rulesData", rulesData);
  6120. customRulesInput.previousElementSibling.scrollIntoView();
  6121. }
  6122. customRulesInput.style.width = "100%";
  6123. customRulesInput.style.height = "800px";
  6124. 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]`;
  6125. let preCustom = getFormatJSON(ruleParser.customRules);
  6126. customRulesInput.value = preCustom;
  6127. if (isGuidePage) customRulesInput.style.display = "none";
  6128. let blacklistInput = document.createElement("textarea");
  6129. blacklistInput.style.width = "100%";
  6130. blacklistInput.style.height = "500px";
  6131. blacklistInput.style.display = "none";
  6132. blacklistInput.spellcheck = false;
  6133. 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";
  6134. blacklistInput.value = rulesData.blacklist ? rulesData.blacklist.join("\n") : "";
  6135. let blacklistBtn = document.createElement("button");
  6136. blacklistBtn.innerText = i18n("editBlacklist");
  6137. blacklistBtn.style.width = "100%";
  6138. blacklistBtn.onclick = e => {
  6139. blacklistInput.style.display = blacklistInput.style.display == "none" ? "" : "none";
  6140. };
  6141. configCon.appendChild(blacklistBtn);
  6142. configCon.appendChild(blacklistInput);
  6143. let saveBtn = document.createElement("button");
  6144. saveBtn.innerHTML = i18n("save");
  6145. saveBtn.id = "saveBtn";
  6146. configCon.appendChild(saveBtn);
  6147. saveBtn.onclick = e => {
  6148. try {
  6149. let customRules;
  6150. if (editor) {
  6151. if (editorChanged) {
  6152. editorChanged = false;
  6153. storage.setItem("hpRules", []);
  6154. storage.setItem("smartRules", []);
  6155. }
  6156. customRules = editor.get();
  6157. if (!customRules) {
  6158. customRules = "";
  6159. } else {
  6160. if (Array && Array.isArray && !Array.isArray(customRules)) {
  6161. showTips(i18n("errorRulesMustBeArray"));
  6162. return;
  6163. }
  6164. }
  6165. } else {
  6166. if (customRulesInput.value != preCustom) {
  6167. storage.setItem("hpRules", []);
  6168. storage.setItem("smartRules", []);
  6169. }
  6170. if (customRulesInput.value == "") {
  6171. customRules = "";
  6172. } else {
  6173. customRules = JSON.parse(customRulesInput.value);
  6174. if (Array && Array.isArray && !Array.isArray(customRules)) {
  6175. showTips(i18n("errorRulesMustBeArray"));
  6176. return;
  6177. }
  6178. customRulesInput.value = JSON.stringify(customRules, null, 4);
  6179. }
  6180. }
  6181. debug(customRules);
  6182. storage.setItem("customRules", customRules);
  6183. } catch(e) {
  6184. debug(e);
  6185. let pos = e && e.message && e.message.match(/position (\d+)/);
  6186. if (pos && !editor) {
  6187. pos = parseInt(pos[1]);
  6188. customRulesInput.value = customRulesInput.value.slice(0, pos) + "➡️" + customRulesInput.value.slice(pos);
  6189. }
  6190. showTips(i18n("errorJson"));
  6191. return;
  6192. }
  6193. rulesData.lang = langSelect.value || "";
  6194. if (setConfigPageInput.checked) rulesData.configPage = location.href;
  6195. rulesData.wedata2github = wedata2githubInput.checked;
  6196. let opacity = parseInt(opacityInput.value) || 0;
  6197. if (opacity > 100) opacity = 100;
  6198. else if (opacity < 0) opacity = 0;
  6199. rulesData.opacity = opacity / 100;
  6200. rulesData.blacklist = blacklistInput.value ? blacklistInput.value.trim().split("\n") : "";
  6201. rulesData.hideBar = hideBarInput.checked;
  6202. rulesData.hideBarButNoStop = hideBarButNoStopInput.checked;
  6203. rulesData.dbClick2Stop = dbClick2StopInput.checked;
  6204. rulesData.enableWhiteList = !enableWhiteListInput.checked;
  6205. rulesData.enableDebug = enableDebugInput.checked;
  6206. rulesData.updateNotification = updateNotificationInput.checked;
  6207. rulesData.enableHistory = enableHistoryInput.checked;
  6208. rulesData.enableHistoryAfterInsert = enableHistoryAfterInsertInput.checked;
  6209. rulesData.openInNewTab = openInNewTabInput.checked;
  6210. rulesData.hideLoadingIcon = hideLoadingIconInput.checked;
  6211. rulesData.hideBarArrow = hidePageBarArrowInput.checked;
  6212. rulesData.customFirst = customFirstInput.checked;
  6213. rulesData.lastPageTips = lastPageTipsInput.checked;
  6214. rulesData.initRun = initRunInput.checked;
  6215. rulesData.autoLoadNum = autoLoadNumInput.value !== "0" ? autoLoadNumInput.value : '';
  6216. rulesData.rate = parseFloat(rateInput.value) || 0;
  6217. rulesData.preload = preloadInput.checked;
  6218. rulesData.manualMode = manualModeInput.checked;
  6219. rulesData.clickMode = clickModeInput.checked;
  6220. rulesData.pageBarMenu = pageBarMenuInput.checked;
  6221. rulesData.arrowToScroll = arrowToScrollInput.checked;
  6222. rulesData.contentVisibility = contentVisibilityInput.checked;
  6223. if (rulesData.sideController != sideControllerInput.checked) {
  6224. rulesData.sideControllerPos = false;
  6225. }
  6226. rulesData.sideController = sideControllerInput.checked;
  6227. rulesData.sideControllerScroll = sideControllerScrollInput.checked;
  6228. rulesData.sideControllerLoadNow = sideControllerLoadNowInput.checked;
  6229. rulesData.sideControllerAlways = sideControllerAlwaysInput.checked;
  6230. rulesData.pageElementCss = pageElementCssInput.value;
  6231. rulesData.customCss = customCssInput.value;
  6232. rulesData.upBtnImg = upBtnImgInput.value;
  6233. rulesData.downBtnImg = downBtnImgInput.value;
  6234. rulesData.sideControllerIcon = sideControllerIconInput.value;
  6235. rulesData.loadingText = loadingTextInput.value;
  6236. rulesData.dbClick2StopCtrl = dbClick2StopCtrlInput.checked;
  6237. rulesData.dbClick2StopAlt = dbClick2StopAltInput.checked;
  6238. rulesData.dbClick2StopShift = dbClick2StopShiftInput.checked;
  6239. rulesData.dbClick2StopMeta = dbClick2StopMetaInput.checked;
  6240. rulesData.dbClick2StopKey = dbClick2StopKeyInput.value;
  6241. storage.setItem("rulesData", rulesData);
  6242. let customUrls = customUrlsInput.value.trim(), urlImported = false;
  6243. if (customUrls) {
  6244. customUrls = customUrls.split(/\n/);
  6245. for (let c = 0; c < customUrls.length; c++) {
  6246. let url;
  6247. if (/^0\s*\|/.test(customUrls[c])) {
  6248. url = customUrls[c].replace(/^0\s*\|\s*/, "").trim();
  6249. if (!/^http/.test(url)) {
  6250. showTips(i18n("errorWrongUrl"));
  6251. return;
  6252. }
  6253. } else {
  6254. url = customUrls[c].trim();
  6255. if (!/^http/.test(url)) {
  6256. showTips(i18n("errorWrongUrl"));
  6257. return;
  6258. }
  6259. }
  6260. let maxId = 1, hasUrl = false;
  6261. if (!rulesData.urls) {
  6262. rulesData.urls = [];
  6263. }
  6264. ruleUrls.forEach(u => {
  6265. if (maxId < u.id) {
  6266. maxId = u.id;
  6267. }
  6268. if (u.url == url) {
  6269. hasUrl = true;
  6270. }
  6271. });
  6272. if (hasUrl) break;
  6273. if (!rulesData.sort) rulesData.sort = [1];
  6274. let newRule = {id: maxId + 1, url: url};
  6275. ruleUrls.push(newRule);
  6276. rulesData.urls.push(newRule);
  6277. rulesData.sort.push(maxId + 1);
  6278. storage.setItem("rulesData", rulesData);
  6279. let rulebar = new Rulebar();
  6280. rulebar.init(newRule);
  6281. rulebarList.push(rulebar);
  6282. }
  6283. }
  6284. showTips(i18n("settingsSaved"));
  6285. };
  6286. return true;
  6287. }
  6288.  
  6289. function updateRules (success, fail, keepCache) {
  6290. if (!storage.supportCrossSave()) {
  6291. fail({url:''}, "Not support cross storage");
  6292. showTips("Current platform do not support cross storage!");
  6293. return;
  6294. }
  6295. if (inUpdate) return;
  6296. inUpdate = true;
  6297. let ruleIndex = ruleUrls.length - 1;
  6298. if (!keepCache) {
  6299. storage.setItem("hpRules", []);
  6300. storage.setItem("smartRules", []);
  6301. }
  6302. let allOk = true;
  6303. let preLength = ruleParser.rules.length;
  6304. let fetchVersion = -1;
  6305. async function needUpdate(url, id) {
  6306. if (!/^https:\/\/hoothin\.github\.io\/|\/hoothin\/UserScripts\/.*\/Pagetual\/pagetualRules\.json/i.test(url)) {
  6307. return true;
  6308. }
  6309. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == id ? 1 : 0), 0);
  6310. if (rulesLength === 0) return true;
  6311. if (fetchVersion >= 0) {
  6312. return fetchVersion > (rulesData.ruleVersion || 0);
  6313. }
  6314. fetchVersion = await new Promise(resolve => {
  6315. _GM_xmlhttpRequest({
  6316. url: url.replace(/\/\w+\.json/i, "/version"),
  6317. method: 'GET',
  6318. timeout: 20000,
  6319. headers: {
  6320. 'accept': 'application/json,text/html'
  6321. },
  6322. onload: function(res) {
  6323. let version = parseInt(res.response || res.responseText);
  6324. resolve(version || -1);
  6325. },
  6326. onerror: function(e) {
  6327. resolve(-1);
  6328. },
  6329. ontimeout: function(e) {
  6330. resolve(-1);
  6331. }
  6332. });
  6333. });
  6334. return fetchVersion > (rulesData.ruleVersion || 0);
  6335. }
  6336. async function addNextRule() {
  6337. if (ruleIndex < 0) {
  6338. let now = new Date().getTime();
  6339. storage.setItem("ruleLastUpdate", now);
  6340. storage.setItem("rules", ruleParser.rules);
  6341. let curLength = ruleParser.rules.length;
  6342. if (curLength !== preLength && rulesData.updateNotification) {
  6343. _GM_notification({
  6344. text: `Rules has updated( ${preLength} => ${curLength} )`,
  6345. title: "Pagetual rules updated",
  6346. onclick: (event) => {
  6347. event.preventDefault();
  6348. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  6349. }
  6350. });
  6351. }
  6352. inUpdate = false;
  6353. let rulesDataChanged = false;
  6354. if (fetchVersion >= 0 && rulesData.ruleVersion !== fetchVersion) {
  6355. rulesData.ruleVersion = fetchVersion;
  6356. rulesDataChanged = true;
  6357. }
  6358. if (rulesData.uninited && allOk && ruleUrls.length > 1) {
  6359. rulesData.uninited = false;
  6360. rulesDataChanged = true;
  6361. }
  6362. if (rulesDataChanged) {
  6363. storage.setItem("rulesData", rulesData);
  6364. }
  6365. success();
  6366. } else {
  6367. let rule = ruleUrls[ruleIndex--];
  6368. if (await needUpdate(rule.url, rule.id)) {
  6369. ruleParser.addRuleByUrl(rule.url, rule.id, (json, err) => {
  6370. if (!json) {
  6371. allOk = false;
  6372. fail(rule, err);
  6373. }
  6374. addNextRule();
  6375. });
  6376. } else {
  6377. addNextRule();
  6378. }
  6379. }
  6380. }
  6381. addNextRule();
  6382. }
  6383.  
  6384. function objIsArr(obj) {
  6385. return obj &&
  6386. typeof obj === 'object' &&
  6387. typeof obj.length === 'number' &&
  6388. !(obj.propertyIsEnumerable('length'));
  6389. }
  6390.  
  6391. function isVisible(el, win) {
  6392. if(!el || !el.offsetParent)return false;
  6393. var loopable = true,
  6394. visible = el.nodeName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  6395. while(loopable && visible) {
  6396. el = el.parentNode;
  6397.  
  6398. if(el && !compareNodeName(el, ["body"])) {
  6399. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  6400. }else {
  6401. loopable = false;
  6402. }
  6403. }
  6404. return visible;
  6405. }
  6406.  
  6407. function getElementTop(ele) {
  6408. if (!ele) return 0;
  6409. if (ele.getBoundingClientRect) {
  6410. return ele.getBoundingClientRect().top + document.documentElement.scrollTop;
  6411. }
  6412. var actualTop = ele.offsetTop;
  6413. var current = ele.offsetParent;
  6414. while (current) {
  6415. actualTop += current.offsetTop;
  6416. current = current.offsetParent;
  6417. }
  6418. return actualTop;
  6419. }
  6420.  
  6421. function getElementLeft(ele) {
  6422. if (!ele) return 0;
  6423. if (ele.getBoundingClientRect) {
  6424. return ele.getBoundingClientRect().left + document.documentElement.scrollLeft;
  6425. }
  6426. var actualLeft = ele.offsetLeft;
  6427. var current = ele.offsetParent;
  6428. while (current) {
  6429. actualLeft += current.offsetLeft;
  6430. current = current.offsetParent;
  6431. }
  6432. return actualLeft;
  6433. }
  6434.  
  6435. function getElementBottom(ele) {
  6436. return getElementTop(ele) + (ele.offsetHeight || ele.scrollHeight);
  6437. }
  6438.  
  6439. function getFormatJSON(obj){
  6440. if(!objIsArr(obj) || obj.length === 0)return "";
  6441. return JSON.stringify(obj, null, 4);
  6442. }
  6443.  
  6444. function globMatch(first, second) {
  6445. if (first === '*') {
  6446. return true;
  6447. }
  6448. if (first.length == 0 && second.length == 0){
  6449. return true;
  6450. }
  6451.  
  6452. if (first.length > 1 && first[0] == '*' &&
  6453. second.length == 0){
  6454. return false;
  6455. }
  6456.  
  6457. if ((first.length > 1 && first[0] == '?') ||
  6458. (first.length != 0 && second.length != 0 &&
  6459. first[0] == second[0])){
  6460. return globMatch(first.substring(1),
  6461. second.substring(1));
  6462. }
  6463.  
  6464. if (first.length > 0 && first[0] == '*'){
  6465. return globMatch(first.substring(1), second) ||
  6466. globMatch(first, second.substring(1));
  6467. }
  6468.  
  6469. return false;
  6470. }
  6471.  
  6472. let pageReady = false;
  6473. function initRules(callback) {
  6474. charset = (document.characterSet || document.charset || document.inputEncoding);
  6475. let equiv = document.querySelector('[http-equiv="Content-Type"]');
  6476. if (equiv && equiv.content) {
  6477. let innerCharSet = equiv.content.match(/charset\=([^;]+)/);
  6478. if (!innerCharSet) {
  6479. charsetValid = false;
  6480. } else if (innerCharSet[1].replace("-", "").toLowerCase() != charset.replace("-", "").toLowerCase()) {
  6481. charsetValid = false;
  6482. }
  6483. } else charsetValid = false;
  6484. storage.getItem("rulesData", data => {
  6485. /*0 wedata格式,1 pagetual格式*/
  6486. ruleUrls = [{
  6487. id: 1,
  6488. url: data && data.wedata2github ? 'https://hoothin.github.io/UserScripts/Pagetual/items_all.json' : 'http://wedata.net/databases/AutoPagerize/items_all.json',
  6489. type: 0,
  6490. }];
  6491. if (data) {
  6492. rulesData = data;
  6493. if (data.urls) ruleUrls = ruleUrls.concat(data.urls);
  6494. if (data.sort) {
  6495. let urls = [];
  6496. data.sort.forEach(id => {
  6497. for (let s = 0; s < ruleUrls.length; s++) {
  6498. if (id == ruleUrls[s].id) {
  6499. urls.push(ruleUrls[s]);
  6500. break;
  6501. }
  6502. }
  6503. });
  6504. ruleUrls = urls;
  6505. }
  6506. }
  6507. if (rulesData.lang) {
  6508. setLang(rulesData.lang);
  6509. }
  6510. if (rulesData.firstRun) {
  6511. rulesData.firstRun = false;
  6512. storage.setItem("rulesData", rulesData);
  6513. setTimeout(() => {
  6514. storage.getItem("rulesData", data => {
  6515. if (data.firstRun === false) {
  6516. _GM_openInTab(firstRunPage, {active: true});
  6517. }
  6518. });
  6519. }, 100);
  6520. }
  6521. _GM_registerMenuCommand(i18n("configure"), () => {
  6522. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  6523. });
  6524. if (rulesData.blacklist && rulesData.blacklist.length > 0) {
  6525. let href = location.href.slice(0, 500);
  6526. let commentStart = false;
  6527. for (let i = 0; i < rulesData.blacklist.length; i++) {
  6528. let curGlob = rulesData.blacklist[i];
  6529. if (!curGlob) continue;
  6530. if (curGlob.indexOf("//") == 0) continue;
  6531. if (commentStart) {
  6532. if (/\*\/$/.test(curGlob)) {
  6533. commentStart = false;
  6534. }
  6535. continue;
  6536. }
  6537. if (curGlob.indexOf("/*") == 0) {
  6538. commentStart = true;
  6539. continue;
  6540. }
  6541. if (curGlob.indexOf("/") == 0) {
  6542. let regMatch = curGlob.match(/^\/(.*)\/(\w*)$/);
  6543. if (regMatch && new RegExp(regMatch[1], regMatch[2]).test(href)) {
  6544. forceState == 1;
  6545. return;
  6546. }
  6547. } else if (globMatch(curGlob, href)) {
  6548. forceState == 1;
  6549. return;
  6550. }
  6551. }
  6552. }
  6553. _GM_registerMenuCommand(i18n("editCurrent"), () => {
  6554. picker.start();
  6555. });
  6556. ruleParser.initSavedRules(async () => {
  6557. let upBtnImg = rulesData.upBtnImg, downBtnImg = rulesData.downBtnImg, _sideControllerIcon = rulesData.sideControllerIcon;
  6558. if (upBtnImg && downBtnImg) {
  6559. downSvgCSS = downSvgCSS.replace("transform: rotate(180deg);", "");
  6560. } else if (upBtnImg && !downBtnImg) {
  6561. downBtnImg = upBtnImg;
  6562. } else if(downBtnImg && !upBtnImg) {
  6563. upBtnImg = downBtnImg;
  6564. }
  6565. if (upBtnImg) {
  6566. upSvg = /https?:|data/.test(upBtnImg) ? `<img class="pagetual" src="${upBtnImg}"/>` : `<span>${upBtnImg}</span>`;
  6567. }
  6568. if (downBtnImg) {
  6569. downSvg = /https?:|data/.test(downBtnImg) ? `<img class="pagetual" src="${downBtnImg}"/>` : `<span>${downBtnImg}</span>`;
  6570. }
  6571. if (_sideControllerIcon) {
  6572. sideControllerIcon = /https?:|data/.test(_sideControllerIcon) ? `<img class="pagetual" src="${_sideControllerIcon}"/>` : `<span>${_sideControllerIcon}</span>`;
  6573. }
  6574. setLoadingDiv(rulesData.loadingText || i18n("loadingText"));
  6575. if (typeof(rulesData.opacity) == "undefined") {
  6576. rulesData.opacity = 1;
  6577. }
  6578. if (typeof(rulesData.hideBar) == "undefined") {
  6579. rulesData.hideBar = false;
  6580. }
  6581. if (typeof(rulesData.dbClick2Stop) == "undefined") {
  6582. rulesData.dbClick2Stop = true;
  6583. }
  6584. if (typeof(rulesData.enableWhiteList) == "undefined") {
  6585. rulesData.enableWhiteList = false;
  6586. }
  6587. if (typeof(rulesData.enableHistory) == "undefined") {
  6588. rulesData.enableHistory = false;
  6589. }
  6590. if (typeof(rulesData.openInNewTab) == "undefined") {
  6591. rulesData.openInNewTab = false;
  6592. }
  6593. if (typeof(rulesData.enableDebug) == "undefined") {
  6594. rulesData.enableDebug = true;
  6595. }
  6596. if (typeof(rulesData.updateNotification) == "undefined") {
  6597. rulesData.updateNotification = true;
  6598. }
  6599. if (typeof(rulesData.initRun) == "undefined") {
  6600. rulesData.initRun = true;
  6601. }
  6602. if (typeof(rulesData.preload) == "undefined") {
  6603. rulesData.preload = true;
  6604. }
  6605. if (typeof(rulesData.customFirst) == "undefined") {
  6606. rulesData.customFirst = false;
  6607. }
  6608. if (typeof(rulesData.manualMode) == "undefined") {
  6609. rulesData.manualMode = false;
  6610. }
  6611. if (typeof(rulesData.clickMode) == "undefined") {
  6612. rulesData.clickMode = false;
  6613. }
  6614. if (typeof(rulesData.pageBarMenu) == "undefined") {
  6615. rulesData.pageBarMenu = true;
  6616. }
  6617. if (typeof(rulesData.arrowToScroll) == "undefined") {
  6618. rulesData.arrowToScroll = false;
  6619. }
  6620. if (typeof(rulesData.hideLoadingIcon) == "undefined") {
  6621. rulesData.hideLoadingIcon = false;
  6622. }
  6623. if (typeof(rulesData.hideBarArrow) == "undefined") {
  6624. rulesData.hideBarArrow = false;
  6625. }
  6626. if (typeof(rulesData.lastPageTips) == "undefined") {
  6627. rulesData.lastPageTips = true;
  6628. }
  6629. if (typeof(rulesData.rate) == "undefined") {
  6630. rulesData.rate = 1;
  6631. }
  6632. rate = rulesData.rate;
  6633. if (rulesData.autoLoadNum && rulesData.initRun) {
  6634. autoLoadNum = parseInt(rulesData.autoLoadNum);
  6635. }
  6636. openInNewTab = rulesData.openInNewTab ? 1 : 0;
  6637. enableDebug = rulesData.enableDebug;
  6638.  
  6639. let _nextSwitch = await getListData("nextSwitch", location.host);
  6640. if (typeof(_nextSwitch) !== "undefined") {
  6641. nextIndex = _nextSwitch || 0;
  6642. }
  6643.  
  6644. let _forceState = await getListData("forceState", location.host);
  6645. if (typeof(_forceState) == "undefined") {
  6646. _forceState = await getData("forceState_" + location.host);
  6647. }
  6648. if (typeof(_forceState) == "undefined") {
  6649. _forceState = (rulesData.enableWhiteList ? 1 : 0);
  6650. }
  6651. forceState = _forceState;
  6652.  
  6653. autoScroll = await getListData("autoScroll", location.host + location.pathname) || 0;
  6654.  
  6655. updateDate = await getData("ruleLastUpdate");
  6656.  
  6657. let _loadNowNum = await getData("loadNowNum");
  6658. if (typeof(_loadNowNum) != "undefined") {
  6659. loadNowNum = _loadNowNum;
  6660. }
  6661. let _autoScrollRate = await getData("autoScrollRate");
  6662. if (_autoScrollRate) {
  6663. autoScrollRate = _autoScrollRate;
  6664. }
  6665.  
  6666. author = await getData("author") || "";
  6667.  
  6668. manualPause = !!await getListData("pauseState", location.host);
  6669.  
  6670. let href = location.href.slice(0, 100);
  6671. try {
  6672. if (_unsafeWindow.initedPagetual) {
  6673. if (ruleImportUrlReg.test(href)) {
  6674. showTips(i18n('duplicate'));
  6675. }
  6676. return;
  6677. }
  6678. _unsafeWindow.initedPagetual = true;
  6679. } catch(e) {showTips(e)}
  6680. listenUrl();
  6681. _GM_registerMenuCommand(i18n("update"), () => {
  6682. showTips(i18n("beginUpdate"), "", 60000);
  6683. updateRules(() => {
  6684. showTips(i18n("updateSucc"));
  6685. location.reload();
  6686. },(rule, err) => {
  6687. showTips(`Failed to update ${rule.url} rules!`);
  6688. debug(err);
  6689. });
  6690. });
  6691. _GM_registerMenuCommand(i18n(forceState == 1 ? "enable" : "disableSite"), () => {
  6692. if (forceState == 1) {
  6693. forceState = 0;
  6694. showTips(i18n("enableSiteTips"));
  6695. changeStop(false);
  6696. } else {
  6697. forceState = 1;
  6698. showTips(i18n("disableSiteTips"));
  6699. changeStop(true);
  6700. sideController.remove();
  6701. }
  6702. setListData("forceState", location.host, forceState);
  6703. if (!ruleParser.curSiteRule.url) {
  6704. setTimeout(() => {
  6705. location.reload();
  6706. }, 500);
  6707. }
  6708. });
  6709. _GM_registerMenuCommand(i18n("toggleAutoScroll"), () => {
  6710. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  6711. autoScroll = parseInt(autoScroll) || 0;
  6712. if (autoScroll < 0) autoScroll = 0;
  6713. if (autoScroll && autoScroll != autoScrollRate) {
  6714. autoScrollRate = autoScroll;
  6715. storage.setItem("autoScrollRate", autoScrollRate);
  6716. }
  6717. setListData("autoScroll", location.host + location.pathname, autoScroll);
  6718. startAutoScroll();
  6719. });
  6720. startAutoScroll();
  6721.  
  6722.  
  6723. if (initConfig(href)) return;
  6724. pageReady = true;
  6725. if (forceState == 1) return;
  6726. let now = new Date().getTime();
  6727. if (!updateDate || now - updateDate > 2 * 24 * 60 * 60 * 1000) {
  6728. updateRules(() => {
  6729. }, (rule, err) => {}, true);
  6730. storage.setItem("ruleLastUpdate", now);
  6731. }
  6732. callback();
  6733. });
  6734. });
  6735. }
  6736.  
  6737. function requestDoc(url, callback) {
  6738. let postParams = url.match(/#p{(.*)}$/);
  6739. if (postParams) {
  6740. postParams = postParams[1];
  6741. url = url.replace(/#p{.*/, "");
  6742. }
  6743. let ruleHeaders = ruleParser.curSiteRule.headers;
  6744. let headers = {
  6745. 'Referer': location.href,
  6746. 'User-Agent': navigator.userAgent,
  6747. 'accept': 'text/html,application/xhtml+xml,application/xml',
  6748. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + charset,
  6749. };
  6750. if (ruleHeaders) {
  6751. if (ruleHeaders.referer) {
  6752. headers.referer = ruleHeaders.referer;
  6753. }
  6754. if (ruleHeaders.userAgent) {
  6755. headers.userAgent = ruleHeaders.userAgent;
  6756. }
  6757. if (ruleHeaders.accept) {
  6758. headers.accept = ruleHeaders.accept;
  6759. }
  6760. if (ruleHeaders.contentType) {
  6761. headers.contentType = ruleHeaders.contentType;
  6762. let ruleCharset = ruleHeaders.contentType.match(/charset\=([^;]+)/);
  6763. if (ruleCharset) charset = ruleCharset[1];
  6764. }
  6765. if (ruleHeaders.cookie) {
  6766. headers.cookie = ruleHeaders.cookie;
  6767. }
  6768. }
  6769. _GM_xmlhttpRequest({
  6770. url: url,
  6771. method: postParams ? 'POST' : 'GET',
  6772. data: postParams,
  6773. overrideMimeType: 'text/html;charset=' + charset,
  6774. headers: headers,
  6775. timeout: 20000,
  6776. onload: async function(res) {
  6777. if (isPause) return callback(false);
  6778. var doc = null, response = res.response;
  6779. let preCode = ruleParser.curSiteRule.pageElementPre || ruleParser.curSiteRule.pagePre;
  6780. if (preCode) {
  6781. try {
  6782. if (typeof preCode == 'function') {
  6783. response = preCode(response);
  6784. } else if (preCode.length == 2) {
  6785. response = response.replace(new RegExp(preCode[0], "gi"), preCode[1]);
  6786. } else {
  6787. response = Function("response",'"use strict";' + preCode)(response);
  6788. }
  6789. } catch(e) {
  6790. debug(e);
  6791. }
  6792. }
  6793. try {
  6794. doc = document.implementation.createHTMLDocument('');
  6795. doc.documentElement.innerHTML = response;
  6796. let base = doc.querySelector("base");
  6797. ruleParser.basePath = base ? base.href : url;
  6798. } catch (e) {
  6799. debug('parse error:' + e.toString());
  6800. }
  6801. if (charsetValid && !ruleHeaders) {
  6802. let equiv = doc.querySelector('[http-equiv="Content-Type"]');
  6803. if (equiv && equiv.content) {
  6804. let innerCharSet = equiv.content.match(/charset\=([^;]+)/);
  6805. if (innerCharSet && innerCharSet[1].replace("-", "").toLowerCase() != charset.replace("-", "").toLowerCase()) {
  6806. charset = innerCharSet[1];
  6807. return requestDoc(url, callback);
  6808. }
  6809. }
  6810. }
  6811. let pageElement = ruleParser.getPageElement(doc);
  6812. if ((!pageElement || pageElement.length == 0) && res.status >= 400) {
  6813. debug(res.status + " " + url, "Error status");
  6814. return callback(false);
  6815. }
  6816. if (inCors && (!pageElement || pageElement.length == 0) && ruleParser.curSiteRule.smart) {
  6817. let article;
  6818. for (let i = 0; i < mainSel.length; i++) {
  6819. article = doc.querySelectorAll(mainSel[i]);
  6820. if (article && article.length === 1) break;
  6821. }
  6822. if (article && article.length == 1) {
  6823. article = article[0];
  6824. ruleParser.curSiteRule.pageElement = article.nodeName.toLowerCase() + (article.id ? "#" + article.id : "") + (article.className ? "." + article.className.replace(/ /g, ".") : "") + ">*";
  6825. pageElement = article.children;
  6826. } else {
  6827. ruleParser.curSiteRule.pageElement = allOfBody;
  6828. pageElement = ruleParser.getPageElement(doc);
  6829. }
  6830. ruleParser.getInsert(true);
  6831. }
  6832. //只有1的話怕不是圖片哦
  6833. if (pageElement && (pageElement.length > 1 || (pageElement.length == 1 && !compareNodeName(pageElement[0], ["img"])))) {
  6834. await ruleParser.insertPage(doc, pageElement, url, callback, false);
  6835. if (ruleParser.curSiteRule.action == 1) {
  6836. isLoading = true;
  6837. requestFromIframe(url, async (doc, eles) => {
  6838. if (eles) {
  6839. await ruleParser.insertPage(doc, eles, url, callback, true);
  6840. } else isLoading = false;
  6841. });
  6842. } else ruleParser.curSiteRule.action = 0;
  6843. } else if ((ruleParser.curSiteRule.smart || curPage == 1) && !inCors) {
  6844. ruleParser.curSiteRule.action = 1;
  6845. requestFromIframe(url, async (doc, eles) => {
  6846. if (eles) {
  6847. await ruleParser.insertPage(doc, eles, url, callback, true);
  6848. } else isLoading = false;
  6849. });
  6850. } else {
  6851. debug("Stop as no page element");
  6852. ruleParser.noValidContent(url);
  6853. changeStop(true);
  6854. callback(false);
  6855. }
  6856. },
  6857. onerror: function(e) {
  6858. debug(e, "NetError");
  6859. callback(false);
  6860. },
  6861. ontimeout: function(e) {
  6862. debug(e, "NetTimeout");
  6863. callback(false);
  6864. }
  6865. });
  6866. }
  6867.  
  6868. function initPage() {
  6869. ruleParser.initPage(() => {
  6870. if (ruleParser.curSiteRule.autoLoadNum) {
  6871. autoLoadNum = ruleParser.curSiteRule.autoLoadNum;
  6872. }
  6873. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  6874. _GM_registerMenuCommand(i18n("nextSwitch"), () => {
  6875. nextSwitch.start();
  6876. });
  6877. }
  6878. if (ruleParser.nextLinkHref) {
  6879. let isJs = ruleParser.hrefIsJs(ruleParser.nextLinkHref);
  6880. if (!isJs) {
  6881. let inForce = (forceState == 2 || forceState == 3);
  6882. _GM_registerMenuCommand(i18n(inForce ? "cancelForceIframe" : "forceIframe"), () => {
  6883. if (inForce) {
  6884. setListData("forceState", location.host, "");
  6885. } else {
  6886. let _state = ruleParser.curSiteRule.action > 0 || confirm(i18n("forceAllBody")) ? 2 : 3;
  6887. setListData("forceState", location.host, _state);
  6888. }
  6889. setTimeout(() => {
  6890. location.reload();
  6891. }, 500);
  6892. });
  6893. }
  6894. _GM_registerMenuCommand(i18n("loadNow"), () => {
  6895. if (autoLoadNum != -1) {
  6896. autoLoadNum = -1;
  6897. return;
  6898. }
  6899. let loadNum = window.prompt(i18n("loadConfirm"), loadNowNum);
  6900. if (loadNum === "" || loadNum === null) return;
  6901. loadNum = Math.abs(parseInt(loadNum)) || 0;
  6902. if (loadNowNum != loadNum) {
  6903. loadNowNum = loadNum;
  6904. storage.setItem("loadNowNum", loadNowNum);
  6905. }
  6906. autoLoadNum = loadNum;
  6907. nextPage();
  6908. });
  6909. }
  6910. initListener();
  6911. });
  6912. }
  6913.  
  6914. var pageBarStyle, mainStyleEle, mainStyleStyle;
  6915. function initView() {
  6916. if (!mainStyleStyle) {
  6917. mainStyleStyle = `
  6918. .pagetual_pageBar{
  6919. -moz-transition:all 0.3s ease-in-out 0s;
  6920. -webkit-transition:all 0.3s ease-in-out 0s;
  6921. transition:all 0.3s ease-in-out 0s;
  6922. font-family: Arial,sans-serif !important;
  6923. text-align: center !important;
  6924. }
  6925. .pagetual_pageBar.stop {
  6926. -webkit-filter: invert(100%);
  6927. filter: invert(100%);
  6928. opacity: 1!important;
  6929. }
  6930. .pagetual_pageBar.hide {
  6931. display: none!important;
  6932. }
  6933. .pagetual-hide {
  6934. display: none!important;
  6935. }
  6936. .pagetual_pageBar:hover {
  6937. opacity: 1!important;
  6938. box-shadow: 0px 0px 10px 0px #000000aa;
  6939. border-radius: 20px;
  6940. background-color: rgb(240 240 240 / 80%);
  6941. border-color: transparent!important;
  6942. }
  6943. .pagetual_pageBar span {
  6944. vertical-align: super;
  6945. }
  6946. .pagetual_pageBar a::before,
  6947. .pagetual_pageBar a::after {
  6948. content: none;
  6949. }
  6950. .pagetual_pageBar a>span {
  6951. margin-top: 0!important;
  6952. pointer-events: none;
  6953. padding: unset;
  6954. opacity: 0;
  6955. -moz-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  6956. -webkit-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  6957. transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  6958. transform: none;
  6959. left: 0;
  6960. margin-left: calc(50% - 20px);
  6961. }
  6962. .pagetual_pageBar a>span:hover {
  6963. color: red;
  6964. }
  6965. .pagetual_pageBar a:hover>span {
  6966. opacity: 1!important;
  6967. }
  6968. .pagetual_pageBar span.prevScreen,
  6969. .pagetual_pageBar span.nextScreen {
  6970. display: block!important;
  6971. top: unset !important;
  6972. padding: unset !important;
  6973. opacity: 0!important;
  6974. }
  6975. .pagetual_pageBar a:hover>span.prevScreen {
  6976. margin-top: -${rulesData.opacity == 1 ? 31 : 30}px!important;
  6977. pointer-events: all;
  6978. }
  6979. .pagetual_pageBar span.refreshRing {
  6980. position: absolute;
  6981. top: 0;
  6982. opacity: 0;
  6983. height: 30px;
  6984. margin-left: calc(50% - 23px);
  6985. display: block!important;
  6986. }
  6987. .pagetual_pageBar span.refreshRing>svg {
  6988. background: white;
  6989. border-radius: 50%;
  6990. }
  6991. .pagetual_pageBar a:hover>span.refreshRing {
  6992. opacity: 0.3;
  6993. -webkit-animation: pagetual_ring 2.0s infinite linear;
  6994. animation: pagetual_ring 2.0s infinite linear;
  6995. }
  6996. @-webkit-keyframes pagetual_ring {
  6997. 0% { -webkit-transform: rotate(0deg) }
  6998. 100% {
  6999. -webkit-transform: rotate(360deg);
  7000. }
  7001. }
  7002. @keyframes pagetual_ring {
  7003. 0% {
  7004. transform: rotate(0deg);
  7005. -webkit-transform: rotate(0deg);
  7006. } 100% {
  7007. transform: rotate(360deg);
  7008. -webkit-transform: rotate(360deg);
  7009. }
  7010. }
  7011. .pagetual_pageBar a:hover>span.nextScreen {
  7012. margin-top: 30px!important;
  7013. pointer-events: all;
  7014. }
  7015. .pagetual_pageBar span>svg {
  7016. -moz-transition:transform 0.5s ease, opacity 0.3s ease;
  7017. -webkit-transition:transform 0.5s ease, opacity 0.3s ease;
  7018. transition:transform 0.5 ease, opacity 0.3s ease;
  7019. opacity: 0;
  7020. }
  7021. .pagetual_pageBar.stop span>svg{
  7022. opacity: 1;
  7023. }
  7024. .pagetual_pageBar.stop span>svg>path{
  7025. transform: scale(.8);
  7026. transform-origin: center;
  7027. -moz-transition:transform 0.3s ease;
  7028. -webkit-transition:transform 0.3s ease;
  7029. transition:transform 0.3 ease;
  7030. }
  7031. .pagetual_pageBar.stop:hover span>svg>path{
  7032. transform: unset;
  7033. }
  7034. .pagetual_pageBar:hover span>svg {
  7035. opacity: 1;
  7036. }
  7037. .pagetual_pageBar span>svg.upSvg:hover {
  7038. transform: rotate(360deg) scale3d(1.2, 1.2, 1.2);
  7039. }
  7040. .pagetual_pageBar span>svg.downSvg:hover {
  7041. transform: rotate(540deg) scale3d(1.2, 1.2, 1.2)!important;
  7042. }
  7043. .pagetual_pageBar .pagetual_pageNum{
  7044. color: #55555f;
  7045. }
  7046. .pagetual_pageBar .pagetual_pageNum:hover{
  7047. color: #ff6464;
  7048. }
  7049. .pagetual_tipsWords {
  7050. font-size: 50px;
  7051. font-weight: bold;
  7052. font-family: "黑体", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
  7053. "Oxygen", "Ubuntu", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
  7054. "Segoe UI Emoji", "Segoe UI Symbol";
  7055. color: #ffffff;
  7056. min-height: 70px;
  7057. max-width: 80%;
  7058. line-height: 1.5;
  7059. position: fixed;
  7060. left: 50%;
  7061. top: 10%;
  7062. margin-left: -99999px;
  7063. padding: 0 15px;
  7064. z-index: 2147483647;
  7065. background-color: #000;
  7066. border: 1px solid #303030;
  7067. border-radius: 10px;
  7068. opacity: 0;
  7069. filter: alpha(opacity=65);
  7070. box-shadow: 5px 5px 20px 0px #000;
  7071. -moz-transition:opacity 0.3s ease-in-out 0s;
  7072. -webkit-transition:opacity 0.3s ease-in-out 0s;
  7073. transition:opacity 0.3s ease-in-out 0s;
  7074. pointer-events: none;
  7075. word-break: break-all;
  7076. }
  7077. .pagetual_tipsWords>a {
  7078. color: #ffffff;
  7079. }
  7080. .pagetual_loading {
  7081. width: 50px;
  7082. height: 50px;
  7083. margin: 10px auto;
  7084. border-radius: 100%;
  7085. display: flex;
  7086. -webkit-animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  7087. animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  7088. }
  7089. @-webkit-keyframes pagetual_loading_scaleout {
  7090. 0% { -webkit-transform: scale(0.0) }
  7091. 100% {
  7092. -webkit-transform: scale(1.0);
  7093. opacity: 0;
  7094. }
  7095. }
  7096. @keyframes pagetual_loading_scaleout {
  7097. 0% {
  7098. transform: scale(0.0);
  7099. -webkit-transform: scale(0.0);
  7100. } 100% {
  7101. transform: scale(1.0);
  7102. -webkit-transform: scale(1.0);
  7103. opacity: 0;
  7104. }
  7105. }
  7106. .pagetual_loading_text {
  7107. white-space: nowrap;
  7108. -webkit-animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  7109. animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  7110. }
  7111. @-webkit-keyframes pagetual_loading_opacity {
  7112. 0% { opacity: 1 }
  7113. 50% { opacity: 0.2 }
  7114. 100% { opacity: 1 }
  7115. }
  7116. @keyframes pagetual_loading_opacity {
  7117. 0% { opacity: 1 }
  7118. 50% { opacity: 0.2 }
  7119. 100% { opacity: 1 }
  7120. }
  7121. `;
  7122. 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%);"}`;
  7123. }
  7124. if (!mainStyleEle || !mainStyleEle.parentNode) {
  7125. mainStyleEle = _GM_addStyle(mainStyleStyle);
  7126. }
  7127. }
  7128. var loadingDiv = document.createElement("div");
  7129. 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;";
  7130.  
  7131. 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;`;
  7132. function setLoadingDiv(loadingText) {
  7133. 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>`}`);
  7134. }
  7135.  
  7136. 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>`;
  7137. 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;`;
  7138. 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>`;
  7139. 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);`;
  7140.  
  7141. 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;`;
  7142. 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;`;
  7143. var sideControllerIcon = '';
  7144.  
  7145. var tipsWords = document.createElement("div");
  7146. tipsWords.className = "pagetual_tipsWords";
  7147.  
  7148. function changeStop(stop) {
  7149. isPause = stop;
  7150. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar,#pagetual-sideController"), bar => {
  7151. if (isPause) {
  7152. bar.classList.add("stop");
  7153. } else {
  7154. bar.classList.remove("stop");
  7155. }
  7156. });
  7157. if (!isPause) ruleParser.showAddedElements();
  7158. manualPause = isPause;
  7159. if (sideController.inited) setListData("pauseState", location.host, isPause ? true : "");
  7160. }
  7161.  
  7162. function changeHideBar(hide) {
  7163. isHideBar = hide;
  7164. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar"), bar => {
  7165. if (isHideBar) {
  7166. bar.classList.add("hide");
  7167. } else {
  7168. bar.classList.remove("hide");
  7169. }
  7170. });
  7171. }
  7172.  
  7173. function isInViewPort(element) {
  7174. if (!getBody(document).contains(element)) return false;
  7175. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  7176. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  7177. const {
  7178. top,
  7179. right,
  7180. bottom,
  7181. left,
  7182. } = element.getBoundingClientRect();
  7183.  
  7184. return (
  7185. top >= 0 &&
  7186. left >= 0 &&
  7187. right <= viewWidth + 1 &&
  7188. top <= viewHeight * rate &&
  7189. isVisible(element, _unsafeWindow)
  7190. );
  7191. }
  7192.  
  7193. function getPageBar() {
  7194. let preBar = null, nextBar = null;
  7195. let pageBars = [].slice.call(document.querySelectorAll(".pagetual_pageBar"));
  7196. for (let i = 0; i < pageBars.length; i++) {
  7197. let pageBar = pageBars[i];
  7198. if (!pageBar || !getBody(document).contains(pageBar)) continue;
  7199. let {
  7200. top,
  7201. right,
  7202. bottom,
  7203. left,
  7204. } = pageBar.getBoundingClientRect();
  7205. if (top > 500) {
  7206. nextBar = pageBar;
  7207. preBar = (i - 1 >= 0 ? pageBars[i - 1] : null);
  7208. if (pageBar && getBody(document).contains(pageBar)) {
  7209. let {
  7210. top,
  7211. right,
  7212. bottom,
  7213. left,
  7214. } = pageBar.getBoundingClientRect();
  7215. if (top < -500) {
  7216. preBar = pageBar;
  7217. } else preBar = (i - 2 >= 0 ? pageBars[i - 2] : null);
  7218. }
  7219. break;
  7220. }
  7221. }
  7222. if (!nextBar) preBar = pageBars[pageBars.length - 2];
  7223. return {preBar: preBar, nextBar: nextBar};
  7224. }
  7225.  
  7226. var urlChanged = false;
  7227. var urlChanging = false;
  7228. var urlchangeHandler = e => {
  7229. if (ruleParser && ruleParser.curSiteRule && ruleParser.curSiteRule.listenUrlChange == false) return;
  7230. isPause = true;
  7231. setTimeout(() => {
  7232. lastActiveUrl = location.href;
  7233. if (urlChanging) return;
  7234. urlChanging = true;
  7235. let href = location.href.slice(0, 60);
  7236. if (href == configPage[1]) {
  7237. setTimeout(() => {
  7238. initConfig(href);
  7239. urlChanging = false;
  7240. }, 1000);
  7241. } else {
  7242. setTimeout(() => {
  7243. if (guidePage.test(href)) {
  7244. setTimeout(() => {
  7245. initConfig(href);
  7246. urlChanging = false;
  7247. }, 1000);
  7248. } else {
  7249. ruleParser.urlChanged();
  7250. if (!ruleParser.nextLinkHref) {
  7251. isLoading = false;
  7252. }
  7253. urlChanging = false;
  7254. //if (!pageReady && !ruleImportUrlReg.test(href)) location.reload();
  7255. }
  7256. }, 500);
  7257. }
  7258. }, 1);
  7259. };
  7260. window.addEventListener('pagetual_pushState', urlchangeHandler);
  7261. /*var _wr = function(type) {
  7262. var orig = history[type];
  7263. return function() {
  7264. var rv = orig.apply(this, arguments);
  7265. var e = new Event('pagetual_' + type);
  7266. e.arguments = arguments;
  7267. window.dispatchEvent(e);
  7268. return rv;
  7269. };
  7270. };
  7271. history.pushState = _wr('pushState');*/
  7272.  
  7273. function listenUrl() {
  7274. var prevPathname = window.location.pathname;
  7275. var prevSearch = window.location.search;
  7276. var checkUrlTime = 100;
  7277. var checkUrlTimer;
  7278. var checkClickedEle = null;
  7279. var checkFunc = () => {
  7280. if (forceState == 1) return;
  7281. if (checkClickedEle) {
  7282. if (!clickedSth && checkClickedEle && checkClickedEle.nodeName) {
  7283. if (compareNodeName(checkClickedEle, ["a", "button"])) {
  7284. clickedSth = true;
  7285. } else {
  7286. let targetStyle = _unsafeWindow.getComputedStyle(checkClickedEle);
  7287. if (targetStyle.cursor == "pointer") clickedSth = true;
  7288. }
  7289. }
  7290. checkClickedEle = null;
  7291. }
  7292. if (checkUrlTime < 5000) {
  7293. checkUrlTime += checkUrlTime>>1;
  7294. }
  7295. clearTimeout(checkUrlTimer);
  7296. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7297. if (document.hidden) return;
  7298. if (!ruleParser.canListenUrlChange()) {
  7299. return;
  7300. }
  7301. if ((prevPathname !== window.location.pathname || prevSearch !== window.location.search) && window.location.href != ruleParser.historyUrl) {
  7302. checkUrlTime = 2000;
  7303. urlWillChange = true;
  7304. var e = new Event('pagetual_pushState');
  7305. e.arguments = arguments;
  7306. window.dispatchEvent(e);
  7307. clickedSth = false;
  7308. }
  7309. prevPathname = window.location.pathname;
  7310. prevSearch = window.location.search;
  7311. };
  7312. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7313.  
  7314. document.addEventListener("click", e => {
  7315. if (!checkClickedEle) {
  7316. checkClickedEle = e.target;
  7317. checkUrlTime = 300;
  7318. clearTimeout(checkUrlTimer);
  7319. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7320. }
  7321. });
  7322. }
  7323.  
  7324. let scrollContainer;
  7325. function distToBottom () {
  7326. let scrolly = window.scrollY;
  7327. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  7328. if (!scrollContainer || !document.documentElement.contains(scrollContainer)) {
  7329. if (curPage > 1 || ruleParser.nextLinkHref) {
  7330. let pageEle = ruleParser.getPageElement(document);
  7331. if (pageEle && pageEle.length) {
  7332. let parent = pageEle[0].parentNode, pageScrollY = parent.scrollTop;
  7333. while (parent && pageScrollY == 0) {
  7334. parent = parent.parentNode;
  7335. pageScrollY = parent.scrollTop;
  7336. }
  7337. if (pageScrollY) {
  7338. scrollContainer = parent;
  7339. return scrollContainer.scrollHeight - pageScrollY - windowHeight;
  7340. }
  7341. }
  7342. }
  7343. }
  7344. if (scrollContainer) {
  7345. return scrollContainer.scrollHeight - scrollContainer.scrollTop - windowHeight;
  7346. }
  7347.  
  7348. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7349. return scrollH - scrolly - windowHeight;
  7350. }
  7351.  
  7352. let scrollHandler, clickToResetHandler, dblclickHandler, keydownHandler, hashchangeHandler, manualModeKeyHandler, pagetualNextHandler, keyupHandler;
  7353. function initListener () {
  7354. document.removeEventListener('scroll', scrollHandler, true);
  7355. document.removeEventListener('wheel', scrollHandler, true);
  7356. document.removeEventListener('dblclick', dblclickHandler);
  7357. document.removeEventListener('keydown', keydownHandler);
  7358. window.removeEventListener('hashchange', hashchangeHandler, false);
  7359. document.removeEventListener('keydown', manualModeKeyHandler);
  7360. document.removeEventListener('pagetual.next', pagetualNextHandler, false);
  7361. document.removeEventListener('keyup', keyupHandler);
  7362. let loadmoreBtn, loadingMore = true, lastScroll = 0, checkLoadMoreTimes = 0;
  7363. if (ruleParser.curSiteRule.smart) {
  7364. loadingMore = false;
  7365. } else if (ruleParser.curSiteRule.loadMore) {
  7366. loadingMore = false;
  7367. }
  7368. clickMode = typeof ruleParser.curSiteRule.clickMode == 'undefined' ? rulesData.clickMode : ruleParser.curSiteRule.clickMode;
  7369. let clickingNext = false;
  7370. let clickNext = async () => {
  7371. if (clickingNext) return;
  7372. clickingNext = true;
  7373. setTimeout(() => {
  7374. clickingNext = false;
  7375. }, 1500);
  7376. let nextLink = ruleParser.nextLinkHref;
  7377. if (!nextLink) return;
  7378. let isJs = ruleParser.hrefIsJs(nextLink);
  7379. if (isJs) {
  7380. let nextBtn = ruleParser.nextLinkEle;
  7381. if (!nextBtn || !nextBtn.offsetParent) nextBtn = await ruleParser.getNextLink(document, true);
  7382. if (nextBtn) emuClick(nextBtn);
  7383. } else {
  7384. window.location.href = nextLink;
  7385. }
  7386. };
  7387. let checkScrollReach = () => {
  7388. let dist = distToBottom();
  7389. if (clickMode) {
  7390. if (dist < 10) {
  7391. clickNext();
  7392. }
  7393. } else if (dist < bottomGap) {
  7394. nextPage();
  7395. }
  7396. };
  7397. scrollHandler = e => {
  7398. if (urlChanged && !isLoading) {
  7399. ruleParser.initPage(() => {});
  7400. urlChanged = false;
  7401. loadingMore = false;
  7402. return;
  7403. }
  7404. if (isPause) return;
  7405. if (!loadingMore) {
  7406. loadmoreBtn = getLoadMore(document, loadmoreBtn);
  7407. if (loadmoreBtn) {
  7408. if (isInViewPort(loadmoreBtn)) {
  7409. emuClick(loadmoreBtn);
  7410. loadingMore = true;
  7411. setTimeout(() => {loadingMore = false}, 200);
  7412. }
  7413. } else {
  7414. loadingMore = true;
  7415. if (!ruleParser.curSiteRule.smart || checkLoadMoreTimes++ < 3) {
  7416. setTimeout(() => {loadingMore = false}, 200);
  7417. }
  7418. }
  7419. }
  7420. if (!isLoading && !stopScroll) {
  7421. checkScrollReach();
  7422. }
  7423. ruleParser.changeVisibility();
  7424. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  7425. if (ruleParser.curSiteRule.lockScroll) {
  7426. if (isLoading && Math.abs(lastScroll - curScroll) > 350) {
  7427. getBody(document).scrollTop = lastScroll;
  7428. document.documentElement.scrollTop = lastScroll;
  7429. } else {
  7430. lastScroll = curScroll;
  7431. }
  7432. }
  7433. if (targetY >= 0) {
  7434. if (Math.abs(targetY - curScroll) < 100) {
  7435. targetY = -1;
  7436. }
  7437. }
  7438. };
  7439. dblclickHandler = e => {
  7440. if (forceState == 1 || compareNodeName(e.target, ["input", "textarea", "select", "a", "button", "svg", "use", "img", "path"])) return;
  7441. if (!rulesData.dbClick2StopKey) {
  7442. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  7443. (rulesData.dbClick2StopAlt && !e.altKey) ||
  7444. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  7445. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  7446. return;
  7447. }
  7448. }
  7449. if (!compareNodeName(e.target, ["body"]) && !e.target.classList.contains('pagetual_pageBar')) {
  7450. try {
  7451. let selection = window.getSelection();
  7452. let selStr = selection.toString().trim();
  7453. if (!selStr) {
  7454. selection = selection.getRangeAt(0);
  7455. selStr = selection && selection.cloneContents().children[0];
  7456. if (selStr && !compareNodeName(selStr, ["img"])) selStr = false;
  7457. }
  7458. if (selStr) {
  7459. return;
  7460. }
  7461. } catch (e) {}
  7462. }
  7463. if (rulesData.dbClick2Stop && (ruleParser.nextLinkHref || loadmoreBtn)) {
  7464. setTimeout(() => {
  7465. if (rulesData.hideBarButNoStop || rulesData.hideBar) {
  7466. changeHideBar(!isHideBar);
  7467. }
  7468. if (!rulesData.hideBarButNoStop) {
  7469. changeStop(!isPause);
  7470. showTips(i18n(isPause ? "disable" : "enable"));
  7471. }
  7472. if (!isPause) {
  7473. checkScrollReach();
  7474. }
  7475. }, 10);
  7476. }
  7477. };
  7478. document.addEventListener('dblclick', dblclickHandler);
  7479. clickToResetHandler = e => {
  7480. if (!ruleParser.nextLinkHref) isLoading = false;
  7481. };
  7482. document.addEventListener('click', clickToResetHandler);
  7483. if (rulesData.dbClick2StopKey) {
  7484. keydownHandler = e => {
  7485. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  7486. (rulesData.dbClick2StopAlt && !e.altKey) ||
  7487. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  7488. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  7489. return;
  7490. }
  7491. if (document.activeElement &&
  7492. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  7493. document.activeElement.contentEditable == 'true')) {
  7494. return;
  7495. }
  7496. var key = e.key.toLowerCase();
  7497. if (rulesData.dbClick2StopKey.toLowerCase() == key) {
  7498. if (forceState == 1) {
  7499. forceState = 0;
  7500. showTips(i18n("enableSiteTips"));
  7501. changeStop(false);
  7502. } else {
  7503. forceState = 1;
  7504. showTips(i18n("disableSiteTips"));
  7505. changeStop(true);
  7506. sideController.remove();
  7507. }
  7508. if (!ruleParser.curSiteRule.url) {
  7509. setListData("forceState", location.host, forceState);
  7510. setTimeout(() => {
  7511. location.reload();
  7512. }, 500);
  7513. }
  7514. }
  7515. };
  7516. document.addEventListener('keydown', keydownHandler);
  7517. }
  7518. if (ruleParser.curSiteRule.listenHashChange) {
  7519. hashchangeHandler = () => {
  7520. isPause = true;
  7521. ruleParser.urlChanged();
  7522. if (!ruleParser.nextLinkHref) isLoading = false;
  7523. };
  7524. window.addEventListener('hashchange', hashchangeHandler, false);
  7525. }
  7526. let manualMode = typeof ruleParser.curSiteRule.manualMode == 'undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode;
  7527. if (manualMode) {
  7528. manualModeKeyHandler = e => {
  7529. if (document.activeElement &&
  7530. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  7531. document.activeElement.contentEditable == 'true')) {
  7532. return;
  7533. }
  7534. if (e.keyCode == 39) {
  7535. clickNext();
  7536. } else if (e.keyCode == 37) {
  7537. history.back();
  7538. }
  7539. };
  7540. document.addEventListener('keydown', manualModeKeyHandler);
  7541. pagetualNextHandler = () => {
  7542. clickNext();
  7543. };
  7544. document.addEventListener('pagetual.next', pagetualNextHandler, false);
  7545. return;
  7546. }
  7547. if (rulesData.arrowToScroll) {
  7548. keyupHandler = e => {
  7549. if (document.activeElement &&
  7550. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  7551. document.activeElement.contentEditable == 'true')) {
  7552. return;
  7553. }
  7554. if (e.keyCode == 39) {
  7555. let nextPageBar=getPageBar().nextBar;
  7556. if (nextPageBar) {
  7557. scrollToPageBar(nextPageBar);
  7558. } else {
  7559. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  7560. window.scrollTo({ top: scrollTop + (window.innerHeight || document.documentElement.clientHeight), behavior: 'instant'});
  7561. }
  7562. } else if (e.keyCode == 37) {
  7563. let prePageBar = getPageBar().preBar;
  7564. if (prePageBar) {
  7565. scrollToPageBar(prePageBar);
  7566. } else {
  7567. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  7568. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'instant'});
  7569. }
  7570. }
  7571. };
  7572. document.addEventListener('keyup', keyupHandler);
  7573. }
  7574. if (!ruleParser.curSiteRule.wheel) {
  7575. document.addEventListener('scroll', scrollHandler, true);
  7576. }
  7577. document.addEventListener('wheel', scrollHandler, true);
  7578. }
  7579.  
  7580. let hideTipsTimeout;
  7581. function showTips(content, href, time, wordColor, backColor) {
  7582. initView();
  7583. document.documentElement.appendChild(tipsWords);
  7584. tipsWords.style.color = wordColor || 0xFFFFFF;
  7585. tipsWords.style.backgroundColor = backColor || 0x000;
  7586. let _time = 1500;
  7587. if (href) {
  7588. _time = 3500;
  7589. tipsWords.innerHTML = createHTML(`<a href='${href}' target='_blank'>${content}</a>`);
  7590. tipsWords.style.pointerEvents = 'all';
  7591. } else {
  7592. tipsWords.innerHTML = createHTML(content);
  7593. }
  7594. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  7595. setTimeout(() => {
  7596. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  7597. }, 0);
  7598. setTimeout(() => {
  7599. tipsWords.style.opacity = 0.8;
  7600. clearTimeout(hideTipsTimeout);
  7601. hideTipsTimeout = setTimeout(() => {
  7602. tipsWords.style.opacity = 0;
  7603. tipsWords.style.pointerEvents = '';
  7604. }, time || _time);
  7605. }, 1);
  7606. }
  7607.  
  7608. const loadmoreReg = /^\s*((点击)?加载更多|(點擊)?加載更多|load\s*more|もっと読み込む)[.…]*\s*$/i;
  7609. 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";
  7610. function getLoadMore(doc, loadmoreBtn) {
  7611. if (!loadmoreBtn || !getBody(doc).contains(loadmoreBtn) || /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  7612. if (!ruleParser.curSiteRule.smart && !ruleParser.curSiteRule.loadMore) return null;
  7613. if (loadmoreBtn) return loadmoreBtn;
  7614. let btnSel = ruleParser.curSiteRule.loadMore || defaultLoadmoreSel;
  7615. if (btnSel) {
  7616. loadmoreBtn = getElement(btnSel, doc, null, true);
  7617. }
  7618. if (!loadmoreBtn) {
  7619. let buttons = doc.querySelectorAll("input,button,a,div[onclick]");
  7620. for (let i = 0; i < buttons.length; i++) {
  7621. let button = buttons[i];
  7622. if (!button.innerText || button.innerText.length > 20) continue;
  7623. if (button && loadmoreReg.test(button.innerText)) {
  7624. loadmoreBtn = button;
  7625. break;
  7626. }
  7627. }
  7628. }
  7629. if (loadmoreBtn && !ruleParser.curSiteRule.loadMore && loadmoreBtn.dataset.ajax !== "true") {
  7630. let href = loadmoreBtn.getAttribute("href");
  7631. if (href && href != "/" && !ruleParser.hrefIsJs(href)) {
  7632. loadmoreBtn = null;
  7633. }
  7634. }
  7635. if (loadmoreBtn && /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  7636. if (loadmoreBtn) debug(loadmoreBtn, 'Load more button');
  7637. return loadmoreBtn;
  7638. }
  7639.  
  7640. var targetY = -1;
  7641. function scrollToPageBar(bar) {
  7642. if (window.pageYOffset == 0) {
  7643. bar.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" });
  7644. } else {
  7645. let yOffset = -20;
  7646. if (typeof ruleParser.curSiteRule.pageBarTop !== 'undefined') {
  7647. yOffset = -ruleParser.curSiteRule.pageBarTop;
  7648. }
  7649. targetY = bar.getBoundingClientRect().top + window.pageYOffset + yOffset;
  7650. window.scrollTo({ top: targetY, behavior: 'smooth'});
  7651. }
  7652. }
  7653.  
  7654. const pageNumReg=/[&\/\?](p=|page[=\/_-]?)\d+|[_-]\d+\./;
  7655. function createPageBar(url) {
  7656. curPage++;
  7657. sideController.setup();
  7658. let posEle = null;
  7659. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7660. let insert = ruleParser.getInsert();
  7661. if (!insert || !insert.parentNode) return;
  7662. if (forceState == 2) {
  7663. posEle = getBody(document);
  7664. posEle = posEle.children[posEle.children.length - 1];
  7665. } else {
  7666. posEle = insert;
  7667. }
  7668. while (posEle && !posEle.offsetParent) {
  7669. posEle = posEle.previousElementSibling || posEle.parentNode;
  7670. }
  7671. if (posEle) {
  7672. let actualBottom = getElementBottom(posEle);
  7673. bottomGap = scrollH - actualBottom + (window.innerHeight || document.documentElement.clientHeight) * rate;
  7674. if (bottomGap < 100) bottomGap = 100;
  7675. } else {
  7676. bottomGap = 1000;
  7677. }
  7678. if (rulesData.opacity == 0 || ruleParser.curSiteRule.pageBar === 0) return null;
  7679. url = url.replace(/#p{.*/, "");
  7680. let example = (ruleParser.curSiteRule.insertPos == 2 || ruleParser.curSiteRule.insertPos == "in") ? insert.children[0] : (insert.parentNode.children[0] || insert);
  7681. while (example && (compareNodeName(example, ["script", "style"]) || example.className == "pagetual_pageBar")) {
  7682. example = example.nextElementSibling;
  7683. }
  7684. if (!example || !example.parentNode) example = insert;
  7685. if (example.nodeType != 1) {
  7686. example = example.previousElementSibling || example.parentNode;
  7687. if (!example || example.nodeType != 1) return;
  7688. }
  7689. let exampleStyle = _unsafeWindow.getComputedStyle(example);
  7690. let inTable, inLi;
  7691. if (forceState == 2) {
  7692. inTable = inLi = false;
  7693. } else {
  7694. inTable = compareNodeName(example.parentNode, ["table", "tbody"]) ||
  7695. compareNodeName(example, ["tr", "tbody"]) ||
  7696. exampleStyle.display == "table-row" ||
  7697. (example.nextElementSibling && compareNodeName(example.nextElementSibling, ["tr", "tbody"]));
  7698. inLi = compareNodeName(example, ["li"]) || (example.nextElementSibling && compareNodeName(example.nextElementSibling, ["li"]));
  7699. }
  7700. let pageBar = document.createElement(inTable ? "tr" : (inLi ? "li" : "div"));
  7701. let upSpan = document.createElement("span");
  7702. let downSpan = document.createElement("span");
  7703. let pageText = document.createElement("a");
  7704. let pageNum;
  7705. pageBar.className = isHideBar ? "pagetual_pageBar hide" : "pagetual_pageBar";
  7706. pageBar.id = "pagetual_pageBar" + curPage;
  7707. pageBar.setAttribute("translate", "no");
  7708. if (isPause) {
  7709. pageBar.classList.add("stop");
  7710. }
  7711. pageBar.style.cssText = pageBarStyle;
  7712. pageBar.title = i18n(isPause ? "enable" : "disable");
  7713. upSpan.innerHTML = createHTML(upSvg);
  7714. upSpan.children[0].style.cssText = upSvgCSS;
  7715. upSpan.title = i18n("toTop");
  7716. downSpan.innerHTML = createHTML(downSvg);
  7717. downSpan.children[0].style.cssText = downSvgCSS;
  7718. downSpan.title = i18n("toBottom");
  7719. upSpan.style.cssText = initStyle;
  7720. downSpan.style.cssText = initStyle;
  7721. pageText.href = url;
  7722. pageText.style.cssText = pageTextStyle;
  7723. pageText.title = i18n("current");
  7724. if (openInNewTab == 1) pageText.target = "_blank";
  7725. pageBar.appendChild(upSpan);
  7726. pageBar.appendChild(pageText);
  7727. let touched = false;
  7728. let touchBodyHandler = e => {
  7729. touched = false;
  7730. getBody(document).removeEventListener('touchstart', touchBodyHandler, { passive: false, capture: false });
  7731. };
  7732. pageText.addEventListener("touchstart", e => {
  7733. if (touched) return;
  7734. touched = true;
  7735. pageText.style.pointerEvents = 'none';
  7736. setTimeout(() => {
  7737. pageText.style.pointerEvents = 'all';
  7738. }, 250);
  7739. getBody(document).addEventListener("touchstart", touchBodyHandler, { passive: false, capture: false });
  7740. }, { passive: false, capture: false });
  7741. if (ruleParser.nextTitle) {
  7742. pageText.innerHTML = createHTML(ruleParser.nextTitle + " ");
  7743. pageText.title = ruleParser.nextTitle;
  7744. }
  7745. if (ruleParser.curSiteRule.pageNum || pageNumReg.test(url)) {
  7746. pageText.innerHTML = createHTML(pageText.innerHTML + i18n("page"));
  7747. pageNum = document.createElement("span");
  7748. let num = ruleParser.getPageNumFromUrl(url, curPage);
  7749. pageNum.innerHTML = createHTML(num + "<i style='font-size: 0;'>&nbsp;</i>");
  7750. pageNum.className = "pagetual_pageNum";
  7751. pageNum.title = i18n("inputPageNum");
  7752. pageNum.style.cssText = pageTextStyle;
  7753. pageNum.style.cursor = "pointer";
  7754. pageNum.style.color = "";
  7755. pageNum.style.marginLeft = "5px";
  7756. pageNum.addEventListener("click", e => {
  7757. let pageInput = prompt(i18n("inputPageNum"), num || "1");
  7758. if (pageInput) {
  7759. let localPageBar = document.querySelector("#pagetual_pageBar" + pageInput);
  7760. if (localPageBar) {
  7761. scrollToPageBar(localPageBar);
  7762. } else {
  7763. let pageLink = ruleParser.getLinkByPage(url, pageInput);
  7764. if (pageLink) {
  7765. _GM_openInTab(pageLink, {active:true});
  7766. }
  7767. }
  7768. }
  7769. e.preventDefault();
  7770. e.stopPropagation();
  7771. });
  7772. pageBar.appendChild(pageNum);
  7773. } else {
  7774. pageText.innerHTML = createHTML(pageText.innerHTML + i18n("page") + curPage + "<i style='font-size: 0;'>&nbsp;</i>");
  7775. }
  7776. let preBtn = document.createElement("span");
  7777. preBtn.innerHTML = createHTML("∧");
  7778. preBtn.title = i18n("prevPage");
  7779. preBtn.className = "prevScreen";
  7780. 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; ";
  7781. let nextBtn = document.createElement("span");
  7782. nextBtn.innerHTML = createHTML("∨");
  7783. nextBtn.title = i18n("nextPage");
  7784. nextBtn.className = "nextScreen";
  7785. 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; ";
  7786. let localPage = curPage;
  7787. preBtn.addEventListener("click", e => {
  7788. e.stopPropagation();
  7789. e.preventDefault();
  7790. let prePageBar = document.querySelector("#pagetual_pageBar" + (localPage - 1));
  7791. if (prePageBar) {
  7792. scrollToPageBar(prePageBar);
  7793. } else {
  7794. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  7795. targetY = scrollTop - (window.innerHeight || document.documentElement.clientHeight);
  7796. window.scrollTo({ top: targetY, behavior: 'smooth'});
  7797. }
  7798. });
  7799. nextBtn.addEventListener("click", e => {
  7800. e.stopPropagation();
  7801. e.preventDefault();
  7802. let nextPageBar = document.querySelector("#pagetual_pageBar" + (localPage + 1));
  7803. if (nextPageBar) {
  7804. scrollToPageBar(nextPageBar);
  7805. } else {
  7806. scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7807. targetY = scrollH || 9999999;
  7808. window.scrollTo({ top: targetY, behavior: 'smooth'});
  7809. }
  7810. });
  7811. if (!rulesData.hideBarArrow) {
  7812. pageText.insertBefore(preBtn, pageText.firstChild);
  7813. pageText.insertBefore(nextBtn, pageText.firstChild);
  7814. }
  7815. if (curForceIframe) {
  7816. let bgRing = document.createElement("span");
  7817. bgRing.className = "refreshRing";
  7818. bgRing.style.display = "none";
  7819. bgRing.innerHTML = createHTML(upSvg);
  7820. pageText.title = "Refresh";
  7821. pageText.appendChild(bgRing);
  7822. pageText.addEventListener("click", e => {
  7823. e.stopPropagation();
  7824. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  7825. e.preventDefault();
  7826. let nextEle = pageBar && pageBar.nextElementSibling;
  7827. if (nextEle && nextEle.name == 'pagetual-iframe') {
  7828. if (curForceIframe == nextEle) {
  7829. nextEle.setAttribute("loaded", "refresh");
  7830. }
  7831. nextEle.src = nextEle.src;
  7832. }
  7833. });
  7834. } else if (rulesData.pageBarMenu) {
  7835. pageText.addEventListener("click", e => {
  7836. e.stopPropagation();
  7837. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  7838. e.preventDefault();
  7839. picker.start();
  7840. });
  7841. }
  7842. pageBar.appendChild(downSpan);
  7843. if (forceState == 2) {
  7844. pageBar.style.width = "99%";
  7845. } else {
  7846. let parentStyle = _unsafeWindow.getComputedStyle(example.parentNode);
  7847. let parentWidth = example.parentNode.offsetWidth || parseInt(parentStyle.width);
  7848. pageBar.style.width = parentWidth - parseInt(parentStyle.paddingLeft) - parseInt(parentStyle.paddingRight) - 10 + "px";
  7849. pageBar.style.margin = '10px 5px';
  7850. if (parentStyle.display == "grid" || parentStyle.display == "inline-grid") {
  7851. pageBar.style.gridColumn = "1/-1";
  7852. }
  7853. if (inTable) {
  7854. example = compareNodeName(example, ["tr", "tbody"]) ? example : example.nextElementSibling || example;
  7855. if (compareNodeName(example, ["tbody"])) example = example.querySelector("tr");
  7856. let nextTr = example;
  7857. while (nextTr && nextTr.children.length == 0) nextTr = nextTr.nextElementSibling;
  7858. if (nextTr) example = nextTr;
  7859. let tdNum = 0;
  7860. if (exampleStyle.display == "table-row") {
  7861. [].forEach.call(example.children, el => {
  7862. tdNum += el.colSpan || 1;
  7863. });
  7864. } else {
  7865. [].forEach.call(example.children, el => {
  7866. if (compareNodeName(el, ["td", "th"])) {
  7867. tdNum += el.colSpan || 1;
  7868. }
  7869. });
  7870. }
  7871. pageBar.style.cssText = "";
  7872. pageBar.style.display = "table-row";
  7873. pageBar.style.backgroundColor = "unset";
  7874. pageBar.style.lineHeight = "20px";
  7875. pageBar.style.boxShadow = "";
  7876. let td = document.createElement("td");
  7877. td.colSpan = tdNum || 1;
  7878. let inTd = document.createElement("div");
  7879. inTd.style.cssText = pageBarStyle;
  7880. inTd.style.display = "";
  7881. inTd.className = pageBar.className;
  7882. pageBar.className = "";
  7883. inTd.appendChild(upSpan);
  7884. inTd.appendChild(pageText);
  7885. if (pageNum) inTd.appendChild(pageNum);
  7886. inTd.appendChild(downSpan);
  7887. td.appendChild(inTd);
  7888. pageBar.appendChild(td);
  7889. } else if (inLi) {
  7890. example = compareNodeName(example, ["li"]) ? example : example.nextElementSibling || example;
  7891. pageBar.style.opacity = 1;
  7892. pageBar.style.display = getComputedStyle(example).display;
  7893. pageBar.style.backgroundColor = "unset";
  7894. pageBar.style.lineHeight = "20px";
  7895. pageBar.style.boxShadow = "";
  7896. pageBar.style.border = "";
  7897. pageBar.style.width = "";
  7898. pageBar.style.maxWidth = "unset";
  7899. pageBar.style.flex = "auto";
  7900. let inTd = document.createElement("div");
  7901. inTd.style.cssText = pageBarStyle;
  7902. inTd.style.display = "";
  7903. inTd.style.margin = "0"
  7904. inTd.style.padding = "0 0";
  7905. inTd.style.textAlign = "center";
  7906. inTd.style.minWidth = "150px";
  7907. inTd.style.width = 'calc(100% - 20px)';
  7908. inTd.className = pageBar.className;
  7909. pageBar.className = "";
  7910. inTd.appendChild(upSpan);
  7911. inTd.appendChild(pageText);
  7912. if (pageNum) inTd.appendChild(pageNum);
  7913. inTd.appendChild(downSpan);
  7914. if (pageBar.style.display === 'table-row') {
  7915. let td = document.createElement("td");
  7916. td.colSpan = example.children.length;
  7917. td.style.width = '100%';
  7918. td.appendChild(inTd);
  7919. pageBar.appendChild(td);
  7920. } else {
  7921. inTd.style.width = '100%';
  7922. pageBar.appendChild(inTd);
  7923. }
  7924. }
  7925. }
  7926.  
  7927. upSpan.addEventListener("click", e => {
  7928. getBody(document).scrollTop = 0;
  7929. document.documentElement.scrollTop = 0;
  7930. e.preventDefault();
  7931. e.stopPropagation();
  7932. });
  7933. downSpan.addEventListener("click", e => {
  7934. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  7935. changeStop(true);
  7936. }
  7937. pageBar.title = i18n(isPause ? "enable" : "disable");
  7938. scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7939. getBody(document).scrollTop = scrollH || 9999999;
  7940. document.documentElement.scrollTop = scrollH || 9999999;
  7941. e.preventDefault();
  7942. e.stopPropagation();
  7943. });
  7944. pageBar.addEventListener("click", e => {
  7945. changeStop(!isPause);
  7946. pageBar.title = i18n(isPause ? "enable" : "disable");
  7947. });
  7948. ruleParser.insertElement(pageBar);
  7949. ruleParser.runPageBar(pageBar);
  7950.  
  7951. return pageBar;
  7952. }
  7953.  
  7954. async function waitForElement(sel, doc) {
  7955. if (!sel) return null;
  7956. return new Promise((resolve) => {
  7957. let checkInv = setInterval(() => {
  7958. let result = getElement(sel, doc, null, true);
  7959. if (result) {
  7960. clearInterval(checkInv);
  7961. resolve(result);
  7962. }
  7963. }, 100);
  7964. });
  7965. }
  7966.  
  7967. async function clickAction(sel, doc) {
  7968. let btn = await waitForElement(sel, doc);
  7969. emuClick(btn, doc);
  7970. }
  7971.  
  7972. async function enterAction(sel, doc) {
  7973. let btn = await waitForElement(sel, doc);
  7974. let eventParam = { key: "Enter", keyCode: 13, bubbles: true };
  7975. let event = new KeyboardEvent('keydown', eventParam);
  7976. btn.dispatchEvent(event);
  7977. event = new KeyboardEvent('keyup', eventParam);
  7978. btn.dispatchEvent(event);
  7979. event = new KeyboardEvent('keypress', eventParam);
  7980. btn.dispatchEvent(event);
  7981. }
  7982.  
  7983. async function inputAction(sel, v, doc) {
  7984. let input = await waitForElement(sel, doc);
  7985. let event = new Event('focus', { bubbles: true });
  7986. input.dispatchEvent(event);
  7987. let lastValue = input.value;
  7988. if (input.nodeName.toUpperCase() == "INPUT") {
  7989. var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
  7990. nativeInputValueSetter.call(input, v);
  7991. } else if (input.nodeName.toUpperCase() == "TEXTAREA") {
  7992. var nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
  7993. nativeTextareaValueSetter.call(input, v);
  7994. } else {
  7995. input.innerHTML = createHTML(v);
  7996. }
  7997. event = new Event('input', { bubbles: true });
  7998. let tracker = input._valueTracker;
  7999. if (tracker) {
  8000. tracker.setValue(lastValue);
  8001. }
  8002. input.dispatchEvent(event);
  8003. event = new Event('change', { bubbles: true });
  8004. input.dispatchEvent(event);
  8005. debug(input, `input ${sel}`);
  8006. }
  8007.  
  8008. function emuClick(btn, doc) {
  8009. if (!doc) doc = document;
  8010. let curScroll = getBody(doc).scrollTop || doc.documentElement.scrollTop;
  8011. let orgHref = btn.getAttribute('href');
  8012. if (orgHref && orgHref.replace(location.origin + location.pathname, "").indexOf("#") === 0) {
  8013. let hashAction = e => {
  8014. e.preventDefault();
  8015. getBody(doc).scrollTop = curScroll;
  8016. doc.documentElement.scrollTop = curScroll;
  8017. btn.removeEventListener('click', hashAction, false);
  8018. };
  8019. btn.addEventListener('click', hashAction, false);
  8020. }
  8021. if (!PointerEvent) return btn.click();
  8022. let eventParam = {
  8023. isTrusted: true,
  8024. altKey: false,
  8025. azimuthAngle: 0,
  8026. bubbles: true,
  8027. button: 0,
  8028. buttons: 0,
  8029. clientX: 1,
  8030. clientY: 1,
  8031. cancelBubble: false,
  8032. cancelable: true,
  8033. composed: true,
  8034. ctrlKey: false,
  8035. defaultPrevented: false,
  8036. detail: 1,
  8037. eventPhase: 2,
  8038. fromElement: null,
  8039. height: 1,
  8040. isPrimary: false,
  8041. metaKey: false,
  8042. pointerId: 1,
  8043. pointerType: "mouse",
  8044. pressure: 0,
  8045. relatedTarget: null,
  8046. returnValue: true,
  8047. shiftKey: false,
  8048. toElement: null,
  8049. twist: 0,
  8050. which: 1
  8051. };
  8052. let mouseEvent = new PointerEvent("mousedown", eventParam);
  8053. btn.dispatchEvent(mouseEvent);
  8054. mouseEvent = new PointerEvent("mouseup", eventParam);
  8055. btn.dispatchEvent(mouseEvent);
  8056. let dispatchTouchEvent = (ele, type) => {
  8057. let touchEvent;
  8058. try {
  8059. touchEvent = document.createEvent('TouchEvent')
  8060. touchEvent.initTouchEvent(type, true, true)
  8061. } catch (err) {
  8062. try {
  8063. touchEvent = document.createEvent('UIEvent')
  8064. touchEvent.initUIEvent(type, true, true)
  8065. } catch (err) {
  8066. touchEvent = document.createEvent('Event')
  8067. touchEvent.initEvent(type, true, true)
  8068. }
  8069. }
  8070. if (touchEvent) {
  8071. try {
  8072. touchEvent.targetTouches = [{
  8073. pageX: 1,
  8074. pageY: 1,
  8075. clientX: 1,
  8076. clientY: 1,
  8077. target: btn
  8078. }];
  8079. touchEvent.touches = [{
  8080. pageX: 1,
  8081. pageY: 1,
  8082. clientX: 1,
  8083. clientY: 1,
  8084. target: btn
  8085. }];
  8086. touchEvent.changedTouches = [{
  8087. pageX: 1,
  8088. pageY: 1,
  8089. clientX: 1,
  8090. clientY: 1,
  8091. target: btn
  8092. }];
  8093. } catch (err) {}
  8094. ele.dispatchEvent(touchEvent);
  8095. }
  8096. }
  8097. dispatchTouchEvent(btn, "touchstart");
  8098. dispatchTouchEvent(btn, "touchend");
  8099.  
  8100. btn.click();
  8101. }
  8102.  
  8103. function emuInput(input, v) {
  8104. let result = false;
  8105. if (!input) return true;
  8106. let event = new Event('focus', { bubbles: true });
  8107. input.dispatchEvent(event);
  8108. let lastValue = input.value;
  8109. if (input.type == 'file') {
  8110. let file = v;
  8111. let blob = new Blob([file], {
  8112. type: 'text/plain'
  8113. });
  8114. file = new File([blob], 'noname.txt', { type: blob.type });
  8115. let dataTransfer = new DataTransfer();
  8116. dataTransfer.items.add(file);
  8117. input.files = dataTransfer.files;
  8118. v = "c:/fakepath/fakefile";
  8119. } else if (/INPUT/i.test(input.nodeName)) {
  8120. var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
  8121. nativeInputValueSetter.call(input, v);
  8122. } else if (/SELECT/i.test(input.nodeName)) {
  8123. var nativeSelectValueSetter = Object.getOwnPropertyDescriptor(window.HTMLSelectElement.prototype, "value").set;
  8124. nativeSelectValueSetter.call(input, v);
  8125. } else if (input.nodeName.toUpperCase() == "TEXTAREA") {
  8126. var nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
  8127. nativeTextareaValueSetter.call(input, v);
  8128. } else {
  8129. input.innerHTML = createHTML(v);
  8130. }
  8131. event = new Event('input', { bubbles: true });
  8132. let tracker = input._valueTracker;
  8133. if (tracker) {
  8134. tracker.setValue(lastValue);
  8135. }
  8136. input.dispatchEvent(event);
  8137. event = new Event('change', { bubbles: true });
  8138. input.dispatchEvent(event);
  8139. return result;
  8140. }
  8141.  
  8142. var failFromIframe = 0;
  8143. var inCors = false;
  8144. var checkRemoveIntv;
  8145. function requestFromIframe(url, callback){
  8146. if (location.protocol === 'https:' && !/^https:/.test(url)) {
  8147. ruleParser.noValidContent(url);
  8148. }
  8149. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  8150. let iframe = document.createElement('iframe');
  8151. iframe.name = 'pagetual-iframe';
  8152. iframe.width = '100%';
  8153. iframe.height = '1000';
  8154. iframe.frameBorder = '0';
  8155. if (ruleParser.curSiteRule.sandbox != false) {
  8156. iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  8157. }
  8158. 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;';
  8159. let waitTime = 100, checkEval;
  8160. ruleParser.runWait((_checkEval, _waitTime) => {
  8161. if (_checkEval) {
  8162. checkEval = _checkEval;
  8163. }
  8164. if (_waitTime) {
  8165. waitTime = _waitTime;
  8166. }
  8167. });
  8168. if (checkRemoveIntv) clearInterval(checkRemoveIntv);
  8169. checkRemoveIntv = setInterval(() => {
  8170. if (!iframe || !getBody(document).contains(iframe)) {
  8171. clearInterval(checkRemoveIntv);
  8172. loadPageOver();
  8173. }
  8174. }, 500);
  8175. let loadedHandler = async e => {
  8176. if (e.data != 'pagetual-iframe:DOMLoaded' && e.type != 'load') return;
  8177. clearInterval(checkRemoveIntv);
  8178. window.removeEventListener('message', loadedHandler, false);
  8179. iframe.removeEventListener('load', loadedHandler, false);
  8180. let pageEleTryTimes = 0;
  8181. async function checkIframe() {
  8182. if (urlChanged || isPause) {
  8183. return callback(false, false);
  8184. }
  8185. try {
  8186. let doc = iframe.contentDocument || iframe.contentWindow.document;
  8187. if (checkEval && !await checkEval(doc)) {
  8188. setTimeout(() => {
  8189. checkIframe();
  8190. }, waitTime);
  8191. return;
  8192. } else {
  8193. let base = doc.querySelector("base");
  8194. ruleParser.basePath = base ? base.href : url;
  8195. let eles = ruleParser.getPageElement(doc, iframe.contentWindow, pageEleTryTimes < 25);
  8196. if (eles && eles.length > 0) {
  8197. await ruleParser.hookUrl(doc);
  8198. await callback(doc, eles);
  8199. } else if (pageEleTryTimes++ < 100) {
  8200. getBody(doc).scrollTop = 9999999;
  8201. doc.documentElement.scrollTop = 9999999;
  8202. setTimeout(() => {
  8203. checkIframe();
  8204. }, waitTime);
  8205. return;
  8206. } else {
  8207. if (failFromIframe++ > 2) {
  8208. failFromIframe = 0;
  8209. debug("Stop as failFromIframe");
  8210. changeStop(true);
  8211. callback(false, false);
  8212. } else {
  8213. ruleParser.noValidContent(url);
  8214. callback(false, false);
  8215. }
  8216. }
  8217. }
  8218. } catch(e) {
  8219. inCors = true;
  8220. if (forceState === 3) {
  8221. debug("Stop as cors");
  8222. isPause = true;
  8223. }
  8224. if (!ruleParser.curSiteRule.pageElement) {
  8225. ruleParser.curSiteRule.pageElement = allOfBody;
  8226. ruleParser.getInsert(true);
  8227. }
  8228. ruleParser.curSiteRule.action = 0;
  8229. ruleParser.nextLinkHref = url;
  8230. callback(false, false);
  8231. nextPage();
  8232. }
  8233. if (iframe && iframe.parentNode) iframe.parentNode.removeChild(iframe);
  8234. }
  8235. setTimeout(() => {
  8236. checkIframe();
  8237. }, waitTime);
  8238. };
  8239. let code = ruleParser.curSiteRule.iframeInit;
  8240. if (code) {
  8241. let checkReady = setInterval(() => {
  8242. let doc;
  8243. try {
  8244. doc = iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document);
  8245. } catch(e) {
  8246. clearInterval(checkReady);
  8247. return;
  8248. }
  8249. if (doc) {
  8250. clearInterval(checkReady);
  8251. try {
  8252. Function('win', 'iframe', '"use strict";' + code)(iframe.contentWindow, iframe);
  8253. } catch(e) {
  8254. debug(e);
  8255. }
  8256. }
  8257. }, 50);
  8258. }
  8259. window.addEventListener('message', loadedHandler, false);
  8260. iframe.addEventListener('load', loadedHandler, false);
  8261. iframe.src = url;
  8262. try {
  8263. getBody(document).appendChild(iframe);
  8264. } catch (e) {
  8265. return callback(false, false);
  8266. }
  8267. }
  8268.  
  8269. var emuIframe, lastActiveUrl, orgContent, meetCors = false;
  8270. function emuPage(callback) {
  8271. let orgPage = null, preContent = null, iframeDoc, checkTimes = 0, loadmoreBtn, pageEle, nextLink, loadmoreEnd = false, waitTimes = 80, changed = false;
  8272. function returnFalse(log) {
  8273. if (curPage > 1) {
  8274. if (rulesData.lastPageTips) showTips(i18n("lastPage"), "", 800);
  8275. } else {
  8276. sideController.remove();
  8277. }
  8278. debug(log);
  8279. isPause = true;
  8280. callback(false, false);
  8281. if (emuIframe && emuIframe.parentNode) {
  8282. emuIframe.parentNode.removeChild(emuIframe);
  8283. emuIframe = null;
  8284. }
  8285. }
  8286. function cloneStatus() {
  8287. if (!iframeDoc) return;
  8288. let inputs = document.querySelectorAll("input:not([type=button],[type=image],[type=reset],[type=submit])");
  8289. let selectOptions = document.querySelectorAll("select>option");
  8290. [...inputs].forEach(input => {
  8291. let sel = geneSelector(input, true, true);
  8292. let mirrorEle = iframeDoc.querySelector(sel);
  8293. if (!mirrorEle) return;
  8294. emuInput(mirrorEle, input.value);
  8295. });
  8296. [...selectOptions].forEach(option => {
  8297. let sel = geneSelector(option, true, true);
  8298. let mirrorEle = iframeDoc.querySelector(sel);
  8299. if (!mirrorEle) return;
  8300. let selected = option.selected;
  8301. mirrorEle.selected = !!selected;
  8302. mirrorEle.parentNode.dispatchEvent(new Event('change'));
  8303. });
  8304. }
  8305. async function checkPage() {
  8306. if (isPause) return loadPageOver();
  8307. try {
  8308. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  8309. } catch(e) {
  8310. returnFalse("Stop as cors");
  8311. return;
  8312. }
  8313.  
  8314. let waitTime = 200, checkEval;
  8315. ruleParser.runWait((_checkEval, _waitTime) => {
  8316. if (_checkEval) {
  8317. checkEval = _checkEval;
  8318. }
  8319. if (_waitTime) {
  8320. waitTime = _waitTime;
  8321. }
  8322. });
  8323.  
  8324. if (!orgPage) {
  8325. if (!loadmoreEnd) {
  8326. loadmoreBtn = getLoadMore(iframeDoc);
  8327. if (loadmoreBtn && isVisible(loadmoreBtn, emuIframe.contentWindow)) {
  8328. emuClick(loadmoreBtn, iframeDoc);
  8329. let intv = setInterval(() => {
  8330. loadmoreBtn = getLoadMore(iframeDoc);
  8331. if (!loadmoreBtn || !getBody(document).contains(loadmoreBtn) || !isVisible(loadmoreBtn, emuIframe.contentWindow)) {
  8332. clearInterval(intv);
  8333. loadmoreEnd = true;
  8334. setTimeout(() => {
  8335. checkPage();
  8336. }, 500);
  8337. } else if (isInViewPort(loadmoreBtn)) {
  8338. emuClick(loadmoreBtn, iframeDoc);
  8339. }
  8340. }, 200);
  8341. return;
  8342. } else {
  8343. loadmoreEnd = true;
  8344. }
  8345. }
  8346. if (checkEval && !await checkEval(iframeDoc)) {
  8347. waitTimes = 50;
  8348. setTimeout(() => {
  8349. checkPage();
  8350. }, waitTime);
  8351. return;
  8352. } else {
  8353. if (!nextLink || !nextLink.offsetParent) nextLink = await ruleParser.getNextLink(iframeDoc, true);
  8354. if (nextLink) pageEle = ruleParser.getPageElement(iframeDoc, emuIframe.contentWindow, true);
  8355. if (!pageEle || pageEle.length == 0 || !nextLink) {
  8356. getBody(iframeDoc).scrollTop = 9999999;
  8357. iframeDoc.documentElement.scrollTop = 9999999;
  8358. if (waitTimes-- > 0) {
  8359. setTimeout(() => {
  8360. checkPage();
  8361. }, waitTime);
  8362. return;
  8363. }
  8364. }
  8365. }
  8366. if (!pageEle || pageEle.length == 0) {
  8367. returnFalse("Stop as no page when emu");
  8368. return;
  8369. }
  8370. pageEle = [].filter.call(pageEle, ele => {return ele && !compareNodeName(ele, ["style", "script", "meta"])});
  8371. if (compareNodeName(pageEle[0], ["ul"]) || pageEle.length == 1) pageEle = pageEle[0];
  8372. else if (pageEle[0].parentNode == pageEle[1].parentNode) {
  8373. pageEle = pageEle[0].parentNode;
  8374. } else {
  8375. pageEle = pageEle[0];
  8376. }
  8377. if (ruleParser.curSiteRule.smart && orgContent != pageEle.innerHTML) {
  8378. orgContent = pageEle.innerHTML;
  8379. if (waitTimes-- > 0) {
  8380. setTimeout(() => {
  8381. checkPage();
  8382. }, 500);
  8383. return;
  8384. }
  8385. }
  8386. orgPage = pageEle;
  8387. if (nextLink) {
  8388. if (compareNodeName(orgPage, ["img"])) {
  8389. if (!ruleParser.curSiteRule.lazyImgSrc) ruleParser.curSiteRule.lazyImgSrc = "0";
  8390. if (orgPage.src) {
  8391. orgContent = orgPage.src;
  8392. } else {
  8393. setTimeout(() => {
  8394. checkPage();
  8395. }, 500);
  8396. return;
  8397. }
  8398. } else {
  8399. orgContent = orgPage.innerHTML;
  8400. }
  8401. preContent = orgContent;
  8402. if (!isVisible(nextLink, emuIframe.contentWindow)) {
  8403. returnFalse("Stop as next hide when emu");
  8404. } else {
  8405. emuClick(nextLink, iframeDoc);
  8406. setTimeout(() => {
  8407. checkPage();
  8408. }, 500);
  8409. }
  8410. } else {
  8411. returnFalse("Stop as no next when emu");
  8412. }
  8413. return;
  8414. }
  8415. if (!ruleParser.checkStopSign(nextLink, iframeDoc)) {
  8416. return returnFalse("Stop as stopSign");
  8417. }
  8418. if (checkTimes++ > 200) {
  8419. returnFalse("Stop as timeout when emu");
  8420. return;
  8421. }
  8422. if (checkEval && !await checkEval(iframeDoc)) {
  8423. checkTimes = 0;
  8424. setTimeout(() => {
  8425. checkPage();
  8426. }, waitTime);
  8427. return;
  8428. }
  8429. let eles = ruleParser.getPageElement(iframeDoc, emuIframe.contentWindow, true), checkItem;
  8430. if (eles && eles.length > 0) {
  8431. eles = [].filter.call(eles, ele => {return ele && !compareNodeName(ele, ["style", "script", "meta"])});
  8432. if (compareNodeName(eles[0], ["ul"]) || eles.length == 1) checkItem = eles[0];
  8433. else if (eles[0].parentNode == eles[1].parentNode) {
  8434. checkItem = eles[0].parentNode;
  8435. } else {
  8436. checkItem = eles[0];
  8437. }
  8438. }
  8439. if (!checkItem) {
  8440. setTimeout(() => {
  8441. checkPage();
  8442. }, waitTime);
  8443. } else {
  8444. let checkInner;
  8445. if (compareNodeName(checkItem, ["img"])) {
  8446. if (checkItem.src) {
  8447. checkInner = checkItem.src;
  8448. } else {
  8449. setTimeout(() => {
  8450. checkPage();
  8451. }, waitTime);
  8452. return;
  8453. }
  8454. } else {
  8455. checkInner = checkItem.innerHTML;
  8456. }
  8457. if (orgPage != checkItem || checkInner != preContent) {
  8458. changed = true;
  8459. orgPage = checkItem;
  8460. preContent = checkInner;
  8461. setTimeout(() => {
  8462. checkPage();
  8463. }, 500);
  8464. } else if (changed) {
  8465. checkTimes = 0;
  8466. if (orgContent == preContent && (ruleParser.curSiteRule.smart || ruleParser.curSiteRule.stopSame)) {
  8467. returnFalse("Stop as same content");
  8468. } else {
  8469. orgContent = preContent;
  8470. await ruleParser.hookUrl(iframeDoc);
  8471. callback(iframeDoc, eles);
  8472. }
  8473. } else {
  8474. if (checkTimes % 10 === 5) {
  8475. if (!nextLink || !nextLink.offsetParent) {
  8476. nextLink = await ruleParser.getNextLink(iframeDoc, true);
  8477. }
  8478. if (nextLink) {
  8479. emuClick(nextLink, iframeDoc);
  8480. }
  8481. }
  8482. setTimeout(() => {
  8483. checkPage();
  8484. }, waitTime);
  8485. }
  8486. }
  8487. }
  8488. if (!emuIframe) {
  8489. let loaded = false;
  8490. emuIframe = document.createElement('iframe');
  8491. emuIframe.name = 'pagetual-iframe';
  8492. let notSetSandbox = typeof ruleParser.curSiteRule.sandbox == 'undefined';
  8493. if (notSetSandbox || ruleParser.curSiteRule.sandbox == true) {
  8494. emuIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  8495. } else if (ruleParser.curSiteRule.sandbox) {
  8496. emuIframe.sandbox = ruleParser.curSiteRule.sandbox;
  8497. }
  8498. emuIframe.width = '100%';
  8499. emuIframe.height = '100%';
  8500. emuIframe.frameBorder = '0';
  8501. 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;';
  8502. emuIframe.addEventListener("load", e => {
  8503. try {
  8504. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  8505. } catch(e) {
  8506. if (e.message && e.message.indexOf("cross-origin") != -1 && notSetSandbox && emuIframe.hasAttribute("sandbox")) {
  8507. emuIframe.removeAttribute("sandbox");
  8508. meetCors = true;
  8509. callback(false, false);
  8510. if (ruleParser.curSiteRule.smart) {
  8511. ruleParser.findNoNext();
  8512. }
  8513. } else {
  8514. returnFalse("Stop as cors");
  8515. }
  8516. return;
  8517. }
  8518. setTimeout(async () => {
  8519. if (meetCors && ruleParser.curSiteRule.smart) {
  8520. ruleParser.smartRules = ruleParser.smartRules.filter(item => {return item && item.url !== ruleParser.curSiteRule.url;});
  8521. storage.setItem("smartRules", ruleParser.smartRules);
  8522. }
  8523. meetCors = false;
  8524. let code = ruleParser.curSiteRule.init;
  8525. if (code) {
  8526. try {
  8527. 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)});
  8528. } catch(e) {
  8529. debug(e);
  8530. }
  8531. } else {
  8532. let refreshByClickSel = ruleParser.curSiteRule.refreshByClick;
  8533. if (iframeDoc && refreshByClickSel) {
  8534. let clickBtn = await waitForElement(refreshByClickSel, iframeDoc);
  8535. await sleep(500);
  8536. cloneStatus();
  8537. emuClick(clickBtn, iframeDoc);
  8538. await sleep(500);
  8539. }
  8540. }
  8541. if (loaded) return;
  8542. loaded = true;
  8543. checkPage();
  8544. }, 500);
  8545. });
  8546. let code = ruleParser.curSiteRule.iframeInit;
  8547. if (code) {
  8548. let checkReady = setInterval(() => {
  8549. try {
  8550. iframeDoc = emuIframe.contentDocument || (emuIframe.contentWindow && emuIframe.contentWindow.document);
  8551. } catch(e) {
  8552. clearInterval(checkReady);
  8553. return;
  8554. }
  8555. if (iframeDoc) {
  8556. clearInterval(checkReady);
  8557. try {
  8558. Function('win', 'iframe', '"use strict";' + code)(emuIframe.contentWindow, emuIframe);
  8559. } catch(e) {
  8560. debug(e);
  8561. }
  8562. }
  8563. }, 50);
  8564. }
  8565. if (!lastActiveUrl) lastActiveUrl = location.href;
  8566. emuIframe.src = lastActiveUrl;
  8567. getBody(document).appendChild(emuIframe);
  8568. } else {
  8569. if (emuIframe.src != lastActiveUrl || meetCors) {
  8570. emuIframe.src = lastActiveUrl;
  8571. return;
  8572. }
  8573. checkPage();
  8574. }
  8575. }
  8576.  
  8577. var scrollToResizeInited = false;
  8578. var resizePool = [];
  8579. var scrollingToResize = false;
  8580.  
  8581. function isTouchViewPort(element) {
  8582. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  8583. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  8584. const {
  8585. top,
  8586. right,
  8587. bottom,
  8588. left,
  8589. } = element.getBoundingClientRect();
  8590.  
  8591. return (
  8592. top < viewHeight &&
  8593. left < viewWidth &&
  8594. right > 0 &&
  8595. bottom > 0
  8596. );
  8597. }
  8598.  
  8599. function resizeIframe(iframe, frameDoc, pageEle) {
  8600. if (targetY >= 0) {
  8601. window.scrollTo({ top: targetY, behavior: 'instant'});
  8602. targetY = -1;
  8603. }
  8604. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  8605. if (ruleParser.curSiteRule.smart || forceState === 2) {
  8606. let height = (getBody(frameDoc).scrollHeight || getBody(frameDoc).offsetHeight || 500);
  8607. if (!iframe.style.height || parseInt(iframe.style.height) === 0 || height - parseInt(iframe.style.height) > window.innerHeight) {
  8608. iframe.style.height = height + "px";
  8609. iframe.style.minHeight = iframe.style.height;
  8610. }
  8611. iframe.style.width = "100%";
  8612. frameDoc.documentElement.scrollTop = 0;
  8613. frameDoc.documentElement.scrollLeft = 0;
  8614. } else {
  8615. if (pageEle) {
  8616. if (document.body.scrollWidth) frameDoc.documentElement.style.width = document.body.scrollWidth + "px";
  8617. let fitWidth = ruleParser.curSiteRule.fitWidth !== false;
  8618. let targetElement = pageEle[0];
  8619. if (!targetElement) return;
  8620. if (pageEle.length > 1) {
  8621. targetElement = targetElement.parentNode;
  8622. }
  8623. let scrollHeight = targetElement.scrollHeight || targetElement.offsetHeight || 500;
  8624. iframe.style.height = scrollHeight + "px";
  8625. let scrollTop = 0, scrollLeft = 0;
  8626. getBody(frameDoc).scrollTop = 0;
  8627. getBody(frameDoc).scrollLeft = 0;
  8628. while (targetElement && targetElement.offsetParent) {
  8629. targetElement.offsetParent.scrollTop = targetElement.offsetTop;
  8630. if (targetElement.offsetParent.scrollTop == 0) {
  8631. scrollTop += targetElement.offsetTop;
  8632. }
  8633. if (fitWidth) {
  8634. targetElement.offsetParent.scrollLeft = targetElement.offsetLeft;
  8635. if (targetElement.offsetParent.scrollLeft == 0) {
  8636. scrollLeft += targetElement.offsetLeft;
  8637. }
  8638. }
  8639. targetElement = targetElement.offsetParent;
  8640. }
  8641. frameDoc.documentElement.scrollTop = scrollTop;
  8642. frameDoc.documentElement.scrollLeft = scrollLeft;
  8643. if (frameDoc.documentElement.scrollTop == 0 && frameDoc.documentElement.scrollLeft == 0) {
  8644. getBody(frameDoc).scrollTop += scrollTop;
  8645. getBody(frameDoc).scrollLeft += scrollLeft;
  8646. }
  8647. if (!fitWidth && iframe.style.marginLeft == '0px') {
  8648. iframe.style.width = "100vw";
  8649. iframe.style.maxWidth = "100vw";
  8650. iframe.style.minWidth = "100vw";
  8651. var cWidth = document.body.clientWidth || document.documentElement.clientWidth;
  8652. var iWidth = window.innerWidth;
  8653. iframe.style.marginLeft = -iframe.getBoundingClientRect().left - (iWidth - cWidth) / 2 + "px";
  8654. }
  8655. }
  8656. }
  8657. let newScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  8658. if (newScroll != curScroll) {
  8659. getBody(document).scrollTop = curScroll;
  8660. document.documentElement.scrollTop = curScroll;
  8661. }
  8662. }
  8663.  
  8664. function scrollToResize(e) {
  8665. if (scrollingToResize) return;
  8666. else {
  8667. scrollingToResize = true;
  8668. let resizeHandler = () => {
  8669. let touched = 0;
  8670. for (let i = 0; i < resizePool.length; i++) {
  8671. let resizeArr = resizePool[i];
  8672. let iframe = resizeArr[1]();
  8673. if (isTouchViewPort(iframe)) {
  8674. touched++;
  8675. let pageEle = resizeArr[0]();
  8676. let frameDoc = resizeArr[2]();
  8677. resizeIframe(iframe, frameDoc, pageEle);
  8678. } else if (touched) {
  8679. if (touched == 1) {
  8680. let pageEle = resizeArr[0]();
  8681. let frameDoc = resizeArr[2]();
  8682. resizeIframe(iframe, frameDoc, pageEle);
  8683. }
  8684. break;
  8685. } else if (!iframe.parentNode) {
  8686. resizePool.splice(i, 1);
  8687. break;
  8688. }
  8689. }
  8690. };
  8691. setTimeout(() => {
  8692. scrollingToResize = false;
  8693. }, 300);
  8694. resizeHandler();
  8695. }
  8696. }
  8697.  
  8698. var curForceIframe;
  8699. function forceIframe(url, callback) {
  8700. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  8701. let curIframe = document.createElement('iframe'), iframeDoc, pageElement = null, inAction = true;
  8702. let loadedHandler = () => {
  8703. let getPageEle = () => {
  8704. if (ruleParser.curSiteRule.smart) {
  8705. return null;
  8706. } else {
  8707. if (!pageElement || pageElement.length === 0 || !pageElement[0].offsetParent) {
  8708. pageElement = ruleParser.getPageElement(iframeDoc, curIframe.contentWindow);
  8709. }
  8710. return pageElement;
  8711. }
  8712. };
  8713. resizeIframe(curIframe, iframeDoc, getPageEle());
  8714. let loaded = curIframe.getAttribute("loaded");
  8715. if (loaded == "true") {
  8716. return;
  8717. }
  8718. curIframe.setAttribute("loaded", "true");
  8719. let getIframe = () => {
  8720. return curIframe;
  8721. };
  8722. let getFrameDoc = () => {
  8723. return iframeDoc;
  8724. };
  8725. ruleParser.insertPage(iframeDoc, [], url, ele => {
  8726. callback(curIframe, loaded == "refresh");
  8727. inAction = false;
  8728. }, true);
  8729. if (!loaded) {
  8730. resizePool.push([getPageEle, getIframe, getFrameDoc]);
  8731. }
  8732. };
  8733. let checkIframeTimer = setInterval(() => {
  8734. if (!curIframe.parentNode) {
  8735. clearInterval(checkIframeTimer);
  8736. return curIframe.getAttribute("loaded") == "true" || callback(false);
  8737. }
  8738. }, 500);
  8739. let code = ruleParser.curSiteRule.iframeInit;
  8740. if (code) {
  8741. let checkReady = setInterval(() => {
  8742. try {
  8743. iframeDoc = curIframe.contentDocument || (curIframe.contentWindow && curIframe.contentWindow.document);
  8744. } catch(e) {
  8745. clearInterval(checkReady);
  8746. return;
  8747. }
  8748. if (iframeDoc) {
  8749. clearInterval(checkReady);
  8750. try {
  8751. Function('win', 'iframe', '"use strict";' + code)(curIframe.contentWindow, curIframe);
  8752. } catch(e) {
  8753. debug(e);
  8754. }
  8755. }
  8756. }, 50);
  8757. }
  8758. let waitTime = 300, checkEval;
  8759. ruleParser.runWait((_checkEval, _waitTime) => {
  8760. if (_checkEval) {
  8761. checkEval = _checkEval;
  8762. }
  8763. if (_waitTime) {
  8764. waitTime = _waitTime;
  8765. }
  8766. });
  8767. async function checkIframe() {
  8768. if (checkEval && !await checkEval(iframeDoc)) {
  8769. setTimeout(() => {
  8770. checkIframe();
  8771. }, waitTime);
  8772. return;
  8773. }
  8774. loadedHandler();
  8775. }
  8776. curIframe.name = 'pagetual-iframe';
  8777. curIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  8778. curIframe.frameBorder = '0';
  8779. curIframe.scrolling = "no";
  8780. 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;';
  8781. curIframe.addEventListener("load", async e => {
  8782. clearInterval(checkIframeTimer);
  8783. if (isPause) return callback(false);
  8784. try {
  8785. iframeDoc = curIframe.contentDocument || curIframe.contentWindow.document;
  8786. } catch(e) {
  8787. debug("Stop as cors");
  8788. isPause = true;
  8789. callback(false);
  8790. return;
  8791. }
  8792. let css = ruleParser.curSiteRule.css || rulesData.customCss;
  8793. if (css) {
  8794. let cssArr = css.split("inIframe:");
  8795. if (cssArr && cssArr.length > 1) {
  8796. let styleEle = iframeDoc.createElement("style");
  8797. styleEle.innerHTML = cssArr[1];
  8798. iframeDoc.head.appendChild(styleEle);
  8799. }
  8800. }
  8801. checkIframe();
  8802. iframeDoc.addEventListener('wheel', e => {
  8803. document.dispatchEvent(new Event('wheel'));
  8804. }, true);
  8805. });
  8806. let checkTimes = 0, findPageEle = false;
  8807. let forceRefresh = e => {
  8808. if (inAction || !iframeDoc) return;
  8809. inAction = true;
  8810. let foundNext = () => {
  8811. document.removeEventListener("scroll", forceRefresh);
  8812. }
  8813. setTimeout(async () => {
  8814. inAction = false;
  8815. if (!ruleParser.nextLinkHref && !isPause) {
  8816. checkTimes++;
  8817. await ruleParser.getNextLink(iframeDoc, true);
  8818. if (ruleParser.nextLinkHref) {
  8819. foundNext();
  8820. if (isLoading) isLoading = false;
  8821. } else if (checkTimes >= 10) {
  8822. foundNext();
  8823. } else if (checkTimes >= 3 && !findPageEle) {
  8824. if (!pageElement) pageElement = ruleParser.getPageElement(iframeDoc, curIframe.contentWindow);
  8825. if (!pageElement) {
  8826. inAction = true;
  8827. curIframe.contentWindow.location.reload();
  8828. } else {
  8829. findPageEle = true;
  8830. }
  8831. }
  8832. } else {
  8833. foundNext();
  8834. }
  8835. }, 100);
  8836. };
  8837. document.addEventListener("scroll", forceRefresh);
  8838. curIframe.src = url;
  8839. curForceIframe = curIframe;
  8840. let insert = ruleParser.getInsert();
  8841. let body = getBody(document);
  8842. let curScroll = body.scrollTop || document.documentElement.scrollTop;
  8843. if (forceState == 2) {
  8844. document.documentElement.appendChild(loadingDiv);
  8845. body.appendChild(curIframe);
  8846. let bodyStyle = getComputedStyle(body);
  8847. if (bodyStyle.display == "flex" || bodyStyle.display == "inline-flex") {
  8848. body.style.flexDirection = "column";
  8849. }
  8850. } else {
  8851. ruleParser.insertElement(curIframe);
  8852. }
  8853. body.scrollTop = curScroll;
  8854. document.documentElement.scrollTop = curScroll;
  8855.  
  8856. if (!scrollToResizeInited) {
  8857. scrollToResizeInited = true;
  8858. document.addEventListener("scroll", scrollToResize);
  8859. }
  8860. return curIframe;
  8861. }
  8862.  
  8863. function loadPageOver() {
  8864. isLoading = false;
  8865. stopScroll = true;
  8866. setTimeout(() => {stopScroll = false;}, 300);
  8867. if (loadingDiv.parentNode) {
  8868. loadingDiv.parentNode.removeChild(loadingDiv);
  8869. }
  8870. if (rate !== 1 && !clickMode) {
  8871. setTimeout(() => {
  8872. if (distToBottom() < bottomGap) {
  8873. nextPage();
  8874. }
  8875. }, 1);
  8876. }
  8877. }
  8878.  
  8879. function checkAutoLoadNum() {
  8880. if (autoLoadNum >= 0) {
  8881. if (autoLoadNum !== 0 && --autoLoadNum === 0) {
  8882. autoLoadNum = -1;
  8883. } else {
  8884. setTimeout(() => nextPage(), 1);
  8885. }
  8886. }
  8887. }
  8888.  
  8889. async function nextPage() {
  8890. if (isPause || isLoading || forceState === 1) return;
  8891. if (ruleParser.curSiteRule.delay) {
  8892. try {
  8893. let checkDelay = ((typeof ruleParser.curSiteRule.delay === 'function') ? ruleParser.curSiteRule.delay : Function('"use strict";' + ruleParser.curSiteRule.delay))();
  8894. if (!checkDelay) return;
  8895. } catch(e) {
  8896. debug(e);
  8897. }
  8898. }
  8899. let nextLink = ruleParser.nextLinkHref;
  8900. if (!nextLink) {
  8901. isLoading = true;
  8902. if (curPage === 1) {
  8903. await ruleParser.getNextLink(document, true);
  8904. nextLink = ruleParser.nextLinkHref;
  8905. }
  8906. if (!nextLink) {
  8907. if (curPage === 1) {
  8908. if (ruleParser.curSiteRule.pinUrl) {
  8909. setTimeout(() => {isLoading = false;}, 500);
  8910. } else if (tryTimes++ < 3) {
  8911. setTimeout(() => {isLoading = false;}, 1000);
  8912. } else {
  8913. ruleParser.findNoNext();
  8914. }
  8915. } else if (rulesData.lastPageTips && !showedLastPageTips) {
  8916. showTips(i18n("lastPage"), "", 800);
  8917. showedLastPageTips = true;
  8918. }
  8919. return;
  8920. }
  8921. isLoading = false;
  8922. }
  8923. showedLastPageTips = false;
  8924. let pvGallery = document.querySelector("span.pv-gallery-container");
  8925. if (pvGallery && pvGallery.style.display !== "none") return;
  8926. let insert = ruleParser.getInsert();
  8927. if (insert) {
  8928. if (curPage === 1) initView();
  8929. /*if (curPage == 1) {
  8930. window.postMessage({
  8931. command: 'pagetual.insert'
  8932. }, '*');
  8933. }*/
  8934. let isJs = ruleParser.curSiteRule.action == 3 || ruleParser.hrefIsJs(nextLink);
  8935. if (!isJs) {
  8936. emuIframe = null;
  8937. lastActiveUrl = nextLink;
  8938. if (location.protocol === "https:" && /^http:/.test(nextLink)) {
  8939. nextLink = nextLink.replace(/^http/, "https");
  8940. }
  8941. }
  8942. isLoading = true;
  8943. if (curPage !== 1 || !isJs || !ruleParser.curSiteRule.smart) {
  8944. ruleParser.beginLoading(loadingDiv);
  8945. }
  8946. let sleep = ruleParser.curSiteRule.sleep || 0;
  8947. setTimeout(() => {
  8948. if (ruleParser.curSiteRule.pageElementByJs) {
  8949. var over = eles => {
  8950. if (urlChanged || isPause) {
  8951. loadPageOver();
  8952. return;
  8953. }
  8954. if (eles) {
  8955. ruleParser.insertPage(document, eles, nextLink, () => {
  8956. createPageBar(nextLink);
  8957. checkAutoLoadNum();
  8958. }, true);
  8959. } else {
  8960. debug("Stop as no page when get by js");
  8961. isPause = true;
  8962. loadPageOver();
  8963. }
  8964. };
  8965. try {
  8966. ((typeof ruleParser.curSiteRule.pageElementByJs === 'function') ? ruleParser.curSiteRule.pageElementByJs : Function("over", "pageNum",'"use strict";' + ruleParser.curSiteRule.pageElementByJs))(over, curPage);
  8967. } catch(e) {
  8968. debug(e);
  8969. }
  8970. } else if ((forceState === 2 || ruleParser.curSiteRule.action == 2) && !isJs) {
  8971. forceIframe(nextLink, (iframe, refresh) => {
  8972. if (urlChanged || isPause) {
  8973. loadPageOver();
  8974. return;
  8975. }
  8976. if (!refresh) {
  8977. let pageBar = createPageBar(nextLink);
  8978. if (pageBar && iframe && iframe.parentNode) iframe.parentNode.insertBefore(pageBar, iframe);
  8979. }
  8980. loadPageOver();
  8981. checkAutoLoadNum();
  8982. });
  8983. } else if ((forceState === 3 || ruleParser.curSiteRule.action == 1) && !isJs) {
  8984. requestFromIframe(nextLink, async (doc, eles) => {
  8985. if (urlChanged || isPause) {
  8986. loadPageOver();
  8987. return;
  8988. }
  8989. if (eles) {
  8990. await ruleParser.insertPage(doc, eles, nextLink, () => {
  8991. createPageBar(nextLink);
  8992. checkAutoLoadNum();
  8993. }, true);
  8994. } else loadPageOver();
  8995. });
  8996. } else {
  8997. if (!isJs) {
  8998. requestDoc(nextLink, (eles) => {
  8999. if (urlChanged || isPause) {
  9000. loadPageOver();
  9001. return;
  9002. }
  9003. if (eles) {
  9004. createPageBar(nextLink);
  9005. checkAutoLoadNum();
  9006. } else loadPageOver();
  9007. });
  9008. } else {
  9009. emuPage((doc, eles) => {
  9010. if (urlChanged || isPause) {
  9011. loadPageOver();
  9012. return;
  9013. }
  9014. if (eles) {
  9015. ruleParser.insertPage(doc, eles, "", () => {
  9016. createPageBar(nextLink);
  9017. checkAutoLoadNum();
  9018. }, true);
  9019. } else loadPageOver();
  9020. });
  9021. }
  9022. }
  9023. }, sleep);
  9024. }
  9025. }
  9026.  
  9027. function init() {
  9028. if (document.readyState === 'loading' || document.readyState === 'uninitialized') {
  9029. let domReady = e => {
  9030. initRules(() => {
  9031. initPage();
  9032. });
  9033. document.removeEventListener("DOMContentLoaded", domReady, false);
  9034. };
  9035. document.addEventListener("DOMContentLoaded", domReady, false);
  9036. } else {
  9037. initRules(() => {
  9038. initPage();
  9039. });
  9040. }
  9041. }
  9042.  
  9043. function visibilitychangeHandler() {
  9044. document.removeEventListener('visibilitychange', visibilitychangeHandler);
  9045. init();
  9046. }
  9047.  
  9048. setTimeout(() => {
  9049. if (document.hidden) {
  9050. document.addEventListener('visibilitychange', visibilitychangeHandler);
  9051. } else {
  9052. init();
  9053. }
  9054. }, 300);
  9055. })();