东方永页机

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

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

  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.55
  14. // @description Perpetual pages - powerful auto-pager script. Auto fetching next paginated web pages and inserting into current page for infinite scroll. Support thousands of web sites without any rule.
  15. // @description:zh-CN 终极自动翻页 - 加载并拼接下一分页内容至当前页尾,智能适配任意网页
  16. // @description:zh-TW 終極自動翻頁 - 加載並拼接下一分頁內容至當前頁尾,智能適配任意網頁
  17. // @description:ja Webページを自動で読み込み継ぎ足し表示を行うブラウザ拡張です、次のページ付けされた Web ページの自動読み込みと現在のページへの挿入 ルールなしで何千もの Web サイトをサポートします。
  18. // @description:ko 페이지가 매겨진 다음 웹 페이지를 자동으로 로드하고 현재 페이지에 삽입합니다. 규칙 없이 수천 개의 웹 사이트를 지원합니다.
  19. // @description:ru Автоматическая подгрузка следующих страниц и вставка их содержимого в текущую страницу. Поддерживает тысячи сайтов даже с настройками по умолчанию.
  20. // @description:de Automatisches Laden der nächsten paginierten Webseiten und Einfügen in die aktuelle Seite. Unterstützen Sie Tausende von Websites ohne Regeln.
  21. // @description:es Carga automática de las siguientes páginas web paginadas e inserción en la página actual. Admite miles de sitios web sin ninguna regla.
  22. // @description:fr Chargement automatique des pages Web paginées suivantes et insertion dans la page en cours. Prend en charge des milliers de sites Web sans aucune règle.
  23. // @description:it Caricamento automatico delle pagine Web impaginate successive e inserimento nella pagina corrente. Supporta migliaia di siti web senza alcuna regola.
  24. // @author hoothin
  25. // @license MPL-2.0
  26. // @match *://*/*
  27. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAdVBMVEUAAAD3VU33VU32VEz8U073VU32VU33VU32VUz0Uk/3VE32VU32VUz2VU32VU32VU32VU33VU33U0z2VU34Wkv3VE32VUz/mpj/nJj2VUz2VU32VE33VEz2VU32VU32VUz3VE32VEz3VE3/mZf2Vkz2VU3/mpilFFolAAAAJXRSTlMA3Lp/GvTBT5YQLuawZ/DOyZwlPQeKc21N04+FX1bqpm9DNoB4T68ePwAAAitJREFUWMPt1tuasiAUBuCFCG5Rs3QybTPV1/1f4v/3PDkyIojn8x5qBrI+ltAfh32/yysmBKvyXb+njb6bDL9kzTd5SzjDAsYT8nFoGSxYe6BVqoNDp2jFDit25BRgVUAODB4YWcETWVTwVNGiGN5iWtBgg4YMCpsoI38dNunmmWyxUTvbPwwbsYR0fIzZLQ0pTG8eieRmBLMmpdH9uimQEf6TNRnXXKLZHixpJtywLzOgMHtFCqdM64DahHRnOE1dsrekm9wr2WtLcAlpdHwcp1pAJySXYnERclzp4+v19jXdmcTvQUJtz+ZaI4i05/V/UGYrCxbaAsOYoNfIKEQxpqQuzCgJJJ/3f42O8ywEZuMVWi/8hODxGj3GW2b0udkbGULLDOjimAG0S3fLGlBnXQM9irG1CiQdVQi0dqQsOSDlyEEz7Vy9OxxfR71VCXsSB23jMrKJYZXSjw57sqgLn5Z0wolsOCz0RyJkyeYjgz7pwwVq20eboZwtVUl2EnN5gJ50dQZFdryATvABRTr/tJXkUMdaAK5pwtCapwtFLskguwuyMh/Sd9WChQ4sIvIUYSk3PYqQvCQlOC04IfN7PkdjOyRKWhdKXMmiAFt9i3sJ5jxoRuR0vqAghxxwHuqfQE5OHGDKOrwEnqs1DgAZ2e4Eev1d45TN7JfhrQLKgfwMFYAsvp33dXII073aVQLI2gN5S58lfmGnKKFtah7nkgnBZB7zlP7Y/QNiTM6sYNzawwAAAABJRU5ErkJggg==
  28. // @grant GM_xmlhttpRequest
  29. // @grant GM_registerMenuCommand
  30. // @grant GM_notification
  31. // @grant GM_getValue
  32. // @grant GM_setValue
  33. // @grant GM_addStyle
  34. // @grant GM_openInTab
  35. // @grant GM_deleteValue
  36. // @grant GM_info
  37. // @grant GM_setClipboard
  38. // @grant GM.xmlHttpRequest
  39. // @grant GM.registerMenuCommand
  40. // @grant GM.notification
  41. // @grant GM.getValue
  42. // @grant GM.setValue
  43. // @grant GM.addStyle
  44. // @grant GM.openInTab
  45. // @grant GM.deleteValue
  46. // @grant GM.info
  47. // @grant GM.setClipboard
  48. // @supportURL https://github.com/hoothin/UserScripts/issues
  49. // @connect wedata.net
  50. // @connect githubusercontent.com
  51. // @connect ghproxy.com
  52. // @connect hoothin.github.io
  53. // @run-at document-idle
  54. // @connect *
  55. // @contributionURL https://ko-fi.com/hoothin
  56. // @contributionAmount 1
  57. // ==/UserScript==
  58.  
  59. (function() {
  60. 'use strict';
  61.  
  62. const pauseVideo = () => {
  63. setTimeout(() => {
  64. [].forEach.call(document.querySelectorAll("video"), video => {
  65. video.removeAttribute && video.removeAttribute("autoplay");
  66. video.pause && video.pause();
  67. });
  68. }, 1000);
  69. };
  70. if (window.name === 'pagetual-iframe' || (window.frameElement && window.frameElement.name === 'pagetual-iframe')) {
  71. [].forEach.call(document.querySelectorAll("iframe"), iframe => {
  72. iframe.name = 'pagetual-iframe';
  73. });
  74. var domloaded = function() {
  75. window.parent.postMessage('pagetual-iframe:DOMLoaded', '*');
  76. };
  77. if (window.opera) {
  78. document.addEventListener('DOMContentLoaded', domloaded, false);
  79. pauseVideo();
  80. } else {
  81. domloaded();
  82. if (document.readystate === 'complete') {
  83. pauseVideo();
  84. } else {
  85. window.addEventListener('load', () => {
  86. pauseVideo();
  87. }, false);
  88. }
  89. }
  90. if (getComputedStyle(document.documentElement).display === 'none') {
  91. document.documentElement.style.display = 'block';
  92. }
  93. if (document.body && getComputedStyle(document.body).display === 'none') {
  94. document.body.style.display = 'block';
  95. }
  96. return;
  97. }
  98.  
  99. if (window.top !== window.self) {
  100. try {
  101. if (window.self.innerWidth < 300 || window.self.innerHeight < 300) {
  102. return;
  103. }
  104. } catch(e) {
  105. return;
  106. }
  107. }
  108.  
  109. const noRuleTest = false;
  110. const lang = navigator.appName === "Netscape" ? navigator.language : navigator.userLanguage;
  111. const langData = [
  112. {
  113. name: "English",
  114. match: ["en"],
  115. lang: {
  116. enableDebug: "Enable debug output",
  117. updateNotification: "Notification after rules updated",
  118. disable: "Disable",
  119. disableSite: "Toggle disabled state",
  120. disableSiteTips: "Disabled on this site",
  121. enableSiteTips: "Enabled on this site",
  122. enable: "Enable",
  123. toTop: "To Top",
  124. toBottom: "To Bottom",
  125. current: "Current Page",
  126. forceIframe: "Force to join next page",
  127. cancelForceIframe: "Cancel Force join",
  128. configure: "Configure",
  129. firstUpdate: "Click here to initialize the rules",
  130. update: "Update online rules",
  131. click2update: "Click to update rules from url now",
  132. loadNow: "Load next automatically",
  133. loadConfirm: "How much pages do you want to load? (0 means infinite)",
  134. noNext: "No next link found, please create a new rule",
  135. passSec: "Updated #t# seconds ago",
  136. passMin: "Updated #t# minutes ago",
  137. passHour: "Updated #t# hours ago",
  138. passDay: "Updated #t# days ago",
  139. cantDel: "Can't delete buildin rules",
  140. confirmDel: "Are you sure you want to delete this rule?",
  141. updateSucc: "Update succeeded",
  142. beginUpdate: "Begin update, wait a minute please",
  143. customUrls: "Import Pagetual or AutoPagerize rule url, One url per line",
  144. customRules: "Input custom rules. <a href='#t#'>✍️Contribute rules</a>",
  145. save: "Save",
  146. loadingText: "Shojo Now Loading...",
  147. opacity: "Opacity",
  148. opacityPlaceholder: "0: hide spacer",
  149. hideBar: "Hide the paging spacer",
  150. hideBarButNoStop: "Hide but not stop",
  151. dbClick2Stop: "Double-click on the blank space to pause",
  152. sortTitle: "Sorting takes effect after the next rule update",
  153. autoRun: "Auto enable (blacklist mode)",
  154. autoLoadNum: "Amount for preload pages",
  155. turnRate: "Turn the next page when it's less than 【X】 times page height from the footer",
  156. inputPageNum: "Enter page number to jump",
  157. enableHistory: "Write browsing history after page turning",
  158. enableHistoryAfterInsert: "Write browsing history immediately after splicing, otherwise write after browsing",
  159. contentVisibility: "Automatically switch contentVisibility to improve rendering performance",
  160. initRun: "Turn pages immediately after opening",
  161. preload: "Preload next page for speeding up",
  162. click2ImportRule: "Click to import base rules link, then wait until the update is complete: ",
  163. forceAllBody: "Join full body of page?",
  164. openInNewTab: "Open urls of additions in new tab",
  165. importSucc: "Import completed",
  166. import: "Import",
  167. editCurrent: "Edit rule for current",
  168. editBlacklist: "Edit the blacklist urls, line by line, Support ? * for wildcard",
  169. upBtnImg: "Icon of back to top",
  170. downBtnImg: "Icon of go to footer",
  171. sideControllerIcon: "Icon of sidebar",
  172. loadingTextTitle: "Loading text",
  173. dbClick2StopCtrl: "Ctrl key",
  174. dbClick2StopAlt: "Alt key",
  175. dbClick2StopShift: "Shift key",
  176. dbClick2StopMeta: "Meta key",
  177. dbClick2StopKey: "Shortcut key",
  178. pageElementCss: "Custom style for main page elements",
  179. customCss: "Custom complete css",
  180. firstAlert: "You have not imported the base rule, please select the appropriate rule to import",
  181. picker: "Pagetual page element picker",
  182. closePicker: "Close Pagetual picker",
  183. pickerPlaceholder: "Element selector, Leave empty if you have no idea",
  184. pickerCheck: "Check selector and copy",
  185. switchSelector: "Click to switch element",
  186. gotoEdit: "Go to edit rule with current selector",
  187. manualMode: "Disable splicing, manually turn pages with the right arrow keys (or dispatch event 'pagetual.next')",
  188. clickMode: "Disable splicing, automatically click the next page when scrolling to the end of the page",
  189. pageBarMenu: "Click the center of the page bar to open the picker menu",
  190. nextSwitch: "Switch next link",
  191. arrowToScroll: "Press left arrow key to scroll prev and right arrow key to scroll next",
  192. sideController: "Display the paging control bar in the sidebar",
  193. sideControllerScroll: "Scroll toggle",
  194. sideControllerAlways: "Always show",
  195. hideLoadingIcon: "Hide loading animation",
  196. hideBarArrow: "Hide arrow for page bar",
  197. duplicate: "Duplicate Pagetual have been installed, check your script manager!",
  198. forceStateIframe: "Embed full page as iframe",
  199. forceStateDynamic: "Load dynamic content via iframe",
  200. forceStateDisable: "Disable page turning on this site",
  201. autoScrollRate: "Scroll speed (1~1000)",
  202. disableAutoScroll: "Stop Auto Scroll",
  203. enableAutoScroll: "Enable Auto Scroll",
  204. toggleAutoScroll: "Toggle Auto Scroll",
  205. ruleRequest: "Rule Request",
  206. page: "Page ",
  207. prevPage: "Prev page",
  208. nextPage: "Next page",
  209. errorRulesMustBeArray: "Rules must be a Array!",
  210. errorJson: "JSON error, check again!",
  211. editSuccess: "Edit successfully",
  212. errorWrongUrl: "Wrong url, check again!",
  213. errorAlreadyExists: "Already exists!",
  214. settingsSaved: "The settings are saved, refresh to view",
  215. iframe: "Iframe",
  216. dynamic: "Dynamic",
  217. reloadPage: "Edit completed, reload page now?",
  218. copied: "Copied",
  219. noValidContent: "No valid content detected, Captcha action may be required, click to view",
  220. outOfDate: "The script is outdated, update to the latest version in time!",
  221. hideBarTips: "Hide the pagination bar, toggle immersive experience",
  222. setConfigPage: "Set current page as the default configuration page",
  223. wedata2github: "Change the wedata address to the mirror address in the github repository",
  224. addOtherProp: "Add rule property",
  225. addNextSelector: "Add selector content as nextLink",
  226. addPageSelector: "Add selector content as pageElement",
  227. propName: "Enter rule property name",
  228. propValue: "Enter rule property value",
  229. customFirst: "Ignore cache for local custom rules",
  230. rulesExample: "Rules Example",
  231. lastPage: "Reached the last page",
  232. lastPageTips: "Show tips when reaching the last page"
  233. }
  234. },
  235. {
  236. //Translated by Prankster 199 (vfggf95565).
  237. name: "Arabic",
  238. match: ["ar", "ar-AE", "ar-BH", "ar-DZ", "ar-EG", "ar-IQ", "ar-JO", "ar-KW", "ar-LB", "ar-LY", "ar-MA", "ar-OM", "ar-QA", "ar-SA", "ar-SY", "ar-TN", "ar-YE"],
  239. lang: {
  240. enableDebug: "تمكين تصحيح الأخطاء",
  241. updateNotification: "إشعار بعد تحديث القواعد",
  242. disable: "معطل",
  243. disableSite: "تبديل حالة التعطيل/التفعيل للموقع",
  244. disableSiteTips: "معطل على هذا الموقع",
  245. enableSiteTips: "مفعل على هذا الموقع",
  246. enable: "مفعل",
  247. toTop: "إلى الأعلى",
  248. toBottom: "إلى الأسفل",
  249. current: "الصفحة الحالية",
  250. forceIframe: "إجبار على الانضمام للصفحة التالية",
  251. cancelForceIframe: "إلغاء الانضمام القسري",
  252. configure: "إعداد",
  253. firstUpdate: "انقر هنا لتفعيل القواعد لأول مرة",
  254. update: "تحديث القواعد عبر الإنترنت",
  255. click2update: "انقر لتحديث القواعد من الرابط الآن",
  256. loadNow: "تحميل التالي تلقائيًا",
  257. loadConfirm: "كم عدد الصفحات التي ترغب تحميلها؟ (0 يعني لانهائي)",
  258. noNext: "لم يتم العثور على رابط الصفحة التالية، يرجى إنشاء قاعدة جديدة",
  259. passSec: "تم التحديث منذ #t# ثانية",
  260. passMin: "تم التحديث منذ #t# دقيقة",
  261. passHour: "تم التحديث منذ #t# ساعة",
  262. passDay: "تم التحديث منذ #t# يوم",
  263. cantDel: "لا يمكن حذف القواعد المدمجة",
  264. confirmDel: "هل أنت متأكد من حذف هذه القاعدة؟",
  265. updateSucc: "تم التحديث بنجاح",
  266. beginUpdate: "بدأ التحديث، يرجى الانتظار لحظة",
  267. customUrls: "استيراد رابط قاعدة Pagetual أو AutoPagerize، رابط واحد لكل سطر",
  268. customRules: "إدخال القواعد المخصصة. <a href='#t#'>✍️ساهم بالقواعد</a>",
  269. save: "حفظ",
  270. /* From the creator hoothin :
  271. "Shojo Now Loading..." is a meme that refers to the game loading text in the Japanese Touhou (東方) game series. */
  272. loadingText: "جارٍ التحميل...",
  273. opacity: "الشفافية",
  274. opacityPlaceholder: "0: إخفاء الفاصل",
  275. hideBar: "إخفاء الفاصل التصفحي",
  276. hideBarButNoStop: "إخفاء، لكن لا تتوقف",
  277. dbClick2Stop: "انقر مزدوج على المساحة الفارغة للإيقاف",
  278. sortTitle: "يتم تفعيل الفرز بعد التحديث التالي للقواعد",
  279. autoRun: "تمكين تلقائي (وضع القائمة السوداء)",
  280. autoLoadNum: "عدد صفحات التحميل المسبق",
  281. turnRate: "الانتقال للصفحة التالية عندما تكون المسافة أقل من 【X】 مرات ارتفاع الصفحة من التذييل",
  282. inputPageNum: "أدخل رقم الصفحة للانتقال",
  283. enableHistory: "كتابة سجل التصفح بعد تحويل الصفحة",
  284. enableHistoryAfterInsert: "كتابة سجل التصفح فورًا بعد الدمج، أو بعد التصفح",
  285. contentVisibility: "التنقل التلقائي لرؤية المحتوى, لتحسين أداء العرض",
  286. initRun: "الانتقال بين الصفحات فور الفتح",
  287. preload: "تحميل الصفحة التالية مسبقًا لتسريع الأداء",
  288. click2ImportRule: "انقر لاستيراد رابط القواعد الأساسية، ثم انتظر حتى يكتمل التحديث",
  289. forceAllBody: "دمج كامل الصفحة كإطار؟",
  290. openInNewTab: "فتح الروابط الإضافية في علامة تبويب جديدة",
  291. importSucc: "تم الاستيراد بنجاح",
  292. import: "استيراد",
  293. editCurrent: "تحرير القاعدة للحالية",
  294. editBlacklist: "تحرير عناوين القائمة السوداء، سطر بسطر، دعم؟ * للرموز المتحركة",
  295. upBtnImg: "أيقونة العودة إلى الأعلى",
  296. downBtnImg: "أيقونة الانتقال إلى الأسفل",
  297. sideControllerIcon: "أيقونة الشريط الجانبي",
  298. loadingTextTitle: "تحميل النص",
  299. dbClick2StopCtrl: "مفتاح Ctrl",
  300. dbClick2StopAlt: "مفتاح Alt",
  301. dbClick2StopShift: "مفتاح Shift",
  302. dbClick2StopMeta: "مفتاح Meta",
  303. dbClick2StopKey: "مفاتيح الاختصار",
  304. pageElementCss: "نمط مخصص لعناصر الصفحة الرئيسية",
  305. customCss: "مخصص بالكامل CSS نمط",
  306. firstAlert: "لم تستورد القاعدة الأساسية بعد، يرجى اختيار القاعدة المناسبة للاستيراد",
  307. picker: "محدد عناصر الصفحة Pagetual",
  308. closePicker: "إغلاق محدد Pagetual",
  309. pickerPlaceholder: "محدد العناصر، اتركه فارغًا إذا كنت لا تعرف",
  310. pickerCheck: "تحقق من المحدد ونسخ",
  311. switchSelector: "انقر للتبديل بين العناصر",
  312. gotoEdit: "اذهب لتحرير القاعدة بالمحدد الحالي",
  313. manualMode: "تعطيل الدمج/الربط، واستخدام مفتاح الاتجاه الأيمن يدويًا للتمرير، واستخدام مفتاح السهم الأيسر للرجوع",
  314. clickMode: "تعطيل الدمج/الربط، عند التمرير إلى نهاية الصفحة، سيتم النقر تلقائيًا على الصفحة التالية",
  315. pageBarMenu: "انقر على مركز شريط الصفحة لفتح قائمة التحديد",
  316. nextSwitch: "تبديل الرابط التالي",
  317. arrowToScroll: "انقر على مفتاح السهم الأيمن للتمرير التالي ومفتاح السهم الأيسر للتمرير السابق",
  318. sideController: "عرض شريط التحكم في التصفح الترقيم في الشريط الجانبي",
  319. sideControllerScroll: "تبديل التمرير",
  320. sideControllerAlways: "عرض دائمًا",
  321. hideLoadingIcon: "إخفاء رمز التحميل",
  322. hideBarArrow: "إخفاء سهم شريط الصفحة",
  323. duplicate: "تم تثبيت Pagetual مكرر، تحقق من مدير النصوص البرمجية الخاص بك!",
  324. forceStateIframe: "تضمين الصفحة بالكامل كإطار",
  325. forceStateDynamic: "تحميل المحتوى الديناميكي عبر الإطار",
  326. forceStateDisable: "تعطيل تحويل الصفحات على هذا الموقع",
  327. autoScrollRate: "سرعة التمرير (1~1000)",
  328. disableAutoScroll: "إيقاف التمرير التلقائي",
  329. enableAutoScroll: "تمكين التمرير التلقائي",
  330. toggleAutoScroll: "تبديل التمرير التلقائي",
  331. ruleRequest: "طلب قاعدة",
  332. page: "صفحة ",
  333. prevPage: "الصفحة السابقة",
  334. nextPage: "الصفحة التالية",
  335. errorRulesMustBeArray: "يجب أن تكون القواعد مصفوفة!",
  336. errorJson: "خطأ في JSON، تحقق مرة أخرى!",
  337. editSuccess: "تم التحرير بنجاح",
  338. errorWrongUrl: "عنوان URL خاطئ، تحقق مرة أخرى!",
  339. errorAlreadyExists: "موجود بالفعل!",
  340. settingsSaved: "تم حفظ الإعدادات، قم بالتحديث لعرض",
  341. iframe: "إطار",
  342. dynamic: "ديناميكي",
  343. reloadPage: "اكتمل التحرير، إعادة تحميل الصفحة الآن؟",
  344. copied: "تم النسخ",
  345. noValidContent: "لم يتم الكشف عن محتوى صالح، قد يكون الإجراء Captcha مطلوبًا، انقر لعرض",
  346. outOfDate: "النص البرمجي قديم، قم بالتحديث إلى الإصدار الأحدث في الوقت المناسب!",
  347. hideBarTips: "إخفاء شريط التحكم في التصفح الترقيم ، والتبديل لوضع كامل الصفحة",
  348. setConfigPage: "تعيين الصفحة الحالية كصفحة الإعداد الافتراضية",
  349. wedata2github: "تغيير عنوان الويب داتا إلى العنوان البديل المرآة, في مستودع جيت هاب",
  350. addOtherProp: "إضافة خاصية قاعدة",
  351. addNextSelector: "إضافة محتوى المحدد كـ nextLink",
  352. addPageSelector: "إضافة محتوى المحدد كـ pageElement",
  353. propName: "أدخل اسم خاصية القاعدة",
  354. propValue: "أدخل قيمة خاصية القاعدة",
  355. customFirst: "تجاهل ذاكرة التخزين المؤقت للقواعد المخصصة المحلية",
  356. rulesExample: "مثال على القواعد",
  357. lastPage: "تم الوصول إلى الصفحة الأخيرة",
  358. lastPageTips: "عرض تلميحات عند الوصول إلى الصفحة الأخيرة"
  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", "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. if (doc && doc.ownerDocument) doc = doc.ownerDocument;
  1055. doc = (doc && doc.evaluate) ? doc : document;
  1056. contextNode = contextNode || doc;
  1057. try {
  1058. let result = doc.evaluate(xpath, contextNode, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  1059. return result.singleNodeValue && result.singleNodeValue.nodeType === 1 && result.singleNodeValue;
  1060. } catch (err) {
  1061. debug(`Invalid xpath: ${xpath}`);
  1062. }
  1063. return null;
  1064. }
  1065.  
  1066. function getAllElementsByXpath(xpath, contextNode, doc) {
  1067. if (doc && doc.ownerDocument) doc = doc.ownerDocument;
  1068. doc = (doc && doc.evaluate) ? doc : document;
  1069. contextNode = contextNode || doc;
  1070. var result = [];
  1071. try {
  1072. var query = doc.evaluate(xpath, contextNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  1073. for (var i = 0; i < query.snapshotLength; i++) {
  1074. var node = query.snapshotItem(i);
  1075. if (node.nodeType === 1) {
  1076. result.push(node);
  1077. }
  1078. }
  1079. } catch (err) {
  1080. debug(`Invalid xpath: ${xpath}`);
  1081. }
  1082. return result;
  1083. }
  1084.  
  1085. function isXPath(xpath) {
  1086. if (!xpath) {
  1087. return false;
  1088. }
  1089. return /^\(*(descendant::|\.\/|\/|id\()/.test(xpath);
  1090. }
  1091.  
  1092. function getAllElements(sel, doc, contextNode) {
  1093. try {
  1094. if (!isXPath(sel)) {
  1095. return doc.querySelectorAll(sel);
  1096. }
  1097. } catch(e) {
  1098. debug(e, 'Error selector');
  1099. }
  1100. return getAllElementsByXpath(sel, contextNode, doc);
  1101. }
  1102.  
  1103. function getElement(sel, doc, contextNode, bySort) {
  1104. try {
  1105. if (!isXPath(sel)) {
  1106. if (!bySort) {
  1107. return doc.querySelector(sel);
  1108. } else {
  1109. let selArr = sel.split(",");
  1110. try {
  1111. for (let i = 0; i < selArr.length; i++) {
  1112. let ele = doc.querySelector(selArr[i].trim());
  1113. if (ele) {
  1114. return ele;
  1115. }
  1116. }
  1117. } catch(e) {
  1118. return doc.querySelector(sel);
  1119. }
  1120. return null;
  1121. }
  1122. }
  1123. } catch(e) {
  1124. debug(e, 'Error selector');
  1125. }
  1126. return getElementByXpath(sel, doc, contextNode);
  1127. }
  1128.  
  1129. function compareNodeName(node, names) {
  1130. if (!node || !node.nodeName || !node.nodeName.toLowerCase) {
  1131. return false;
  1132. }
  1133. let nodeName = node.nodeName.toLowerCase();
  1134. for (let i = 0; i < names.length; i++) {
  1135. if (names[i] === nodeName) {
  1136. return true;
  1137. }
  1138. }
  1139. return false;
  1140. }
  1141.  
  1142. function geneSelector(ele, addID, exact) {
  1143. let selector = ele.nodeName.toLowerCase();
  1144. //Google id class都是隨機。百度更過分,style script順序都是隨機的
  1145. if (selector !== "html" && selector !== "body") {
  1146. let hasId = false;
  1147. if (addID && ele.id && /^[a-z_][\w\-_]*$/i.test(ele.id)) {
  1148. if (ele.ownerDocument && ele.ownerDocument.querySelectorAll("#" + ele.id).length === 1) {
  1149. hasId = true;
  1150. selector = '#' + ele.id;
  1151. }
  1152. }
  1153. if (!hasId) {
  1154. let className = "";
  1155. if (ele.className) {
  1156. let classList = ele.classList;
  1157. for (let i = 0; i < classList.length; i++) {
  1158. let c = classList[i];
  1159. if (/^[\w\-_]+$/.test(c) && !/\d{4,}/.test(c)) {
  1160. className += '.' + c;
  1161. }
  1162. }
  1163. selector += className;
  1164. }
  1165. let parent = ele.parentElement;
  1166. if (parent) {
  1167. if (exact) {
  1168. let i, nth = 0, all = 0;
  1169. for (i = 0; i < parent.children.length; i++) {
  1170. if (parent.children[i].nodeName === ele.nodeName) {
  1171. all++;
  1172. if (parent.children[i] === ele) {
  1173. nth = all;
  1174. }
  1175. if (nth > 0 && all > 1) {
  1176. break;
  1177. }
  1178. }
  1179. }
  1180. selector += (all === 1 ? "" : `:nth-of-type(${nth})`);
  1181. } else if (!className && !hasId && parent.children.length > 1 && !compareNodeName(parent, ["html"])) {
  1182. let prevE = ele.previousElementSibling;
  1183. if (prevE && prevE.className) {
  1184. let classList = prevE.classList;
  1185. for (let i = 0; i < classList.length; i++) {
  1186. let c = classList[i];
  1187. if (/^[\w\-_]+$/.test(c) && !/\d{4,}/.test(c)) {
  1188. className += '.' + c;
  1189. }
  1190. }
  1191. if (className) {
  1192. selector = prevE.nodeName.toLowerCase() + className + "+" + selector;
  1193. }
  1194. }
  1195. if (!className) {
  1196. let i, nth = 0, all = 0;
  1197. for (i = 0; i < parent.children.length; i++) {
  1198. if (parent.children[i].nodeName === ele.nodeName) {
  1199. all++;
  1200. if (parent.children[i] === ele) {
  1201. nth = all;
  1202. }
  1203. if (nth > 0 && all > 1) {
  1204. break;
  1205. }
  1206. }
  1207. }
  1208. selector += (all === 1 ? "" : `:nth-of-type(${nth})`);
  1209. }
  1210. }
  1211. selector = geneSelector(parent, addID, exact) + ' > ' + selector;
  1212. }
  1213. }
  1214. }
  1215. return selector;
  1216. }
  1217.  
  1218. function createXPathFromElement(elm) {
  1219. let allNodes = document.getElementsByTagName('*'), segs;
  1220. for (segs = []; elm && elm.nodeType === 1; elm = elm.parentNode) {
  1221. if (compareNodeName(elm, ["body", "html"])) {
  1222. segs.unshift(elm.localName.toLowerCase());
  1223. continue;
  1224. }
  1225. if (elm.hasAttribute && elm.hasAttribute('id')) {
  1226. var uniqueIdCount = 0;
  1227. for (var n = 0; n < allNodes.length; n++) {
  1228. if (allNodes[n].hasAttribute('id') && allNodes[n].id === elm.id) {
  1229. uniqueIdCount++;
  1230. }
  1231. if (uniqueIdCount > 1) {
  1232. break;
  1233. }
  1234. }
  1235. if ( uniqueIdCount === 1) {
  1236. segs.unshift('id("' + elm.getAttribute('id') + '")');
  1237. return segs.join('/');
  1238. } else {
  1239. segs.unshift(elm.localName.toLowerCase() + '[@id="' + elm.getAttribute('id') + '"]');
  1240. }
  1241. } else if (elm.hasAttribute && elm.hasAttribute('class')) {
  1242. segs.unshift(elm.localName.toLowerCase() + '[@class="' + elm.getAttribute('class') + '"]');
  1243. } else {
  1244. let i, sib;
  1245. for (i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling) {
  1246. if (sib.localName === elm.localName) {
  1247. i++;
  1248. }
  1249. }
  1250. segs.unshift(elm.localName.toLowerCase() + '[' + i + ']');
  1251. }
  1252. }
  1253. return segs.length ? '/' + segs.join('/') : null;
  1254. }
  1255.  
  1256. const escapeHTMLPolicy = (_unsafeWindow.trustedTypes && _unsafeWindow.trustedTypes.createPolicy) ? _unsafeWindow.trustedTypes.createPolicy('pagetual_default', {
  1257. createHTML: (string, sink) => string
  1258. }) : null;
  1259.  
  1260. function createHTML(html) {
  1261. return escapeHTMLPolicy ? escapeHTMLPolicy.createHTML(html) : html;
  1262. }
  1263.  
  1264. const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
  1265.  
  1266. async function sleep(time) {
  1267. await new Promise((resolve) => {
  1268. setTimeout(() => {
  1269. resolve();
  1270. }, time);
  1271. });
  1272. }
  1273.  
  1274. class RuleParser {
  1275. constructor() {
  1276. this.hpRules = [];
  1277. this.smartRules = [];
  1278. this.customRules = [];
  1279. this.rules = [];
  1280. this.pageDoc = document;
  1281. this.nextLinkHref = null;
  1282. this.nextTitle = "";
  1283. this.oldUrl = "";
  1284. this.curUrl = location.href;
  1285. this.curSiteRule = {};
  1286. }
  1287.  
  1288. async initSavedRules(callback) {
  1289. var self = this;
  1290. let smartRules = await getData("smartRules");
  1291. if (smartRules) self.smartRules = smartRules;
  1292. let hpRules = await getData("hpRules");
  1293. if (hpRules) self.hpRules = hpRules;
  1294. let customRules = await getData("customRules");
  1295. if (customRules) self.customRules = customRules;
  1296. if (_unsafeWindow.pagetualRules && _unsafeWindow.pagetualRules.length) {
  1297. _unsafeWindow.pagetualRules.forEach(rule => {
  1298. rule.isScript = true;
  1299. });
  1300. self.customRules = _unsafeWindow.pagetualRules.concat(self.customRules);
  1301. }
  1302. let rules = await getData("rules");
  1303. if (rules) self.rules = rules;
  1304. callback();
  1305. }
  1306.  
  1307. saveCurSiteRule() {
  1308. /*if(!this.curSiteRule || !this.curSiteRule.url || this.curSiteRule.smart || this.curSiteRule.url.length<13)return;
  1309. this.hpRules=this.hpRules.filter(item=>{return item&&item.url!=this.curSiteRule.url});
  1310. this.hpRules.unshift(this.curSiteRule);
  1311. if(this.hpRules.length>30){
  1312. this.hpRules.pop();
  1313. }
  1314. storage.setItem("hpRules", this.hpRules);*/
  1315. }
  1316.  
  1317. requestJSON(url, callback) {
  1318. _GM_xmlhttpRequest({
  1319. url: url,
  1320. method: 'GET',
  1321. timeout: 1000000,
  1322. headers: {
  1323. 'accept': 'application/json,text/html',
  1324. 'Referer': url,
  1325. },
  1326. onload: function(res) {
  1327. let json = null;
  1328. try {
  1329. json = JSON.parse(res.response || res.responseText);
  1330. } catch(e) {
  1331. debug(e, 'Error json');
  1332. }
  1333. callback(json);
  1334. },
  1335. onerror: function(e) {
  1336. callback(null, e);
  1337. },
  1338. ontimeout: function(e) {
  1339. callback(null, e);
  1340. }
  1341. });
  1342. }
  1343.  
  1344. formatRule(item, from) {
  1345. if (item.data && item.data.url) {
  1346. let result = {
  1347. name: item.name,
  1348. from: from,
  1349. action: item.data.forceIframe === "true" ? 1 : undefined,
  1350. url: item.data.url,
  1351. pageElement: item.data.pageElement,
  1352. nextLink: item.data.nextLink,
  1353. insert: item.data.insertBefore||undefined,
  1354. updatedAt: item.updated_at
  1355. };
  1356. let _css = (item.data.Stylus || '') + (item.data.CSS || '');
  1357. if (_css) result.css = _css;
  1358. if (item.data.bookmarklet) result.pageAction = item.data.bookmarklet;
  1359. return result;
  1360. } else {
  1361. item.from = from;
  1362. return item;
  1363. }
  1364. return null;
  1365. }
  1366.  
  1367. addRuleByUrl(url, from, callback) {
  1368. if (url.indexOf("?") === -1) {
  1369. url = url + "?" + Date.now();
  1370. } else {
  1371. url = url + "&" + Date.now();
  1372. }
  1373. this.requestJSON(url, (json,err) => {
  1374. if (!json) {
  1375. debug(err, "Failed to update " + url + " rules!");
  1376. }
  1377. this.addRules(json, from);
  1378. callback(json, err);
  1379. });
  1380. }
  1381.  
  1382. addRules(rules, from) {
  1383. if (rules && rules.length > 0) {
  1384. let first = -1;
  1385. this.rules = this.rules.filter((item, i) => {
  1386. if (item.from === from) {
  1387. if (first === -1) first = i;
  1388. return false;
  1389. } else return true;
  1390. });
  1391. if (first === -1) first = 0;
  1392. rules.forEach(item => {
  1393. let rule = this.formatRule(item, from);
  1394. if (rule) {
  1395. this.rules.splice(first, 0, rule)
  1396. }
  1397. });
  1398. }
  1399. }
  1400.  
  1401. ruleMatchPre(r) {
  1402. if (r.include) {
  1403. let include;
  1404. if (Array && Array.isArray && Array.isArray(r.include)) {
  1405. include = r.include.every((sel, i) => {
  1406. let ele = getElement(sel, document);
  1407. return !!ele;
  1408. });
  1409. } else include = getElement(r.include, document);
  1410. if (!include) return false;
  1411. }
  1412. if (r.exclude) {
  1413. let exclude;
  1414. if (Array && Array.isArray && Array.isArray(r.exclude)) {
  1415. exclude = !r.exclude.every((sel, i) => {
  1416. let ele = getElement(sel, document);
  1417. return !ele;
  1418. });
  1419. } else exclude = getElement(r.exclude, document);
  1420. if (exclude) return false;
  1421. }
  1422. return true;
  1423. }
  1424.  
  1425. ruleMatchReady(r) {
  1426. let findIndex = 0;
  1427. if (r.nextLink && r.nextLink !== 0) {
  1428. let nextLinkSel = r.nextLink, nextLink;
  1429. if (Array && Array.isArray && Array.isArray(nextLinkSel)) {
  1430. nextLink = !nextLinkSel.every((sel, i) => {
  1431. let ele = getElement(sel, document);
  1432. if (ele) findIndex = i;
  1433. return !ele;
  1434. });
  1435. } else nextLink = getElement(nextLinkSel, document);
  1436. if (!nextLink) return false;
  1437. }
  1438. if (r.pageElement) {
  1439. let pageElementSel = r.pageElement, pageElement;
  1440. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  1441. pageElementSel = pageElementSel[findIndex];
  1442. }
  1443. pageElement = getElement(pageElementSel, document);
  1444. if (!pageElement) return false;
  1445. }
  1446. if (r.insert) {
  1447. let insertSel = r.insert, insert;
  1448. if (Array && Array.isArray && Array.isArray(insertSel)) {
  1449. insertSel = insertSel[findIndex];
  1450. }
  1451. insert = getElement(insertSel, document);
  1452. if (!insert) return false;
  1453. }
  1454. //if (findIndex !== 0) nextIndex = findIndex;
  1455. return true;
  1456. }
  1457.  
  1458. ruleMatch(r) {
  1459. return this.ruleMatchPre(r) && this.ruleMatchReady(r);
  1460. }
  1461.  
  1462. scrollToShow(sel, doc) {
  1463. let exclude = getElement(sel, doc);
  1464. if (exclude) {
  1465. var actualTop = exclude.offsetTop;
  1466. var current = exclude.offsetParent;
  1467. while (current !== null) {
  1468. actualTop += current.offsetTop;
  1469. current = current.offsetParent;
  1470. }
  1471. getBody(doc).scrollTop = 0;
  1472. doc.documentElement.scrollTop = 0;
  1473. let maxHeight = Math.max(getBody(doc).scrollHeight, doc.documentElement.scrollHeight);
  1474. getBody(doc).scrollTop = actualTop - 10;
  1475. doc.documentElement.scrollTop = actualTop - 10;
  1476. setTimeout(() => {
  1477. while (actualTop < maxHeight) {
  1478. actualTop += 200;
  1479. getBody(doc).scrollTop = actualTop;
  1480. doc.documentElement.scrollTop = actualTop;
  1481. }
  1482. }, 0);
  1483. return false;
  1484. }
  1485. return true;
  1486. }
  1487.  
  1488. waitElement(doc, selArr) {
  1489. if (!selArr) selArr = this.curSiteRule.waitElement;
  1490. if (!Array.isArray(selArr)) {
  1491. selArr = [selArr];
  1492. }
  1493. let includeSel = selArr[0].trim(), excludeSel;
  1494. if (selArr.length === 2) {
  1495. excludeSel = selArr[1].trim().replace(/^!/, '');
  1496. } else if (includeSel.indexOf('!') === 0) {
  1497. excludeSel = includeSel.replace(/^!/, '');
  1498. includeSel = '';
  1499. }
  1500. if (includeSel) {
  1501. let include = getElement(includeSel, doc);
  1502. if (!include) {
  1503. if (doc !== document) {
  1504. getBody(doc).scrollTop = 9999999;
  1505. doc.documentElement.scrollTop = 9999999;
  1506. }
  1507. return false;
  1508. }
  1509. }
  1510. if (doc === document) return true;
  1511. if (excludeSel) {
  1512. if (!this.scrollToShow(excludeSel, doc)) {
  1513. if (!loadingDiv.offsetParent && this.insert.parentNode) {
  1514. this.insertElement(loadingDiv);
  1515. }
  1516. return false;
  1517. }
  1518. }
  1519. return true;
  1520. }
  1521.  
  1522. runPageBar(pageBar) {
  1523. if (this.curSiteRule.pageBar && this.curSiteRule.pageBar !== 0) {
  1524. try {
  1525. ((typeof this.curSiteRule.pageBar === 'function') ? this.curSiteRule.pageBar : Function("pageBar",'"use strict";' + this.curSiteRule.pageBar))(pageBar);
  1526. } catch(e) {
  1527. debug(e);
  1528. }
  1529. }
  1530. }
  1531.  
  1532. runWait(cb) {
  1533. let checkEval = null, waitTime = 0;
  1534. if (this.curSiteRule.waitElement) {
  1535. checkEval = async doc => {
  1536. return await this.waitElement(doc);
  1537. };
  1538. } else if(this.curSiteRule.wait) {
  1539. if (isNaN(this.curSiteRule.wait)) {
  1540. try {
  1541. checkEval = (typeof this.curSiteRule.wait === 'function') ? this.curSiteRule.wait : new AsyncFunction("doc", '"use strict";' + this.curSiteRule.wait);
  1542. } catch(e) {
  1543. debug(e);
  1544. }
  1545. } else {
  1546. waitTime = this.curSiteRule.wait;
  1547. }
  1548. }
  1549. cb(checkEval, waitTime);
  1550. }
  1551.  
  1552. findNoNext() {
  1553. if (!this.curSiteRule || !this.curSiteRule.smart || this.curSiteRule.nextLink === 0 || this.possibleRule) return;
  1554. let self = this;
  1555. self.curSiteRule.nextLink = 0;
  1556. self.smartRules = self.smartRules.filter(item => {return item && item.url !== self.curSiteRule.url;});
  1557. self.smartRules.unshift(self.curSiteRule);
  1558. storage.setItem("smartRules", self.smartRules);
  1559. }
  1560.  
  1561. async getRule(callback) {
  1562. var href = location.href.slice(0, 500);
  1563. if(noRuleTest) {
  1564. this.curSiteRule = {};
  1565. this.curSiteRule.url = href;
  1566. this.curSiteRule.smart = true;
  1567. callback();
  1568. return;
  1569. }
  1570. if (_unsafeWindow.pagetualRule) {
  1571. this.curSiteRule = _unsafeWindow.pagetualRule;
  1572. if (!this.curSiteRule.url) this.curSiteRule.url = ".";
  1573. this.curSiteRule.isScript = true;
  1574. }
  1575. if (this.curSiteRule && this.curSiteRule.url && !this.curSiteRule.smart) {
  1576. let urlReg = new RegExp(this.curSiteRule.url, "i");
  1577. if (urlReg.test(href) && this.ruleMatch(this.curSiteRule)) {
  1578. return callback();
  1579. }
  1580. }
  1581. if (this.possibleRule) {
  1582. let urlReg = new RegExp(this.possibleRule.url, "i");
  1583. if (urlReg.test(href) && this.ruleMatch(this.possibleRule)) {
  1584. this.curSiteRule = this.possibleRule;
  1585. debug(this.curSiteRule, 'Match');
  1586. return callback();
  1587. }
  1588. }
  1589. this.curSiteRule = {};
  1590. var self = this;
  1591.  
  1592. function setRule(r) {
  1593. if (self.preSiteRule) {
  1594. href = location.href.slice(0, 500);
  1595. let urlReg = new RegExp(self.preSiteRule.url, "i");
  1596. if (urlReg.test(href) && self.ruleMatch(self.preSiteRule)) {
  1597. self.curSiteRule = self.preSiteRule;
  1598. return callback();
  1599. }
  1600. }
  1601. if (r.from === 2) {
  1602. delete r.autoLoadNum;
  1603. delete r.history;
  1604. delete r.sideController;
  1605. if (r.pageBar === 0) delete r.pageBar;
  1606. }
  1607. if (!r.smart) {
  1608. self.insert = null;
  1609. self.curSiteRule = r;
  1610. self.preSiteRule = r;
  1611. if (r.enable !== 0) debug(r, 'Match');
  1612. } else if (!self.curSiteRule || !self.curSiteRule.smart) self.curSiteRule = r;
  1613. callback();
  1614. }
  1615.  
  1616. function checkRule(r) {
  1617. if (r.from === 1 && r.url.length <= 13) return false;
  1618. let urlReg = new RegExp(r.url, "i");
  1619. if (urlReg.test(href)) {
  1620. if (!self.ruleMatchPre(r)) return false;
  1621. if (r.url.length > 15 && r.from !== 1) {
  1622. self.possibleRule = r;
  1623. }
  1624. if (r.waitElement) {
  1625. let waitTime = 500;
  1626. let checkReady = () => {
  1627. setTimeout(() => {
  1628. if (!self.waitElement(document, r.waitElement) || !self.ruleMatchReady(r)) {
  1629. checkReady();
  1630. } else {
  1631. setRule(r);
  1632. }
  1633. }, parseInt(waitTime));
  1634. };
  1635. checkReady();
  1636. debug(r, 'Wait for');
  1637. return true;
  1638. } else if (r.wait) {
  1639. let waitTime = 500, checkEval, maxCheckTimes = 50;
  1640. if (isNaN(r.wait)) {
  1641. try {
  1642. checkEval = (typeof r.wait === 'function') ? r.wait : AsyncFunction("doc",'"use strict";' + r.wait);
  1643. } catch(e) {
  1644. debug(e, 'Error when checkeval');
  1645. }
  1646. } else {
  1647. waitTime = r.wait;
  1648. }
  1649. let checkReady = () => {
  1650. if (maxCheckTimes-- <= 0) {
  1651. debug("Wait for rule ready but failed");
  1652. setRule(r);
  1653. return;
  1654. }
  1655. setTimeout(async() => {
  1656. if (!self.ruleMatchReady(r) || (checkEval && !await checkEval(document))) {
  1657. checkReady();
  1658. } else {
  1659. setRule(r);
  1660. }
  1661. }, parseInt(waitTime));
  1662. };
  1663. checkReady();
  1664. debug(r, 'Wait for');
  1665. return true;
  1666. }
  1667. if (r.pinUrl) {
  1668. setRule(r);
  1669. return true;
  1670. }
  1671. if (!self.ruleMatchReady(r)) {
  1672. return false;
  1673. }
  1674. setRule(r);
  1675. return true;
  1676. }
  1677. return false;
  1678. }
  1679.  
  1680. function checkHpRules() {
  1681. for (let i in self.hpRules) {
  1682. let rule = self.hpRules[i];
  1683. if (!rule || !rule.url || rule.smart) continue;
  1684. if (checkRule(rule)) return true;
  1685. }
  1686. return false;
  1687. }
  1688.  
  1689. function checkCustomRules() {
  1690. for (let i in self.customRules) {
  1691. let rule = self.customRules[i];
  1692. if (!rule || !rule.url) continue;
  1693. if (checkRule(rule)) return true;
  1694. }
  1695. return false;
  1696. }
  1697.  
  1698. if (rulesData.customFirst) {
  1699. if (checkCustomRules()) return;
  1700. await sleep(1);
  1701. if (checkHpRules()) return;
  1702. } else {
  1703. if (checkHpRules()) return;
  1704. await sleep(1);
  1705. if (checkCustomRules()) return;
  1706. }
  1707. await sleep(1);
  1708.  
  1709. for (let i in this.smartRules) {
  1710. let rule = this.smartRules[i];
  1711. if (!rule || !rule.url || !rule.smart) continue;
  1712. if (href == rule.url) {
  1713. setRule(rule);
  1714. return;
  1715. }
  1716. }
  1717. let r = 0;
  1718. async function searchByTime() {
  1719. while (document.hidden) {
  1720. await sleep(1000);
  1721. }
  1722. setTimeout(() => {
  1723. let end = r + 20;
  1724. end = end > self.rules.length ? self.rules.length : end;
  1725. for (; r < end; r++) {
  1726. let rule = self.rules[r];
  1727. if (checkRule(rule)) return;
  1728. }
  1729. if (end >= self.rules.length) {
  1730. setRule({url: href, smart: true});
  1731. return;
  1732. } else {
  1733. searchByTime();
  1734. }
  1735. }, 1);
  1736. }
  1737. searchByTime();
  1738. }
  1739.  
  1740. addToHpRules(instead) {
  1741. try {
  1742. if (this.curSiteRule.isScript) return;
  1743. if (!this.hpRules) this.hpRules = [];
  1744. let url = this.curSiteRule && this.curSiteRule.url, self = this;
  1745. let href = location.href.slice(0, 500);
  1746. let matchedRules = this.hpRules.filter(rule => rule != self.curSiteRule && new RegExp(rule.url, "i").test(href) && self.ruleMatch(rule));
  1747. if (url) matchedRules.unshift(this.curSiteRule);
  1748. matchedRules.sort((a, b) => {
  1749. if ((a.include || a.exclude) && (!b.include && !b.exclude)) {
  1750. return -1;
  1751. } else if ((b.include || b.exclude) && (!a.include && !a.exclude)) {
  1752. return 1;
  1753. } else {
  1754. if ((a.nextLink || a.pageElement) && (!b.nextLink && !b.pageElement)) {
  1755. return -1;
  1756. } else if ((b.nextLink || b.pageElement) && (!a.nextLink && !a.pageElement)) {
  1757. return 1;
  1758. } else {
  1759. if (a.url.length > b.url.length) {
  1760. return -1;
  1761. } else if (a.url.length < b.url.length) {
  1762. return 1;
  1763. } else {
  1764. return 0;
  1765. }
  1766. }
  1767. }
  1768. });
  1769. this.hpRules = this.hpRules.filter(item => {
  1770. return item && !matchedRules.find(rule => item.url == rule.url && JSON.stringify(item) == JSON.stringify(rule));
  1771. });
  1772. if (instead) {
  1773. if (url) {
  1774. this.hpRules.unshift(this.curSiteRule);
  1775. matchedRules = [];
  1776. }
  1777. } else {
  1778. this.hpRules = matchedRules.concat(this.hpRules);
  1779. }
  1780. if (matchedRules && matchedRules.length) this.curSiteRule = matchedRules[0];
  1781. if (this.hpRules.length > 30) {
  1782. this.hpRules.pop();
  1783. }
  1784. if (!rulesData.sort) rulesData.sort = [1];
  1785. this.hpRules.sort((a, b) => {
  1786. let aSort = -1, bSort = -1;
  1787. for (let s = 0; s < rulesData.sort.length; s++) {
  1788. if (a.from == rulesData.sort[s]) aSort = s;
  1789. if (b.from == rulesData.sort[s]) bSort = s;
  1790. if (aSort > -1 && bSort > -1) break;
  1791. }
  1792. return aSort - bSort;
  1793. });
  1794. storage.setItem("hpRules", this.hpRules);
  1795. } catch (e) {
  1796. debug(e);
  1797. }
  1798. }
  1799.  
  1800. replaceElement(doc) {
  1801. if (!doc || doc === document) return;
  1802. let replaceElementSel = this.curSiteRule.replaceElement;
  1803. if (replaceElementSel) {
  1804. if (!Array.isArray(replaceElementSel)) {
  1805. replaceElementSel = [replaceElementSel];
  1806. }
  1807. replaceElementSel.forEach(sel => {
  1808. let pageEles = getAllElements(sel, document);
  1809. let replaceEles = getAllElements(sel, doc);
  1810. for (let i = 0; i < pageEles.length; i++) {
  1811. let replaceEle = replaceEles[i];
  1812. let pageEle = pageEles[i];
  1813. if (replaceEle) {
  1814. pageEle.parentNode.replaceChild(replaceEle.cloneNode(true), pageEle);
  1815. } else break;
  1816. }
  1817. });
  1818. }
  1819. }
  1820.  
  1821. refreshByClick() {
  1822. let refreshByClickSel = this.curSiteRule.refreshByClick;
  1823. if (refreshByClickSel) {
  1824. let self = this;
  1825. if (!this.refreshByClickHandler) {
  1826. this.refreshByClickHandler = e => {
  1827. if (!self.refreshing) {
  1828. self.refreshing = true;
  1829. setTimeout(() => {
  1830. self.refreshing = false;
  1831. let checkEles = getAllElements(refreshByClickSel, document);
  1832. for (let i = 0; i < checkEles.length; i++) {
  1833. let curEle = checkEles[i];
  1834. if (curEle === e.target || curEle.contains(e.target)) {
  1835. ruleParser.urlChanged();
  1836. isPause = true;
  1837. if (!ruleParser.nextLinkHref) isLoading = false;
  1838. break;
  1839. }
  1840. }
  1841. }, 300);
  1842. }
  1843. }
  1844. }
  1845. document.removeEventListener("click", this.refreshByClickHandler);
  1846. document.addEventListener("click", this.refreshByClickHandler);
  1847. }
  1848. }
  1849.  
  1850. getValidSize(ele, win) {
  1851. if (!win) return {h: 0, w: 0};
  1852. let eleStyle = win.getComputedStyle(ele);
  1853. if (!ele.offsetParent && (eleStyle.position !== "fixed" || eleStyle.opacity === 0)) {
  1854. return {h: 0, w: 0};
  1855. }
  1856. if (ele.children && ele.children.length === 1 && (ele.offsetWidth === 0 || ele.offsetHeight === 0)) {
  1857. ele = ele.children[0];
  1858. }
  1859. let h = ele.scrollHeight, w;
  1860. if (eleStyle.overflow === "hidden") {
  1861. h = ele.offsetHeight;
  1862. w = ele.offsetWidth;
  1863. } else w = parseInt(ele.offsetWidth || ele.scrollWidth);
  1864. if (h === 0 && ele.parentNode && ele.parentNode.children.length === 1) {
  1865. h = ele.parentNode.scrollHeight;
  1866. }
  1867. while (h === 0 && ele.children && ele.children.length === 1) {
  1868. ele = ele.children[0];
  1869. h = ele.scrollHeight;
  1870. }
  1871. if (h === 0 && ele.children && ele.children.length) {
  1872. let maxChildSize = {h: 0}, self = this;
  1873. [].forEach.call(ele.children, el => {
  1874. let childSize = self.getValidSize(el, win);
  1875. if (childSize.h > maxChildSize.h) maxChildSize = childSize;
  1876. });
  1877. if (maxChildSize.h !== 0) return maxChildSize;
  1878. }
  1879. const maxNum = 2147483647;
  1880. let moreChild = ele.children[0], minOffsetTop = maxNum;
  1881. while (moreChild) {
  1882. if ((moreChild.offsetParent === ele || moreChild.offsetParent === ele.offsetParent)) {
  1883. let curOffsetTop = moreChild.offsetParent === ele.offsetParent ? moreChild.offsetTop - ele.offsetTop : moreChild.offsetTop;
  1884. if (curOffsetTop < minOffsetTop) {
  1885. minOffsetTop = curOffsetTop;
  1886. }
  1887. }
  1888. moreChild = moreChild.nextElementSibling;
  1889. }
  1890. if (h && minOffsetTop !== maxNum && minOffsetTop > 0) {
  1891. h -= minOffsetTop;
  1892. }
  1893. return {h: h, w: w};
  1894. }
  1895.  
  1896. checkTargetChildren(ele, curWin, articleNum, curHeight) {
  1897. let pf = false;
  1898. if (ele.parentNode) {
  1899. let paStyle = curWin.getComputedStyle(ele.parentNode);
  1900. let paDisplay = paStyle.display;
  1901. let paOverflow = paStyle.overflow;
  1902. pf = (paDisplay.indexOf('flex') !== -1 && paStyle.flexDirection.indexOf("row") === 0 && paStyle.flexWrap !== "wrap") || compareNodeName(ele.parentNode, ["ul"]) || paDisplay.indexOf('grid') !== -1 || paOverflow === "hidden";
  1903. }
  1904. let curStyle = curWin.getComputedStyle(ele);
  1905. if (ele.children.length > 1) {
  1906. if (articleNum > 1) {
  1907. return ">article";
  1908. } else {
  1909. let hasText = false;
  1910. for (let i in ele.childNodes) {
  1911. let child = ele.childNodes[i];
  1912. if (child.nodeType === 3 && child.nodeValue.trim() !== '') {
  1913. hasText = true;
  1914. break;
  1915. }
  1916. }
  1917. let gridArea = curStyle.gridArea;
  1918. if (gridArea && gridArea !== "auto" && gridArea !== "auto / auto / auto / auto") {
  1919. return ">*";
  1920. } else {
  1921. let middleChild = ele.children[parseInt(ele.children.length / 2)];
  1922. if ((curStyle.display === 'flex' && curStyle.flexDirection.indexOf("row") === 0 && curStyle.flexWrap !== "wrap") || (curStyle.float === "none" && curStyle.display !== "table-cell" && (rulesData.opacity !== 0 || hasText) && !pf)) {
  1923. return "";
  1924. } else if ((middleChild.style && middleChild.style.position === "absolute" && middleChild.style.left && middleChild.style.top) || compareNodeName(ele, ["ul"]) || curHeight === 0) {
  1925. return "";
  1926. } else {
  1927. return ">*";
  1928. }
  1929. }
  1930. }
  1931. } else if (pf || curStyle.position === "absolute") {
  1932. return ">*";
  1933. }
  1934. return "";
  1935. }
  1936.  
  1937. getPageElement(doc, curWin, dontFind) {
  1938. if (doc === document && this.docElementValid()) {
  1939. return this.docPageElement;
  1940. }
  1941. let pageElement = null;
  1942. let self = this;
  1943. let body = getBody(doc);
  1944. if (this.curSiteRule.pageElement) {
  1945. let pageElementSel = this.curSiteRule.pageElement;
  1946. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  1947. pageElementSel = pageElementSel[nextIndex < pageElementSel.length ? nextIndex : 0];
  1948. }
  1949. pageElement = getAllElements(pageElementSel, doc);
  1950. if (this.curSiteRule.smart && (!pageElement || pageElement.length === 0)) {
  1951. const childSelMatch = />\s*\*$/;
  1952. const targetChild = childSelMatch.test(pageElementSel);
  1953. if (targetChild) pageElementSel = pageElementSel.replace(childSelMatch, "");
  1954. let pageElementSelSplit = pageElementSel.split(">");
  1955. while(pageElementSelSplit && pageElementSelSplit.length > 5) {
  1956. pageElementSelSplit.shift();
  1957. let tempSel = pageElementSelSplit.join(">");
  1958. pageElement = getAllElements(tempSel, doc);
  1959. if (pageElement && pageElement.length === 1) {
  1960. if (targetChild) {
  1961. pageElement = pageElement.children;
  1962. }
  1963. this.curSiteRule.pageElement = tempSel + (targetChild ? ">*" : "");
  1964. break;
  1965. }
  1966. }
  1967. if (!pageElement || pageElement.length === 0) {
  1968. pageElementSel = pageElementSel.replace(/:nth-of-type\(\d+\)/g, "");
  1969. pageElement = getAllElements(pageElementSel, doc);
  1970. if (pageElement && pageElement.length === 1) {
  1971. if (targetChild) {
  1972. pageElement = pageElement.children;
  1973. }
  1974. this.curSiteRule.pageElement = pageElementSel + (targetChild ? ">*" : "");
  1975. }
  1976. }
  1977. }
  1978. if (this.curSiteRule.smart && pageElement && pageElement.length && curWin && curWin !== _unsafeWindow) {
  1979. let parent = pageElement[0].parentNode;
  1980. let loading = parent.querySelector('[class*=loading]');
  1981. if (loading && loading.offsetParent && loading.offsetHeight > parent.offsetHeight>>2) {
  1982. pageElement = null;
  1983. }
  1984. }
  1985. }
  1986. if (pageElement && pageElement.length === 1 && pageElement[0].style.display === 'none') {
  1987. pageElement = [body];
  1988. }
  1989. if (this.curSiteRule.smart && pageElement && pageElement.length > 0 && compareNodeName(pageElement[0], ["tr"])) {
  1990. let mainTr = this.insert.parentNode.querySelectorAll('tr'), mainTdNum = 0, newTdNum = 0;
  1991. mainTr = mainTr[mainTr.length - 1];
  1992. [].forEach.call(mainTr.children, el => {
  1993. if (compareNodeName(el, ["td", "th"])) {
  1994. mainTdNum += el.colSpan || 1;
  1995. }
  1996. });
  1997. [].forEach.call(pageElement[0].children, el => {
  1998. if (compareNodeName(el, ["td", "th"])) {
  1999. newTdNum += el.colSpan || 1;
  2000. }
  2001. });
  2002. if (mainTdNum !== newTdNum) {
  2003. this.curSiteRule.pageElement = this.curSiteRule.pageElement.replace(/> *table.*/, ">table");
  2004. this.getInsert(true);
  2005. return this.getPageElement(doc, curWin, dontFind);
  2006. }
  2007. }
  2008. if ((this.curSiteRule.smart || !this.curSiteRule.pageElement) && (!pageElement || pageElement.length == 0) && curWin && !dontFind) {
  2009. if (!body) return null;
  2010. let bodyHeight = parseInt(body.offsetHeight || body.scrollHeight);
  2011. let curHeight = bodyHeight, curWidth = 0;
  2012. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  2013. let windowWidth = window.innerWidth || document.documentElement.clientWidth;
  2014. let needCheckNext = (doc == document && this.initNext), nextLeftPos = 0;
  2015. if (needCheckNext && this.initNext.getBoundingClientRect) {
  2016. nextLeftPos = this.initNext.getBoundingClientRect().left;
  2017. }
  2018. function checkElement(ele) {
  2019. if (compareNodeName(ele, ["pre", "code"])) {
  2020. self.curSiteRule.pageElement = geneSelector(ele.parentNode);
  2021. debug(self.curSiteRule.pageElement, 'Page element');
  2022. return [ele.parentNode];
  2023. }
  2024. if (ele.children && ele.children.length === 1) {
  2025. let hasText = false;
  2026. for (let i in ele.childNodes) {
  2027. let child = ele.childNodes[i];
  2028. if (child.nodeType === 3 && child.nodeValue.trim() !== '') {
  2029. hasText = true;
  2030. break;
  2031. }
  2032. }
  2033. if (!hasText) {
  2034. ele = ele.children[0];
  2035. let validSize = self.getValidSize(ele, curWin);
  2036. curHeight = validSize.h;
  2037. curWidth = validSize.w;
  2038. }
  2039. }
  2040. if (compareNodeName(ele, ["picture"]) || !ele.innerText || ele.innerText.trim() === '') {
  2041. self.curSiteRule.pageElement = geneSelector(ele.parentNode) + ">" + ele.nodeName.toLowerCase();
  2042. debug(self.curSiteRule.pageElement, 'Page element');
  2043. let eles = [];
  2044. for (let i = 0; i < ele.parentNode.children.length; i++) {
  2045. let curNode = ele.parentNode.children[i];
  2046. if (curNode.nodeName === ele.nodeName && curNode.id === ele.id && curNode.className === ele.className) {
  2047. eles.push(curNode);
  2048. }
  2049. }
  2050. return eles;
  2051. }
  2052. if (compareNodeName(ele, ["form"]) && ele.parentNode !== getBody(document)) {
  2053. self.curSiteRule.pageElement = geneSelector(ele) + ">*";
  2054. debug(self.curSiteRule.pageElement, 'Page element');
  2055. return ele.children;
  2056. }
  2057. if (ele.children.length === 0 && !self.curSiteRule.pageElement) {
  2058. if (compareNodeName(ele.parentNode, ["p"])) ele = ele.parentNode;
  2059. self.curSiteRule.pageElement = geneSelector(ele.parentNode) + ">" + ele.nodeName.toLowerCase();
  2060. debug(self.curSiteRule.pageElement, 'Page element');
  2061. return getAllElements(self.curSiteRule.pageElement, doc);
  2062. }
  2063. let i, minHeight = curHeight * 0.52, curMaxEle = null, curMaxArea = 0, minWidth = Math.min(curWidth * 0.38, 500);
  2064. let isHori, preOffsetTop = -1;
  2065. let articleNum = 0;
  2066. for (i = 0; i < ele.children.length; i++) {
  2067. let curNode = ele.children[i];
  2068. if (ele !== body && /^H\d$/i.test(curNode.nodeName) && curNode.offsetParent) {
  2069. curMaxEle = null;
  2070. break;
  2071. }
  2072. if (compareNodeName(curNode, ["canvas", "nav"])) continue;
  2073. let curStyle = curWin.getComputedStyle(curNode);
  2074. if (!curNode.offsetParent && (curStyle.position !== "fixed" || curStyle.opacity === 0)) {
  2075. continue;
  2076. }
  2077. if (!compareNodeName(curNode, ["img"]) && curNode.querySelector('img') === null && /^\s*$/.test(curNode.innerText)) continue;
  2078. if (needCheckNext && !curNode.contains(self.initNext) && getElementTop(curNode) > windowHeight) {
  2079. continue;
  2080. }
  2081. if (compareNodeName(curNode, ["article"])) articleNum++;
  2082. let validSize = self.getValidSize(curNode, curWin);
  2083. let h = validSize.h;
  2084. let w = validSize.w;
  2085. if (isNaN(h) || isNaN(w) || !h || !w) continue;
  2086. isHori = Math.abs(preOffsetTop - curNode.offsetTop) <= 20 ? true : (preOffsetTop === -1 && curNode.nextElementSibling && curNode.nextElementSibling.offsetTop === curNode.offsetTop);
  2087. if (isHori && h <= 50) continue;
  2088. /*if (isHori && nextLeftPos && curMaxEle && curWidth > 500 && curHeight > 500) {
  2089. let curRect = curNode.getBoundingClientRect();
  2090. if (curRect.left > windowWidth>>2 && curRect.left <= nextLeftPos && curRect.right > nextLeftPos) {
  2091. continue;
  2092. }
  2093. }*/
  2094. let a = h * w, moreChild = curNode.children[0];
  2095. while (moreChild) {
  2096. let validSize = self.getValidSize(moreChild, curWin);
  2097. let ch = validSize.h;
  2098. let cw = validSize.w;
  2099. if (h < ch) {
  2100. h = ch;
  2101. }
  2102. if (moreChild.innerText !== "" && ch && cw) {
  2103. a += ch * cw;
  2104. }
  2105. moreChild = moreChild.nextElementSibling;
  2106. }
  2107. let isMax = false;
  2108. if (isHori) {
  2109. if (curMaxEle) {
  2110. if (w > curWidth && (windowWidth>>1) > curWidth) {
  2111. isMax = true;
  2112. } else if (w + 300 > curWidth && a > curMaxArea) {
  2113. isMax = true;
  2114. }
  2115. }
  2116. } else {
  2117. if (curMaxEle && curMaxEle.offsetParent === curNode.offsetParent && curMaxEle.offsetTop === curNode.offsetTop) {
  2118. if (curMaxArea * 2 > a) continue;
  2119. }
  2120. isMax = curMaxArea < a;
  2121. }
  2122. if (curMaxEle === null || isMax) {
  2123. if (isHori) {
  2124. if (w < minWidth) {
  2125. continue;
  2126. }
  2127. }
  2128. if (h < minHeight) {
  2129. if (!needCheckNext || h < (windowHeight>>1)) {
  2130. continue;
  2131. }
  2132. if (!ele.contains(self.initNext)) {
  2133. continue;
  2134. } else if (!curNode.contains(self.initNext) && h < curHeight >> 1) {
  2135. continue;
  2136. }
  2137. }
  2138. curHeight = h;
  2139. curMaxArea = a;
  2140. curWidth = w;
  2141. curMaxEle = curNode;
  2142. preOffsetTop = curNode.offsetTop;
  2143. }
  2144. }
  2145. let curHeightPercent = curHeight / bodyHeight;
  2146. if (curMaxEle && curHeightPercent <= 0.18) {
  2147. let article;
  2148. for (let i = 0; i < mainSel.length; i++) {
  2149. article = doc.querySelectorAll(mainSel[i]);
  2150. if (article && article.length === 1) break;
  2151. }
  2152. if (article && article.length === 1) {
  2153. article = article[0];
  2154. let childrenEnd = self.checkTargetChildren(article, curWin, articleNum, curHeight);
  2155. self.curSiteRule.pageElement = article.nodeName.toLowerCase() + (article.id ? "#" + article.id : "") + (article.className ? "." + article.className.replace(/ /g, ".") : "") + childrenEnd;
  2156. debug(self.curSiteRule.pageElement, 'Page element');
  2157. return childrenEnd ? article.children : [article];
  2158. }
  2159. curMaxEle = null;
  2160. }
  2161. if (curMaxEle && (!compareNodeName(curMaxEle, ["ul"]) || curHeightPercent > 0.8)) {
  2162. let sameClassNum = 0, hasDifferent = false;
  2163. if (curMaxEle.className) {
  2164. for(i = 0; i < ele.children.length; i++) {
  2165. let curNode = ele.children[i];
  2166. if (curMaxEle !== curNode && curNode.style.display !== 'none' && curMaxEle.className === curNode.className && curMaxEle.nodeName === curNode.nodeName){
  2167. sameClassNum++;
  2168. } else if (curMaxEle.className !== curNode.className) {
  2169. hasDifferent = true;
  2170. }
  2171. }
  2172. }
  2173. if (sameClassNum < 2 || (sameClassNum < 5 && hasDifferent)) {
  2174. return checkElement(curMaxEle);
  2175. }
  2176. }
  2177. if (ele.nodeName === "APP-ROOT") {
  2178. isPause = true;
  2179. debug(ele, "Angular root");
  2180. return null;
  2181. }
  2182. while (compareNodeName(ele, ["p", "br", "td"])) {
  2183. ele = ele.parentNode;
  2184. }
  2185. if (compareNodeName(ele, ["tbody"])) {
  2186. self.curSiteRule.pageElement = geneSelector(ele) + ">*";
  2187. if (ele.children.length > 0 && ele.children[0].querySelector("th")) {
  2188. self.curSiteRule.pageElement += ":not(:first-child)";
  2189. }
  2190. debug(self.curSiteRule.pageElement, 'Page element');
  2191. return ele.children;
  2192. }
  2193. let imgs = ele.querySelectorAll('img');
  2194. if (imgs.length === 1) {
  2195. let img = imgs[0];
  2196. if (img.offsetWidth > ele.offsetWidth / 3 * 2 && img.offsetHeight > ele.offsetHeight / 2) {
  2197. ele = img;
  2198. }
  2199. }
  2200. let childrenEnd = self.checkTargetChildren(ele, curWin, articleNum, curHeight);
  2201. if (childrenEnd) {
  2202. self.curSiteRule.pageElement = geneSelector(ele) + childrenEnd;
  2203. ele = ele.children;
  2204. } else {
  2205. if (ele.scrollHeight === 0 && ele.parentNode.children.length === 1) {
  2206. ele = ele.parentNode;
  2207. }
  2208. self.curSiteRule.pageElement = geneSelector(ele);
  2209. ele = [ele];
  2210. }
  2211. debug(self.curSiteRule.pageElement, 'Page element');
  2212. return ele;
  2213. }
  2214. pageElement = checkElement(body);
  2215. if (pageElement && pageElement.length > 0 && self.initNext) {
  2216. let posEle = pageElement[pageElement.length - 1];
  2217. while (posEle && !posEle.offsetParent) {
  2218. posEle = posEle.previousElementSibling || posEle.parentNode;
  2219. }
  2220. if (posEle && posEle.scrollHeight === 0 && posEle.lastElementChild) posEle = posEle.lastElementChild;
  2221. let lastBottom = forceState !== 2 && forceState !== 3 && posEle && getElementBottom(posEle);
  2222. if (lastBottom && getElementTop(self.initNext) - lastBottom > 1000) {
  2223. debug("Stop as too long between next & page element, try to enable Force-Join mode.");
  2224. isPause = true;
  2225. pageElement = [];
  2226. sideController.remove();
  2227. } else {
  2228. if (pageElement.length === 1 && compareNodeName(pageElement[0], ["img"])) {
  2229. self.curSiteRule.pageBar = 0;
  2230. }
  2231. }
  2232. }
  2233. //if(pageElement)this.saveCurSiteRule();
  2234. }
  2235.  
  2236. if (doc !== document) {
  2237. this.setPageElementCss(pageElement);
  2238. this.lazyImgAction(pageElement, doc);
  2239. this.filterEles(doc, pageElement);
  2240. } else if (!this.docPageElement) {
  2241. this.setPageElementCss(pageElement, true);
  2242. this.docPageElement = pageElement;
  2243. this.filterEles(doc, pageElement);
  2244. if (this.nextLinkHref) {
  2245. this.openInNewTab(pageElement);
  2246. }
  2247. }
  2248. return pageElement;
  2249. }
  2250.  
  2251. showAddedElements() {
  2252. if (!this.addedElementsIsHide) return;
  2253. if (this.addedElePool && this.addedElePool.length) {
  2254. this.addedElePool.forEach(ele => {
  2255. ele.classList && ele.classList.remove("pagetual-hide");
  2256. });
  2257. }
  2258. this.addedElementsIsHide = false;
  2259. }
  2260.  
  2261. hideAddedElements() {
  2262. if (this.addedElePool && this.addedElePool.length) {
  2263. this.addedElePool.forEach(ele => {
  2264. ele.classList && ele.classList.add("pagetual-hide");
  2265. });
  2266. }
  2267. this.addedElementsIsHide = true;
  2268. }
  2269.  
  2270. toggleAddedElements() {
  2271. if (this.addedElementsIsHide) {
  2272. this.showAddedElements();
  2273. } else {
  2274. this.hideAddedElements();
  2275. }
  2276. }
  2277.  
  2278. changeVisibility() {
  2279. let contentVisibility = this.curSiteRule.contentVisibility || rulesData.contentVisibility;
  2280. if (!contentVisibility) return;
  2281. if (!this.changingVisibility) {
  2282. clearTimeout(this.changeVisibilityTimer);
  2283. this.changeVisibilityTimer = setTimeout(() => {
  2284. this.changingVisibility = true;
  2285. this.changeVisibility();
  2286. }, 300);
  2287. return;
  2288. }
  2289. this.changingVisibility = false;
  2290. if (!this.visibilityItems || !this.visibilityItems.length || this.visibleIndex < 0) return;
  2291. let tempIndex = this.visibleIndex, findVisible = false, lastVisible = 0;
  2292. let viewPortHeight = window.innerHeight || document.documentElement.clientHeight || getBody(document).clientHeight;
  2293. let checkItem = this.visibilityItems[tempIndex];
  2294. while(checkItem) {
  2295. if (checkItem.offsetParent) {
  2296. if (!checkItem.style.containIntrinsicSize) return;
  2297. let clientRect = checkItem.getBoundingClientRect();
  2298. let top = clientRect && clientRect.top;
  2299. let bottom = clientRect && clientRect.bottom;
  2300. if (bottom > 0 && top < viewPortHeight) {
  2301. if (!findVisible) {
  2302. findVisible = true;
  2303. lastVisible = tempIndex;
  2304. }
  2305. checkItem.style.contentVisibility = "visible";
  2306. } else {
  2307. if (top < viewPortHeight && checkItem.style.contentVisibility === "auto") {
  2308. break;
  2309. } else checkItem.style.contentVisibility = "auto";
  2310. }
  2311. }
  2312. if (tempIndex === 0) break;
  2313. tempIndex--;
  2314. checkItem = this.visibilityItems[tempIndex];
  2315. }
  2316. tempIndex = this.visibleIndex + 1;
  2317. if (findVisible) {
  2318. this.visibleIndex = lastVisible;
  2319. }
  2320. checkItem = this.visibilityItems[tempIndex];
  2321. while(checkItem) {
  2322. if (checkItem.offsetParent) {
  2323. if (!checkItem.style.containIntrinsicSize) return;
  2324. let clientRect = checkItem.getBoundingClientRect();
  2325. let top = clientRect && clientRect.top;
  2326. let bottom = clientRect && clientRect.bottom;
  2327. if (bottom > 0 && top < viewPortHeight) {
  2328. findVisible = true;
  2329. lastVisible = tempIndex;
  2330. checkItem.style.contentVisibility = "visible";
  2331. } else {
  2332. if (findVisible && checkItem.style.contentVisibility === "auto") {
  2333. break;
  2334. } else checkItem.style.contentVisibility = "auto";
  2335. }
  2336. }
  2337. if (tempIndex === this.visibilityItems.length - 1) break;
  2338. tempIndex++;
  2339. checkItem = this.visibilityItems[tempIndex];
  2340. }
  2341. if (findVisible) {
  2342. this.visibleIndex = lastVisible;
  2343. }
  2344. }
  2345.  
  2346. setPageElementCss(pageElement, init) {
  2347. let self = this;
  2348. if (pageElement && pageElement.length > 0) {
  2349. let pageElementCss = this.curSiteRule.pageElementCss || rulesData.pageElementCss;
  2350. if (!pageElementCss && init && !this.nextLinkHref) return;
  2351. let contentVisibility = this.curSiteRule.contentVisibility || rulesData.contentVisibility;
  2352. if (!contentVisibility && !pageElementCss) return;
  2353. [].forEach.call(pageElement, (ele, i) => {
  2354. if (!compareNodeName(ele, ["link", "meta", "style", "script"])) {
  2355. if (pageElementCss) {
  2356. if (pageElementCss !== '0' && !ele.dataset.pagetualPageElement) {
  2357. ele.style.cssText = (ele.style.cssText || '') + pageElementCss;
  2358. ele.dataset.pagetualPageElement = 1;
  2359. }
  2360. }
  2361. if (contentVisibility) {
  2362. ele.style.containIntrinsicSize = `auto ${ele.offsetHeight || self.preVisibleHeight || 100}px`;
  2363. if (ele.style.containIntrinsicSize) {
  2364. if (ele.offsetHeight) self.preVisibleHeight = ele.offsetHeight;
  2365. if (init) {
  2366. ele.style.contentVisibility = "visible";
  2367. self.visibilityItems.push(ele);
  2368. self.visibleIndex++;
  2369. } else {
  2370. ele.style.contentVisibility = emuIframe ? "visible" : "auto";
  2371. }
  2372. }
  2373. }
  2374. }
  2375. });
  2376. }
  2377. }
  2378.  
  2379. clearAddedElements() {
  2380. if (this.addedElePool && this.addedElePool.length) {
  2381. this.addedElePool.forEach(ele => {
  2382. if (ele.parentNode) ele.parentNode.removeChild(ele);
  2383. });
  2384. }
  2385. this.addedElePool = [];
  2386. sideController.remove();
  2387. }
  2388.  
  2389. linkHasHref(link) {
  2390. return link.href && link.href.replace && !this.hrefIsJs(link.href);
  2391. }
  2392.  
  2393. hrefIsJs(href) {
  2394. return /^(javascript|#|$)/.test(href.trim().replace("#p{", "").replace(location.href, ""));
  2395. }
  2396.  
  2397. async querySelectorList(source, list, defaultView) {
  2398. for (let i = 0; i < list.length; i++) {
  2399. await sleep(1);
  2400. let sel = list[i];
  2401. let result = getAllElements(sel, source);
  2402. if (result.length > 0) {
  2403. if (defaultView) {
  2404. for (let i = result.length - 1; i >= 0; i--) {
  2405. let ele = result[i];
  2406. if (isVisible(ele, defaultView)) return ele;
  2407. }
  2408. }
  2409. return result[result.length - 1];
  2410. }
  2411. }
  2412. return null;
  2413. }
  2414.  
  2415. verifyElement(ele) {
  2416. let verifyHandler = e => {
  2417. if (e.nodeType == 9) return true;
  2418. if (e.style.display === "none" || e.getAttribute("aria-disabled") === "true") {
  2419. return false;
  2420. }
  2421. if (e.className) {
  2422. if (/slick|slide|gallery|disabled\s*$/i.test(e.className)) {
  2423. return false;
  2424. } else if (e.classList) {
  2425. if (e.classList.contains('disabled') || e.classList.contains('active')) {
  2426. return false;
  2427. }
  2428. }
  2429. }
  2430. let ariaLabel = e.getAttribute("aria-label");
  2431. if (ariaLabel && /slick|slide|gallery/i.test(ariaLabel)) return false;
  2432. return true;
  2433. };
  2434. if (!ele) return false;
  2435. let i = 0;
  2436. while (ele && i++ < 6) {
  2437. if (!verifyHandler(ele)) return false;
  2438. ele = ele.parentNode;
  2439. }
  2440. return true;
  2441. }
  2442.  
  2443. async getPage(doc, exist) {
  2444. if (document.documentElement.className.indexOf && document.documentElement.className.indexOf('discourse') !== -1) return {};
  2445. let body = getBody(doc);
  2446. let canSave = false;//發現頁碼選擇器在其他頁對不上,還是別保存了
  2447. let url = this.curUrl.slice(0, 250).replace("index.php?", "?");
  2448. let _url = url.replace(/\.s?html?$/i, "").toLowerCase();
  2449. let pageNum = 1, preStr = "", afterStr = "";
  2450. let pageTwoReg = /^[\/\?&]?[_-]?(p|page)?=?\/?2(\/[^\/]*$|\?|&|$)/i;
  2451. let pageMatch1 = url.match(/(.*[\?&]p(?:age)?=)(\d+)($|[#&].*)/i);
  2452. let doubtTextReg = /^\s*(»|>>)\s*$/;
  2453. if (pageMatch1) {
  2454. preStr = pageMatch1[1];
  2455. pageNum = parseInt(pageMatch1[2]);
  2456. afterStr = pageMatch1[3];
  2457. } else {
  2458. let pageMatch2 = url.match(/(.*[a-z\/\-_](?:p|page)?\/?)(\d+)(\.s?html?$|\/?$)/i);
  2459. if (pageMatch2) {
  2460. preStr = pageMatch2[1];
  2461. pageNum = parseInt(pageMatch2[2]);
  2462. afterStr = pageMatch2[3];
  2463. if (/^\/?$/.test(afterStr) && !/(p(age)?|_|\-|\/)$/.test(preStr)) {
  2464. preStr = "";
  2465. afterStr = "";
  2466. }
  2467. }
  2468. }
  2469. if (pageNum > 999) {
  2470. pageNum = 1;
  2471. preStr = "";
  2472. afterStr = "";
  2473. }
  2474. let curPage = doc, i, cur, jsNext;
  2475. let next1, next2, next3, next4, nextJs1, nextJs2;
  2476. let selectorList = [
  2477. ".page-next>a",
  2478. "a.next_page",
  2479. "#next_page",
  2480. ".curPage+a",
  2481. ".nextPage",
  2482. ".pagination-next>a",
  2483. "a[data-pagination=next]",
  2484. ".pageButtonsCurrent+a",
  2485. "a[class*=nextpage]",
  2486. "li.page-current+li>a",
  2487. "[class^=pag] a[rel=next]",
  2488. "[class^=Pag] [aria-label=next]",
  2489. "[aria-label='Next Page']",
  2490. "[aria-label='Next page']",
  2491. "[aria-label='next page']",
  2492. ".pagination-nav__item--next>a",
  2493. "a.pageright",
  2494. ".page-numbers.current+a",
  2495. "a.page-numbers.next",
  2496. "body [class*=pagination] li.active+span+li>a",
  2497. "body [class*=pagination] li.active+li>a",
  2498. "body [class^=pag] .current+a",
  2499. ".page_current+a",
  2500. "input[value='next']",
  2501. "input[value='Next page']",
  2502. "input[value='下一页']",
  2503. "input[value='下一頁']",
  2504. "a#pb_next",
  2505. "a#rightFix",
  2506. "a#btnPreGn",
  2507. "a.page-next",
  2508. "a.pages-next",
  2509. "a.page.right",
  2510. ".paging>.active+.item",
  2511. "a#next",
  2512. ".next>a",
  2513. ".next>button",
  2514. "a[alt=next]",
  2515. ".pg_area>em+a",
  2516. "button.next:not([disabled])",
  2517. ".btn_next:not([disabled])",
  2518. ".btn-next:not([disabled])",
  2519. "a#linkNext",
  2520. "a[class*=page__next]",
  2521. "[class*=pager]>a.next",
  2522. "[class*=pagination-next]>a",
  2523. "[class*=pagination-next]>button",
  2524. "[class*=page--current]+li>a",
  2525. "[class*=Pages]>.curr+a",
  2526. ".page>em+a",
  2527. '//button[contains(@class, "Page")][text()="Next"]',
  2528. '//button[contains(@class, "page")][text()="next"]'
  2529. ];
  2530. let next = await this.querySelectorList(body, selectorList, doc.defaultView);
  2531. if (!next) {
  2532. await sleep(1);
  2533. let nexts = body.querySelectorAll("a.next");
  2534. const prevReg = /^\s*([上前首尾]|previous)/i;
  2535. for (i = 0; i < nexts.length; i++) {
  2536. let n = nexts[i];
  2537. if (this.verifyElement(n) && this.linkHasHref(n) && !prevReg.test(n.innerText.trim())) {
  2538. next = n;
  2539. break;
  2540. }
  2541. }
  2542. }
  2543. if (next) {
  2544. let innerText = next.innerText;
  2545. let isJs = !this.linkHasHref(next);
  2546. if (innerText && nextTextReg2.test(innerText.trim())) {
  2547. if (isJs) {
  2548. if (this.verifyElement(next)) {
  2549. nextJs2 = next;
  2550. }
  2551. } else {
  2552. next2 = next;
  2553. }
  2554. next = null;
  2555. } else {
  2556. if (isJs) {
  2557. if (this.verifyElement(next)) {
  2558. jsNext = next;
  2559. }
  2560. next = null;
  2561. }
  2562. }
  2563. }
  2564. if (!next) {
  2565. await sleep(1);
  2566. next = body.querySelector("a.curr+a") ||
  2567. body.querySelector("div.wp-pagenavi>span.current+a,div.page-nav>span.current+a,div.article-paging>span+a") ||
  2568. body.querySelector(".number>ul>li.active+li>a");
  2569. }
  2570. if (!next) {
  2571. await sleep(1);
  2572. let pageDiv = body.querySelector(".pages>ul,.page_no>ul");
  2573. if (pageDiv) {
  2574. cur = pageDiv.querySelector("li>b,li>strong");
  2575. if (cur) next = cur.parentNode.nextElementSibling;
  2576. if (next) next = next.querySelector("a");
  2577. }
  2578. }
  2579. if (!next) {
  2580. await sleep(1);
  2581. next = body.querySelector(".pages>a[href='javascript:;']+a");
  2582. if (next && (next.href === "javascript:;" || next.getAttribute("href") === "#")) next = null;
  2583. }
  2584. if (!next) {
  2585. await sleep(1);
  2586. let pageDiv = body.querySelector(".pagination");
  2587. if (pageDiv) {
  2588. cur = pageDiv.querySelector("[class*=current],.page-selected");
  2589. if (cur) next = cur.parentNode.nextElementSibling;
  2590. if (next) next = next.querySelector("a");
  2591. }
  2592. }
  2593. if (!next) {
  2594. await sleep(1);
  2595. let pageDivs = body.querySelectorAll("[class*=pagination],[class*=Pagination]");
  2596. if (pageDivs && pageDivs.length) {
  2597. for (let i = pageDivs.length - 1; i >= 0; i--) {
  2598. let p = pageDivs[i];
  2599. if (/(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)/i.test(p.title || p.value || '')) {
  2600. next = p.querySelector("a,button,[type='button']") || p;
  2601. break;
  2602. } else if (/^(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)$/i.test((p.innerText || '').trim())) {
  2603. next = p.querySelector("a,button,[type='button']") || p;
  2604. break;
  2605. }
  2606. }
  2607. if (next && !this.linkHasHref(next)) {
  2608. if (!jsNext) jsNext = next;
  2609. next = null;
  2610. }
  2611. }
  2612. }
  2613. if (!next) {
  2614. let isApp = !!body.querySelector("main#app");
  2615. let aTags = body.querySelectorAll("a,button,[type='button']");
  2616. for (i = aTags.length - 1; i >= 0; i--) {
  2617. if (next1) break;
  2618. if (i % 100 === 0) {
  2619. await sleep(1);
  2620. }
  2621. let aTag = aTags[i];
  2622. let title = aTag.title || "";
  2623. let value = aTag.value || "";
  2624. let innerText = aTag.innerText || "";
  2625. if (innerText === "" || (title !== "" && title.length < innerText.length)) {
  2626. innerText = title;
  2627. }
  2628. if (innerText === "" || (value !== "" && value.length < innerText.length)) {
  2629. innerText = value;
  2630. }
  2631. if (innerText !== "") {
  2632. if (innerText === "§") continue;
  2633. innerText = innerText.trim();
  2634. if (innerText.length > 80) continue;
  2635. }
  2636. if (!this.verifyElement(aTag)) continue;
  2637. if (aTag.dataset && aTag.dataset.preview) continue;
  2638. let availableHref = aTag.href && aTag.href.length < 250 && /^http/.test(aTag.href);
  2639. if (availableHref && /next\-?(page)?$|\/video\/|\/vod\/play\//i.test(aTag.href)) continue;
  2640. if (compareNodeName(aTag.parentNode, ["blockquote"])) continue;
  2641. if (aTag.previousElementSibling && /\b(play|volume)\b/.test(aTag.previousElementSibling.className)) continue;
  2642. if (aTag.nextElementSibling && /\b(play|volume)\b/.test(aTag.nextElementSibling.className)) continue;
  2643. let isJs = !this.linkHasHref(aTag);
  2644. if (exist && isJs && !aTag.offsetParent) continue;
  2645. if (innerText) {
  2646. innerText = innerText.split(/\n/)[0].replace(/ /g, '');
  2647. if (isJs && /^(»|>>|>|›|→|❯)$/.test(innerText)) continue;
  2648. if (innerText && innerText.length <= 25) {
  2649. if (!next1) {
  2650. if (nextTextReg1.test(innerText)) {
  2651. if (isJs) {
  2652. if (!nextJs1) nextJs1 = aTag;
  2653. } else {
  2654. next1 = aTag;
  2655. }
  2656. }
  2657. }
  2658. if (!next4) {
  2659. if (!next2) {
  2660. if (nextTextReg2.test(innerText) || /nextpage|pager\-older/i.test(aTag.className) || /^(»|>>)$/.test(innerText)) {
  2661. if (isJs) {
  2662. if (!nextJs2) nextJs2 = aTag;
  2663. } else {
  2664. next2 = aTag;
  2665. }
  2666. }
  2667. }
  2668. if (!isApp && !next3 && !isJs) {
  2669. if (/^(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)$/i.test(aTag.textContent) && aTag.parentNode.hasAttribute && !aTag.parentNode.hasAttribute("jsaction")) {
  2670. next3 = aTag;
  2671. }
  2672. }
  2673. }
  2674. }
  2675. }
  2676. if (isJs) continue;
  2677. if (!next4) {
  2678. let prevEle = aTag.previousElementSibling;
  2679. if (prevEle && compareNodeName(prevEle, ["b", "span", "strong"])) {
  2680. if (/^\d+$/.test(aTag.innerText.trim()) && /^\d+$/.test(prevEle.innerText.trim()) && parseInt(aTag.innerText) === parseInt(prevEle.innerText) + 1) {
  2681. next4 = aTag;
  2682. }
  2683. }
  2684. }
  2685. if (urlWillChange) continue;
  2686. if (!next4 && availableHref) {
  2687. if (aTag.href.indexOf(location.hostname) === -1) continue;
  2688. let _aHref = aTag.href.replace("?&", "?").replace("index.php?", "?").toLowerCase();
  2689. if (preStr || afterStr) {
  2690. let _aHrefTrim = _aHref;
  2691. if (preStr) _aHrefTrim = _aHrefTrim.replace(preStr, "");
  2692. if (afterStr) _aHrefTrim = _aHrefTrim.replace(afterStr, "");
  2693. if (_aHrefTrim == pageNum + 1) {
  2694. next4 = aTag;
  2695. }
  2696. } else if (this.curUrl !== aTag.href) {
  2697. _aHref = _aHref.replace(/\.s?html?$/i, "");
  2698. if (_aHref.indexOf(_url) !== -1) {
  2699. let pageTwoMatch = _aHref.replace(_url, "").match(pageTwoReg);
  2700. if (pageTwoMatch) {
  2701. afterStr = pageTwoMatch[2];
  2702. next4 = aTag;
  2703. }
  2704. }
  2705. }
  2706. if (next4 && !/page/.test(next4.href)) {
  2707. let curHref = next4.getAttribute("href");
  2708. let curPageReg = new RegExp("(.*)" + (pageNum + 1) + afterStr.replace(/([\.\?])/g, '\\$1'));
  2709. let otherPageHref = curHref.replace(curPageReg, `$1${pageNum}${afterStr}`);
  2710. let otherPageEle = body.querySelector(`a[href='${otherPageHref}']`);
  2711. if (!otherPageEle) {
  2712. otherPageHref = curHref.replace(curPageReg, `$1${pageNum + 2}${afterStr}`);
  2713. otherPageEle = body.querySelector(`a[href='${otherPageHref}']`);
  2714. }
  2715. if (otherPageEle) {
  2716. let parent = otherPageEle.parentNode;
  2717. if (parent && parent.parentNode) {
  2718. parent = parent.parentNode;
  2719. if (parent.parentNode) {
  2720. parent = parent.parentNode;
  2721. }
  2722. }
  2723. if (parent && parent.contains(next4) && !/^\d+$/.test(next4.innerText.trim())) {
  2724. next4 = null;
  2725. }
  2726. }
  2727. }
  2728. }
  2729. }
  2730. if (next2 && doubtTextReg.test(next2.innerText)) {
  2731. next2 = this.verifyNext(next2, doc, false);
  2732. }
  2733. if (nextJs2 && doubtTextReg.test(nextJs2.innerText)) {
  2734. nextJs2 = this.verifyNext(nextJs2, doc, true);
  2735. }
  2736. if (next3) {
  2737. next3 = this.verifyNext(next3, doc, false);
  2738. }
  2739. }
  2740. if (!next) next = next1 || next4 || next3 || next2;
  2741. if (!next && location.pathname + location.search !== "/") {
  2742. next = jsNext || nextJs1 || nextJs2;
  2743. if (next && next.parentNode.className && next.parentNode.className.indexOf && next.parentNode.className.indexOf('tab') !== -1) next = null;
  2744. }
  2745. if (next && next.classList && (next.classList.contains("results-more") || next.classList.contains("no"))) next = null;
  2746. if (next && next.hasAttribute && next.hasAttribute("disabled")) next = null;
  2747. if (next && next.parentNode.href && compareNodeName(next.parentNode, ["a"])) next = next.parentNode;
  2748. return {next:next, canSave:canSave};
  2749. }
  2750.  
  2751. verifyNext(next, doc, isJs) {
  2752. if (!next) return null;
  2753. if (!isJs) {
  2754. let href = next.getAttribute("href");
  2755. if (href && !/\d/.test(next.getAttribute("href"))) {
  2756. return null;
  2757. }
  2758. }
  2759. if (next.previousElementSibling && compareNodeName(next.previousElementSibling, ["br"])) return null;
  2760. let eles = [];
  2761. if (next.innerText && next.innerText.indexOf("\n") === -1) {
  2762. eles = getAllElements(`//${next.nodeName}[text()='${next.innerText}']`, doc);
  2763. }
  2764. if (eles.length >= 2 && eles[0].href !== eles[1].href) {
  2765. next = null;
  2766. } else if (doc === document) {
  2767. let left = getElementLeft(next);
  2768. if (left < 20 || (document.documentElement.scrollWidth > 500 && left < 250)) {
  2769. next = null;
  2770. } else {
  2771. let top = getElementTop(next);
  2772. if (top < 20 || (left < window.innerWidth / 3 && top < window.innerHeight / 3)) {
  2773. next = null;
  2774. } else {
  2775. let bottom = top + next.offsetHeight || 0;
  2776. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  2777. if (scrollH - bottom < 10) next = null;
  2778. }
  2779. }
  2780. }
  2781. return next;
  2782. }
  2783.  
  2784. canonicalUri(src) {
  2785. if (!src) {
  2786. return "";
  2787. }
  2788. if (src.charAt(0) === "#") return this.curUrl + src;
  2789. if (src.charAt(0) === "?") return this.curUrl.replace(/^([^\?#]+).*/, "$1" + src);
  2790. let origin = location.protocol + '//' + location.host;
  2791. let url = this.basePath || origin;
  2792. url = url.replace(/(\?|#).*/, "");
  2793. if (/https?:\/\/[^\/]+$/.test(url)) url = url + '/';
  2794. if (url.indexOf("http") !== 0) url = origin + url;
  2795. var root_page = /^[^\?#]*\//.exec(url)[0],
  2796. root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  2797. absolute_regex = /^\w+\:\/\//;
  2798. this.updateUrl = false;
  2799. while (src.indexOf("../") === 0) {
  2800. src = src.substr(3);
  2801. root_page = root_page.replace(/\/[^\/]+\/$/, "/");
  2802. this.updateUrl = true;
  2803. }
  2804. src = src.replace(/\.\//, "");
  2805. if (/^\/\/\/?/.test(src)) {
  2806. src = location.protocol + src;
  2807. }
  2808. return (absolute_regex.test(src) ? src : ((src.charAt(0) === "/" ? root_domain : root_page) + src));
  2809. }
  2810.  
  2811. getLinkByPage(url, pageNum) {
  2812. if (!url) return null;
  2813. if (this.curSiteRule.pageNum) {
  2814. let result = this.curSiteRule.pageNum;
  2815. let strMatch = result.match(/\{.*?}/);
  2816. if (!strMatch) return null;
  2817. let urlReg = new RegExp("(" + result.replace(strMatch[0], ")\\d+(") + ")", "i");
  2818. let code = strMatch[0].replace(/^{/, "").replace(/}$/, "").replace(/\$p/g, pageNum);
  2819. if (code === pageNum) {
  2820. result = url.replace(urlReg, "$1" + code + "$2");
  2821. } else {
  2822. try {
  2823. code = Function('"use strict";return ' + code)();
  2824. if (code && code % 1 == 0) {
  2825. result = url.replace(urlReg, "$1" + code + "$2");
  2826. } else return null;
  2827. } catch(e) {
  2828. debug(e);
  2829. }
  2830. }
  2831. if (result != url) {
  2832. return result;
  2833. }
  2834. }
  2835. return url.replace(/([&\/\?](p=|page[=\/_-]?))\d+/i, "$1" + pageNum).replace(/([_-])\d+\./i, "$1" + pageNum + ".");
  2836. }
  2837.  
  2838. getPageNumFromUrl(url, defaultPage) {
  2839. if (!url) return defaultPage;
  2840. if (this.curSiteRule.pageNum) {
  2841. let result = this.curSiteRule.pageNum;
  2842. let strMatch = result.match(/\{.*?}/);
  2843. if (!strMatch) return defaultPage;
  2844. let urlReg = new RegExp(".*" + result.replace(strMatch[0], "(\\d+)") + ".*", "i");
  2845. let curShowNum = url.replace(urlReg, "$1");
  2846. if (curShowNum !== url) {
  2847. let code = strMatch[0].replace(/^{/, "").replace(/}$/, "");
  2848. if (code === "$p") {
  2849. return curShowNum;
  2850. } else {
  2851. try {
  2852. let page1 = parseInt(Function('"use strict";return ' + code.replace("$p", "0"))());
  2853. let page2 = parseInt(Function('"use strict";return ' + code.replace("$p", "1"))());
  2854. let numGap = page2 - page1;
  2855. let _page = (parseInt(curShowNum) - page1) / numGap;
  2856. if (_page && _page % 1 === 0) return _page;
  2857. else {
  2858. this.curSiteRule.pageNum = null;
  2859. return defaultPage;
  2860. }
  2861. } catch(e) {
  2862. debug(e);
  2863. }
  2864. }
  2865. } else {
  2866. return defaultPage;
  2867. }
  2868. }
  2869. let pageNum = url.replace(/.*[&\/\?](p=|page[=\/_-]?)(\d+).*/i, "$2");
  2870. return pageNum === url ? defaultPage : (pageNum.length > 4 ? defaultPage : pageNum);
  2871. }
  2872.  
  2873. async getNextLink(doc, exist) {
  2874. let nextLink = null, page, href;
  2875. let getNextLinkByForm = (form, submitBtn, n) => {
  2876. let params = [];
  2877. let formData = new FormData(form);
  2878. if (submitBtn && submitBtn.getAttribute) {
  2879. let btnValue, btnName;
  2880. btnName = submitBtn.getAttribute("name");
  2881. btnValue = submitBtn.getAttribute("value");
  2882. if (btnName && btnValue) params = [btnName + "=" + encodeURIComponent(btnValue)];
  2883. }
  2884. for (let [key, value] of formData) {
  2885. if (n && /^(p|page)$/i.test(key)) {
  2886. params.push(key + '=' + n);
  2887. } else {
  2888. params.push(key + '=' + encodeURIComponent(value));
  2889. }
  2890. }
  2891. params = params.join('&');
  2892. return form.action + (form.action.indexOf('?') === -1 ? '?' : '&') + params + (form.method === 'post' ? '#p{' + params + '}' : '');
  2893. };
  2894. if (this.curSiteRule.pageElementByJs) {
  2895. this.nextLinkHref = "#";
  2896. return true;
  2897. } else if (this.curSiteRule.nextLinkByJs) {
  2898. try {
  2899. let over = _url => {};
  2900. let targetUrl = await ((typeof this.curSiteRule.nextLinkByJs === 'function') ? this.curSiteRule.nextLinkByJs : new AsyncFunction("doc", '"use strict";' + this.curSiteRule.nextLinkByJs))(doc);
  2901. if (targetUrl) nextLink = {href: targetUrl};
  2902. } catch(e) {
  2903. debug(e);
  2904. }
  2905. } else if (this.curSiteRule.nextLinkByUrl) {
  2906. let targetUrl = this.curUrl.replace(new RegExp(this.curSiteRule.nextLinkByUrl[0], "i"), this.curSiteRule.nextLinkByUrl[1]);
  2907. if (targetUrl !== this.curUrl) {
  2908. let includeSel = this.curSiteRule.nextLinkByUrl[2];
  2909. let excludeSel = this.curSiteRule.nextLinkByUrl[3];
  2910. if (includeSel) {
  2911. includeSel = includeSel.trim();
  2912. if (!getElement(includeSel, doc)) {
  2913. this.nextLinkHref=false;
  2914. return null;
  2915. }
  2916. }
  2917. if (excludeSel) {
  2918. excludeSel = excludeSel.trim();
  2919. if (getElement(excludeSel, doc)) {
  2920. this.nextLinkHref=false;
  2921. return null;
  2922. }
  2923. }
  2924. let reps = targetUrl.match(/{.*?}/g);
  2925. if (reps) {
  2926. reps.forEach(rep => {
  2927. let code = rep.replace("{", "").replace("}", "").replace(/\(\)/g, "0");
  2928. let result = code.match(/^(\d*)\+1$/);
  2929. if (result) {
  2930. result = parseInt(result[1] || 1) + 1;
  2931. } else {
  2932. try {
  2933. result = Function('"use strict";return ' + code)();
  2934. } catch(e) {
  2935. debug(e);
  2936. }
  2937. }
  2938. targetUrl = targetUrl.replace(rep, result);
  2939. });
  2940. }
  2941. }
  2942. nextLink = {href: targetUrl};
  2943. } else if (typeof this.curSiteRule.nextLink !== 'undefined') {
  2944. let nextLinkSel = this.curSiteRule.nextLink;
  2945. if (nextLinkSel != 0) {
  2946. if (Array && Array.isArray && Array.isArray(nextLinkSel)) {
  2947. nextLink = getElement(nextLinkSel[nextIndex], doc, null, true);
  2948. if (!nextLink && curPage === 1 && nextIndex !== 0) {
  2949. nextIndex = 0;
  2950. nextLink = getElement(nextLinkSel[nextIndex], doc, null, true);
  2951. }
  2952. } else nextLink = getElement(nextLinkSel, doc, null, true);
  2953. }
  2954. if (nextLink && (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2)) {
  2955. let form = doc.querySelector('#search-form');
  2956. if (!nextLink.href && nextLink.hasAttribute && nextLink.hasAttribute("onclick") && form) {
  2957. if (/^\d+$/.test(nextLink.innerText)) {
  2958. nextLink.href = getNextLinkByForm(form, nextLink, nextLink.innerText);
  2959. }
  2960. } else if (compareNodeName(nextLink, ["input"]) || nextLink.type === "submit") {
  2961. form = nextLink.parentNode;
  2962. while (form) {
  2963. if (compareNodeName(form, ["form"])) break;
  2964. else form = form.parentNode;
  2965. }
  2966. if (form) {
  2967. nextLink.href = getNextLinkByForm(form, nextLink);
  2968. }
  2969. }
  2970. if (nextLink.href && this.curSiteRule.action != 0) {
  2971. nextLink.href = nextLink.href.replace(/#p{.*/, "");
  2972. }
  2973. }
  2974. } else {
  2975. page = await this.getPage(doc, exist);
  2976. nextLink = page.next;
  2977. if (nextLink) {
  2978. if (compareNodeName(nextLink, ["input"]) || nextLink.type === "submit") {
  2979. if (!/next/i.test(nextLink.getAttribute("onclick"))) {
  2980. let form = nextLink.parentNode;
  2981. while (form) {
  2982. if (compareNodeName(form, ["form"])) break;
  2983. else form = form.parentNode;
  2984. }
  2985. if (form) {
  2986. nextLink.href = getNextLinkByForm(form, nextLink);
  2987. }
  2988. }
  2989. }
  2990. let parent = nextLink;
  2991. while (parent && !compareNodeName(parent, ["body"])) {
  2992. if (parent.hasAttribute && parent.hasAttribute("disabled")) {
  2993. this.nextLinkHref = false;
  2994. return null;
  2995. }
  2996. if (parent.className && parent.classList) {
  2997. if (parent.classList.contains("noClick") || parent.classList.contains("no-pages") || parent.classList.contains("disabled")) {
  2998. this.nextLinkHref = false;
  2999. return null;
  3000. }
  3001. }
  3002. if (parent.style && parent.style.display === "none") {
  3003. this.nextLinkHref = false;
  3004. return null;
  3005. }
  3006. parent = parent.parentNode;
  3007. }
  3008. if (doc === document) {
  3009. if (!this.linkHasHref(nextLink)) {
  3010. if ((clickedSth && this.curSiteRule.smart) || !isVisible(nextLink, _unsafeWindow)) {
  3011. this.nextLinkHref = false;
  3012. return null;
  3013. }
  3014. let video = document.querySelector("video,iframe[id*=play],[id*=play]>iframe,iframe[src*=player],iframe[src*=m3u8]");
  3015. if (video) {
  3016. if (video.offsetParent && video.name !== 'pagetual-iframe') {
  3017. let scrollWidth = video.scrollWidth || video.offsetWidth;
  3018. let scrollHeight = video.scrollHeight || video.offsetHeight;
  3019. if (compareNodeName(video, ["iframe"])) {
  3020. } else if (scrollWidth > 100 && scrollHeight > 100) {
  3021. let winWidth = window.innerWidth || document.documentElement.clientWidth;
  3022. let winHeight = window.innerHeight || document.documentElement.clientHeight;
  3023. if (scrollWidth > winWidth>>1 && scrollHeight > winHeight>>1) {
  3024. debug("Disable when large media found");
  3025. } else {
  3026. video = null;
  3027. }
  3028. } else {
  3029. video = null;
  3030. }
  3031. } else {
  3032. video = null;
  3033. }
  3034. }
  3035. if (video) {
  3036. isPause = true;
  3037. this.clearAddedElements();
  3038. this.nextLinkHref = false;
  3039. return null;
  3040. }
  3041. }
  3042.  
  3043. let nextLinkCs = _unsafeWindow.getComputedStyle(nextLink);
  3044. if (nextLinkCs.cursor === "not-allowed") {
  3045. this.nextLinkHref = false;
  3046. return null;
  3047. }
  3048. this.initNext = nextLink;
  3049. }
  3050. let form = doc.querySelector('#search-form');
  3051. if (!nextLink.href && nextLink.hasAttribute("onclick") && form) {
  3052. if (form && /^\d+$/.test(nextLink.innerText)) {
  3053. href = getNextLinkByForm(form, nextLink, nextLink.innerText);
  3054. }
  3055. }
  3056. }
  3057. }
  3058. if (nextLink) {
  3059. if (!this.checkStopSign(nextLink, doc)) {
  3060. if (curPage > 1 && rulesData.lastPageTips) showTips(i18n("lastPage"), "", 800);
  3061. return null;
  3062. }
  3063. if (this.curSiteRule.action == 3) {
  3064. if (doc == document) debug(nextLink, 'Next link');
  3065. this.nextLinkHref = '#';
  3066. } else {
  3067. let needUrl = (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2);
  3068. if (!href) href = nextLink.href;
  3069. if (href && nextLink.getAttribute) {
  3070. let _href = nextLink.getAttribute("href");
  3071. if (_href) {
  3072. if (_href.charAt(0) === "#" || _href === "?"){
  3073. href = "#";
  3074. } else {
  3075. href = _href;
  3076. }
  3077. } else if (_href === "") {
  3078. href = _href;
  3079. }
  3080. }
  3081.  
  3082. if (needUrl && (href === "" || href === null)) {
  3083. this.nextLinkHref = false;
  3084. } else if (needUrl && /^(javascript:|#)/.test(href)) {
  3085. this.nextLinkHref = false;
  3086. } else {
  3087. this.nextLinkHref = (href && !/^(javascript:|#)/.test(href)) ? this.canonicalUri(href) : "#";
  3088. let tempUrl = this.nextLinkHref;
  3089. 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 + "#"))) {
  3090. this.nextLinkHref = false;
  3091. } else if (doc === document) {
  3092. debug(nextLink, 'Next link');
  3093. }
  3094. }
  3095. }
  3096. } else {
  3097. this.nextLinkHref = false;
  3098. }
  3099. this.nextLinkEle = nextLink;
  3100. this.preload();
  3101. return nextLink;
  3102. }
  3103.  
  3104. compareUrl(url1, url2) {
  3105. if (url1 === url2) return true;
  3106. if (!url1 || !url2) return false;
  3107. let url1Arr = url1.split("?");
  3108. let url2Arr = url2.split("?");
  3109. if (url1Arr[0] != url2Arr[0]) return false;
  3110. if (!url1Arr[1] || !url2Arr[1]) return false;
  3111. url1Arr = url1Arr[1].split("&").sort().join("&");
  3112. url2Arr = url2Arr[1].split("&").sort().join("&");
  3113. return url1Arr === url2Arr;
  3114. }
  3115.  
  3116. filterEles(doc, eles) {
  3117. let filter = this.curSiteRule.filter;
  3118. if (!filter || !eles || eles.length === 0) return;
  3119. if (eles.length === 1) {
  3120. eles = eles[0].children;
  3121. if (eles.length === 1) {
  3122. eles = eles[0].children;
  3123. }
  3124. }
  3125. if (typeof filter === "string") {
  3126. if (/^\d+$/.test(filter)) {
  3127. filter = {count: parseInt(filter)};
  3128. } else filter = {words: filter};
  3129. }
  3130. [].forEach.call(eles, ele => {
  3131. if (!ele.parentNode) return;
  3132. let canKeep = (() => {
  3133. let innerText = (ele.innerText && ele.innerText.trim()) || "";
  3134. if (filter.count) {
  3135. if (innerText.length < filter.count) return false;
  3136. }
  3137. if (filter.words) {
  3138. let wordsRegExp = new RegExp(filter.words, "i");
  3139. if (innerText && wordsRegExp.test(innerText)) return false;
  3140. }
  3141. if (filter.link) {
  3142. let linkRegExp = new RegExp(filter.link, "i");
  3143. if (compareNodeName(ele, ["a"]) && linkRegExp.test(ele.href)) return false;
  3144. let aChildren = ele.querySelectorAll("a");
  3145. for (let i = 0; i < aChildren.length; i++) {
  3146. let child = aChildren[i];
  3147. if (linkRegExp.test(child.href)) return false;
  3148. }
  3149. }
  3150. if (filter.selector) {
  3151. if (getElement(filter.selector, doc, ele)) return false;
  3152. }
  3153. return true;
  3154. })();
  3155. if (!canKeep) {
  3156. ele.parentNode.removeChild(ele);
  3157. }
  3158. });
  3159. }
  3160.  
  3161. checkStopSign(nextLink, doc) {
  3162. if (this.curSiteRule.stopSign) {
  3163. let typeArray = Array && Array.isArray && Array.isArray(this.curSiteRule.stopSign);
  3164. let typeObject = !typeArray && (this.curSiteRule.stopSign.include || this.curSiteRule.stopSign.exclude || this.curSiteRule.stopSign.pageNum);
  3165. if (typeArray || typeObject) {
  3166. let includeSel, excludeSel, curSign, maxSign;
  3167. if (typeArray) {
  3168. includeSel = this.curSiteRule.stopSign[0];
  3169. excludeSel = this.curSiteRule.stopSign[1];
  3170. curSign = this.curSiteRule.stopSign[2];
  3171. maxSign = this.curSiteRule.stopSign[3];
  3172. if (Array && Array.isArray && Array.isArray(includeSel) && !curSign) {
  3173. curSign = includeSel;
  3174. includeSel = false;
  3175. }
  3176. if (excludeSel && Array && Array.isArray && Array.isArray(excludeSel) && !maxSign) {
  3177. maxSign = excludeSel;
  3178. excludeSel = false;
  3179. }
  3180. } else {
  3181. includeSel = this.curSiteRule.stopSign.include;
  3182. excludeSel = this.curSiteRule.stopSign.exclude;
  3183. curSign = this.curSiteRule.stopSign.pageNum;
  3184. }
  3185. if (includeSel) {
  3186. includeSel = includeSel.trim();
  3187. if (!getElement(includeSel, doc)) {
  3188. isPause = true;
  3189. this.nextLinkHref = false;
  3190. return false;
  3191. }
  3192. }
  3193. if (excludeSel) {
  3194. excludeSel = excludeSel.trim();
  3195. if (getElement(excludeSel, doc)) {
  3196. isPause = true;
  3197. this.nextLinkHref = false;
  3198. return false;
  3199. }
  3200. }
  3201. if (curSign) {
  3202. if (!maxSign) maxSign = curSign.slice(2);
  3203. let currentEle = getElement(curSign[0], doc);
  3204. let maxEle = getElement(maxSign[0], doc);
  3205. if (currentEle && maxEle) {
  3206. let currentSignNum, maxSignNum;
  3207. if (/\(.*\)/.test(curSign[1])) {
  3208. currentSignNum = currentEle.innerText.match(new RegExp(curSign[1]));
  3209. if (currentSignNum) currentSignNum = currentSignNum[1];
  3210. } else if (currentEle.getAttribute) {
  3211. currentSignNum = currentEle.getAttribute(curSign[1]);
  3212. }
  3213. if (/\(.*\)/.test(maxSign[1])) {
  3214. maxSignNum = maxEle.innerText.match(new RegExp(maxSign[1]));
  3215. if (maxSignNum) maxSignNum = maxSignNum[1];
  3216. } else if (maxEle.getAttribute) {
  3217. maxSignNum = maxEle.getAttribute(maxSign[1]);
  3218. }
  3219. if (currentSignNum && maxSignNum && currentSignNum == maxSignNum) {
  3220. isPause = true;
  3221. this.nextLinkHref = false;
  3222. return false;
  3223. }
  3224. }
  3225. }
  3226. } else {
  3227. try {
  3228. let stopSign = ((typeof this.curSiteRule.stopSign === 'function') ? this.curSiteRule.stopSign : Function("doc", "nextLink", '"use strict";' + this.curSiteRule.stopSign))(doc, nextLink);
  3229. if (stopSign) {
  3230. isPause = true;
  3231. this.nextLinkHref = false;
  3232. return false;
  3233. }
  3234. } catch(e) {
  3235. debug(e);
  3236. }
  3237. }
  3238. }
  3239. return true;
  3240. }
  3241.  
  3242. preloadImageHandler() {
  3243. if (this.preloadingImage || !this.unCheckedImgs.length) return;
  3244. this.preloadingImage = true;
  3245. setTimeout(() => {
  3246. this.preloadingImage = false;
  3247. this.preloadImageHandler();
  3248. }, 10);
  3249. let iSrc = this.unCheckedImgs.shift();
  3250. let img = document.createElement('img');
  3251. img.src = iSrc;
  3252. this.preloadDiv.appendChild(img);
  3253. }
  3254.  
  3255. preload() {
  3256. if (!rulesData.preload) return;
  3257. if (this.curSiteRule.preload === 0) return;
  3258. if (!this.nextLinkHref || this.nextLinkHref == "#") return;
  3259. if (this.readyStateUnComplete) return;
  3260. if (document.readyState !== 'complete') {
  3261. this.readyStateUnComplete = true;
  3262. let self = this;
  3263. window.addEventListener("load", e => {
  3264. self.readyStateUnComplete = false;
  3265. self.preload();
  3266. });
  3267. return;
  3268. }
  3269. let self = this, url = this.nextLinkHref;
  3270. let postParams = url.match(/#p{(.*)}$/);
  3271. if (postParams) {
  3272. postParams = postParams[1];
  3273. url = url.replace(/#p{.*/, "");
  3274. }
  3275. _GM_xmlhttpRequest({
  3276. url: url,
  3277. method: postParams ? 'POST' : 'GET',
  3278. data: postParams,
  3279. overrideMimeType: 'text/html;charset=' + charset,
  3280. headers: {
  3281. 'Referer': location.href,
  3282. 'User-Agent': navigator.userAgent,
  3283. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + charset,
  3284. },
  3285. timeout: 10000,
  3286. onload: function(res) {
  3287. var doc = null;
  3288. try {
  3289. doc = document.implementation.createHTMLDocument('');
  3290. doc.documentElement.innerHTML = createHTML(res.response);
  3291. var body = getBody(doc);
  3292. if (!self.preloadDiv) {
  3293. self.preloadDiv = document.createElement('div');
  3294. self.preloadDiv.id = "pagetual-preload";
  3295. self.preloadDiv.style.cssText = 'display:none!important;';
  3296. getBody(document).appendChild(self.preloadDiv);
  3297. self.checkedImgs = {};
  3298. self.unCheckedImgs = [];
  3299. }
  3300. let code = self.curSiteRule.preloadImages;
  3301. if (code) {
  3302. let imgSrcArr = new Function("doc", '"use strict";' + code)(doc);
  3303. if (imgSrcArr && imgSrcArr.length) {
  3304. imgSrcArr.forEach(imgSrc => {
  3305. if (imgSrc && !self.checkedImgs[imgSrc]) {
  3306. self.checkedImgs[imgSrc] = true;
  3307. self.unCheckedImgs.push(imgSrc);
  3308. }
  3309. });
  3310. }
  3311. self.preloadImageHandler();
  3312. } else if (code !== 0 && code !== false) {
  3313. if (body && body.firstChild) {
  3314. self.lazyImgAction(body.children, doc);
  3315. }
  3316. [].forEach.call(doc.images, i => {
  3317. let iSrc = i.src;
  3318. if (iSrc && !self.checkedImgs[iSrc]) {
  3319. self.checkedImgs[iSrc] = true;
  3320. self.unCheckedImgs.push(iSrc);
  3321. }
  3322. });
  3323. self.preloadImageHandler();
  3324. }
  3325. }
  3326. catch(e) {
  3327. debug(e);
  3328. return;
  3329. }
  3330. }
  3331. });
  3332. }
  3333.  
  3334. getInsert(refresh) {
  3335. if (refresh) {
  3336. this.insert = null;
  3337. }
  3338. if (this.insert && this.insert.parentNode && document.documentElement.contains(this.insert)) {
  3339. return this.insert;
  3340. }
  3341. if (this.curSiteRule.insert) {
  3342. let insertSel = this.curSiteRule.insert;
  3343. if (Array && Array.isArray && Array.isArray(insertSel)) {
  3344. insertSel = insertSel[nextIndex < insertSel.length ? nextIndex : 0];
  3345. }
  3346. this.insert = getElement(insertSel, document, null, true);
  3347. } else {
  3348. this.docPageElement = null;
  3349. let pageElement = this.getPageElement(document, _unsafeWindow);
  3350. if (this.curSiteRule.smart && this.nextLinkHref == "#" && this.curSiteRule.pageElement === 'body') {
  3351. debug("Stop as jsNext & whole body");
  3352. isPause = true;
  3353. return null;
  3354. }
  3355. if (pageElement && pageElement.length > 0) {
  3356. let pEIndex = pageElement.length - 1;
  3357. let pELast = pageElement[pEIndex];
  3358. while(pELast && compareNodeName(pELast, ["link", "meta", "style", "script"])) {
  3359. pEIndex--;
  3360. pELast = pageElement[pEIndex];
  3361. }
  3362. this.insert = pELast.nextSibling ? pELast.nextSibling : pELast.parentNode.appendChild(document.createTextNode(' '));
  3363. }
  3364. }
  3365. return this.insert;
  3366. }
  3367.  
  3368. pageInit(doc, eles) {
  3369. let code = this.curSiteRule.pageInit;
  3370. if (code) {
  3371. let initFunc = ((typeof code == 'function') ? code : Function("doc", "eles", '"use strict";' + code));
  3372. let checkInit = (resolve) => {
  3373. try {
  3374. if (initFunc(doc, eles) === false) {
  3375. setTimeout(() => {
  3376. checkInit(resolve);
  3377. }, 100);
  3378. } else {
  3379. resolve(true);
  3380. }
  3381. } catch(e) {
  3382. resolve(false);
  3383. debug(e);
  3384. }
  3385. };
  3386. return new Promise((resolve) => {
  3387. checkInit(function(e) {
  3388. resolve(e)
  3389. });
  3390. })
  3391. }
  3392. }
  3393.  
  3394. pageAction(doc, eles) {
  3395. let code = this.curSiteRule.pageAction;
  3396. if (code) {
  3397. try {
  3398. ((typeof code == 'function') ? code : Function("doc", "eles", '"use strict";' + code))(doc, eles);
  3399. } catch(e) {
  3400. debug(e);
  3401. }
  3402. }
  3403. this.openInNewTab(eles);
  3404. this.replaceElement(doc);
  3405. }
  3406.  
  3407. openInNewTab(eles) {
  3408. if (openInNewTab) {
  3409. [].forEach.call(eles, ele => {
  3410. if (compareNodeName(ele, ["a"]) && ele.href && !/^(mailto:|javascript:)|#/.test(ele.href)) {
  3411. ele.setAttribute('target', openInNewTab == 1 ? '_blank' : '_self');
  3412. } else {
  3413. [].forEach.call(ele.querySelectorAll('a[href]:not([href^="mailto:"]):not([href^="javascript:"]):not([href^="#"])'), a => {
  3414. if (openInNewTab == 1) {
  3415. a.setAttribute('target', '_blank');
  3416. if (a.getAttribute('onclick') == 'atarget(this)') {
  3417. a.removeAttribute('onclick');
  3418. }
  3419. } else a.setAttribute('target', '_self');
  3420. });
  3421. }
  3422. });
  3423. }
  3424. }
  3425.  
  3426. lazyImgAction(eles, doc) {
  3427. if (!eles || eles.length == 0) return;
  3428. let lazyImgSrc = this.curSiteRule.lazyImgSrc;
  3429. if (lazyImgSrc === 0 || lazyImgSrc === '0') return;
  3430. let imgLazyAttrs = [];
  3431. 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"];
  3432. let removeProps = [];
  3433. let setLazyImg = img => {
  3434. let realSrc;
  3435. imgLazyAttrs.forEach(attr => {
  3436. realSrc = img.getAttribute(lazyImgSrc[0]);
  3437. if (realSrc) {
  3438. removeProps.forEach(prop => {
  3439. img.removeAttribute(prop.trim());
  3440. });
  3441. img.src = realSrc;
  3442. return;
  3443. }
  3444. })
  3445. if (!realSrc) {
  3446. let lazyAttr = "";
  3447. if (img.getAttribute("_src") && !img.src) {
  3448. lazyAttr = "_src";
  3449. realSrc = img.getAttribute(lazyAttr);
  3450. } else {
  3451. for (let i in lazyImgAttr) {
  3452. lazyAttr = lazyImgAttr[i];
  3453. let attrValue = img.getAttribute(lazyAttr);
  3454. if (attrValue) {
  3455. realSrc = attrValue;
  3456. break;
  3457. }
  3458. }
  3459. }
  3460. if (!realSrc && img._lazyrias && img._lazyrias.srcset) {
  3461. realSrc = img._lazyrias.srcset[img._lazyrias.srcset.length - 1];
  3462. lazyAttr = "_lazyrias";
  3463. }
  3464. if (!realSrc && img.srcset) {
  3465. lazyAttr = "srcset";
  3466. var srcs = img.srcset.split(/[xw],/i), largeSize = 0;
  3467. srcs.forEach(srci => {
  3468. let srcInfo = srci.trim().split(" "), curSize = parseInt(srcInfo[1]);
  3469. if (srcInfo[1] && curSize > largeSize) {
  3470. largeSize = curSize;
  3471. realSrc = srcInfo[0];
  3472. }
  3473. });
  3474. }
  3475. if (realSrc) {
  3476. img.src = realSrc;
  3477. img.removeAttribute("srcset");
  3478. img.removeAttribute(lazyAttr);
  3479. if (img.classList && img.classList.contains && img.classList.contains("lazy")) {
  3480. img.classList.remove("lazy");
  3481. }
  3482. if (img.style.display == "none") {
  3483. img.style.display = "";
  3484. }
  3485. if (img.style.visibility == "hidden") {
  3486. img.style.visibility = "";
  3487. }
  3488. if (img.style.opacity == 0) {
  3489. img.style.opacity = "";
  3490. }
  3491. }
  3492. }
  3493. };
  3494. if (lazyImgSrc) {
  3495. if (!Array.isArray(lazyImgSrc)) {
  3496. lazyAttrs = lazyImgSrc.split(",");
  3497. } else {
  3498. lazyAttrs = lazyImgSrc[0].split(",");
  3499. removeProps = lazyImgSrc[1].split(",");
  3500. }
  3501. }
  3502. lazyAttrs.forEach(attr => {
  3503. let attrArr = attr.split("|");
  3504. if (attrArr.length !== 2) {
  3505. imgLazyAttrs.push(attr.trim());
  3506. } else {
  3507. let selector = attrArr[0].trim();
  3508. let lazyAttr = attrArr[1].trim();
  3509. if (selector == "img") {
  3510. imgLazyAttrs.push(lazyAttr);
  3511. } else {
  3512. selector += "[" + lazyAttr + "]";
  3513. [].forEach.call(doc.querySelectorAll(selector), ele => {
  3514. ele.style.setProperty("background-image", "url(" + ele.getAttribute(lazyAttr) + ")", "important");
  3515. removeProps.forEach(prop => {
  3516. ele.removeAttribute(prop.trim());
  3517. });
  3518. });
  3519. }
  3520. }
  3521. });
  3522. [].forEach.call(doc.querySelectorAll("img,picture>source"), img => {
  3523. setLazyImg(img);
  3524. });
  3525. }
  3526.  
  3527. canListenUrlChange() {
  3528. if (this.curSiteRule && typeof this.curSiteRule.listenUrlChange === 'undefined' && this.docElementValid()) {
  3529. return false;
  3530. }
  3531. return true;
  3532. }
  3533.  
  3534. docElementValid() {
  3535. return (this.docPageElement && document.documentElement.contains(this.docPageElement[0]));
  3536. }
  3537.  
  3538. urlChanged() {
  3539. urlChanged = true;
  3540. this.clearAddedElements();
  3541. }
  3542.  
  3543. initPage(callback) {
  3544. let self = this;
  3545. if (self.initing) return;
  3546. self.initing = true;
  3547. setTimeout(() => {
  3548. self.initing = false;
  3549. }, 100);
  3550. curPage = 1;
  3551. urlChanged = false;
  3552. tryTimes = 0;
  3553. this.clearAddedElements();
  3554. this.insert = null;
  3555. this.visibilityItems = [];
  3556. this.visibleIndex = -1;
  3557. this.pageDoc = document;
  3558. this.nextLinkHref = null;
  3559. this.curUrl = location.href;
  3560. this.oldUrl = "";
  3561. this.initUrl = location.href;
  3562. this.historyUrl = "";
  3563. this.possibleCheck = 0;
  3564. let base = document.querySelector("base");
  3565. this.basePath = base ? base.href : location.href;
  3566. this.getRule(async () => {
  3567. if (self.curSiteRule.sideController === true || (self.curSiteRule.sideController !== false && rulesData.sideController)) {
  3568. isPause = manualPause;
  3569. }
  3570. if (typeof(self.curSiteRule.rate) !== "undefined") {
  3571. rate = self.curSiteRule.rate;
  3572. }
  3573. if (self.curSiteRule.enable == 0) {
  3574. debug("Stop as rule disable");
  3575. isPause = true;
  3576. _GM_registerMenuCommand(i18n("enable"), () => {
  3577. showTips(i18n("enableSiteTips"));
  3578. if(!self.customRules) {
  3579. self.customRules = [];
  3580. }
  3581. for (let i in self.customRules) {
  3582. if (self.customRules[i].url == self.curSiteRule.url) {
  3583. self.customRules.splice(i, 1);
  3584. break;
  3585. }
  3586. }
  3587. self.curSiteRule.enable = 1;
  3588. self.customRules.unshift(self.curSiteRule);
  3589. storage.setItem("customRules", self.customRules);
  3590. location.reload();
  3591. });
  3592. return;
  3593. }
  3594. if (rulesData.sideControllerAlways) {
  3595. sideController.setup();
  3596. }
  3597. //若是再亂匹配就不緩存wedata,或者只在找完本地規則之後再考慮wedata的緩存
  3598. if (self.curSiteRule.smart) {
  3599. delete self.curSiteRule.pageElement;
  3600. if (!self.possibleRule) {
  3601. self.smartRules = self.smartRules.filter(item => {return item && item.url != self.curSiteRule.url});
  3602. self.smartRules.unshift(self.curSiteRule);
  3603. if (self.smartRules.length > 100) {
  3604. self.smartRules.pop();
  3605. }
  3606. storage.setItem("smartRules", self.smartRules);
  3607. }
  3608. } else if (self.curSiteRule && self.curSiteRule.url.length > 13) {
  3609. self.addToHpRules();
  3610. }
  3611. let css = self.curSiteRule.css || rulesData.customCss;
  3612. if (css) {
  3613. let cssArr = css.split("inIframe:");
  3614. if (cssArr && cssArr.length) {
  3615. _GM_addStyle(cssArr[0]);
  3616. }
  3617. }
  3618. if (/sidesearch=(1|true)$/.test(self.curUrl)) {
  3619. openInNewTab = 0;
  3620. } else if (typeof self.curSiteRule.openInNewTab !== 'undefined') {
  3621. openInNewTab = self.curSiteRule.openInNewTab ? 1 : 2;
  3622. }
  3623. let autoClick = self.curSiteRule.autoClick;
  3624. if (autoClick) {
  3625. let autoClickBtn;
  3626. autoClickBtn = getElement(autoClick, document, null, true);
  3627. if (autoClickBtn) {
  3628. emuClick(autoClickBtn);
  3629. }
  3630. }
  3631. let code = self.curSiteRule.init;
  3632. if (code) {
  3633. try {
  3634. 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)});
  3635. } catch(e) {
  3636. debug(e);
  3637. }
  3638. }
  3639. await self.getNextLink(document, true);
  3640. if (self.curSiteRule.pageNum && self.nextLinkHref && self.nextLinkHref != "#") {
  3641. let num1st = self.getPageNumFromUrl(location.href, 1);
  3642. let num2nd = self.getPageNumFromUrl(self.nextLinkHref, 1);
  3643. if (num2nd != num1st + 1) {
  3644. self.curSiteRule.pageNum = null;
  3645. }
  3646. }
  3647. if (self.curSiteRule.smart && self.nextLinkHref == false && self.possibleRule) {
  3648. let urlReg = new RegExp(self.possibleRule.url, "i");
  3649. function checkPossible () {
  3650. if (self.possibleCheck++ < 3) {
  3651. setTimeout(() => {
  3652. if (self.curSiteRule.smart) {
  3653. var href = location.href.slice(0, 500);
  3654. if (urlReg.test(href) && self.ruleMatch(self.possibleRule)) {
  3655. self.initPage(() => {});
  3656. } else checkPossible();
  3657. }
  3658. }, 3000);
  3659. }
  3660. }
  3661. checkPossible();
  3662. }
  3663. self.refreshByClick();
  3664. if (emuIframe && emuIframe.parentNode) {
  3665. emuIframe.parentNode.removeChild(emuIframe);
  3666. emuIframe = null;
  3667. }
  3668.  
  3669. let pageElementCss = self.curSiteRule.pageElementCss || rulesData.pageElementCss;
  3670. if (pageElementCss && pageElementCss !== '0') {
  3671. self.getPageElement(document, _unsafeWindow);
  3672. }
  3673. callback();
  3674. let initRun = typeof self.curSiteRule.initRun == 'undefined' ? rulesData.initRun : self.curSiteRule.initRun;
  3675. if (self.nextLinkHref) {
  3676. sideController.setup();
  3677. if (initRun && initRun != false) {
  3678. setTimeout(() => {
  3679. nextPage();
  3680. }, 300);
  3681. }
  3682. }
  3683. });
  3684. }
  3685.  
  3686. async hookUrlSetEle(ele, doc) {
  3687. let self = this;
  3688. return new Promise((resolve) => {
  3689. let catchUrl = e => {
  3690. ele.dataset.url = self.catchedUrl;
  3691. ele.setAttribute('onclick', 'window.open(this.dataset.url)');
  3692. window.removeEventListener('pagetual_openUrl', catchUrl);
  3693. resolve();
  3694. };
  3695. window.addEventListener('pagetual_openUrl', catchUrl);
  3696. emuClick(ele, doc);
  3697. });
  3698. }
  3699.  
  3700. async hookUrl(doc) {
  3701. let sel = this.curSiteRule.hookUrl;
  3702. if (!sel) return;
  3703. let self = this;
  3704. if (!this.initHook) {
  3705. this.initHook = true;
  3706. Object.defineProperty(doc.defaultView, 'open', {
  3707. get: function () {
  3708. return (s) => {
  3709. self.catchedUrl = s;
  3710. var e = new CustomEvent('pagetual_openUrl');
  3711. window.dispatchEvent(e);
  3712. }
  3713. }
  3714. });
  3715. }
  3716. let eles = getAllElements(sel, doc);
  3717. for (let i = 0; i < eles.length; i++) {
  3718. await sleep(1);
  3719. let ele = eles[i];
  3720. if (!ele.dataset.url) {
  3721. await this.hookUrlSetEle(ele, doc);
  3722. }
  3723. }
  3724. }
  3725.  
  3726. beginLoading() {
  3727. isLoading = true;
  3728. if (targetY >= 0) {
  3729. window.scrollTo({ top: targetY, behavior: 'instant'});
  3730. targetY = -1;
  3731. }
  3732. let lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3733. ruleParser.insertElement(loadingDiv);
  3734. if (forceState == 2) {
  3735. getBody(document).appendChild(loadingDiv);
  3736. } else {
  3737. let parent = loadingDiv.parentNode;
  3738. if (compareNodeName(parent, ["tbody"])) {
  3739. parent = parent.parentNode;
  3740. }
  3741. if (compareNodeName(parent, ["table"])) {
  3742. parent.parentNode.appendChild(loadingDiv);
  3743. }
  3744. }
  3745. getBody(document).scrollTop = lastScrollTop;
  3746. document.documentElement.scrollTop = lastScrollTop;
  3747. }
  3748.  
  3749. insertElement(ele) {
  3750. if (!this.insert || !this.insert.parentNode) {
  3751. this.getInsert();
  3752. }
  3753. if (this.insert && this.insert.parentNode) {
  3754. let self = this;
  3755. if (ele.nodeName == "#document-fragment") {
  3756. [].forEach.call(ele.children, el => {
  3757. self.addedElePool.push(el);
  3758. });
  3759. } else {
  3760. this.addedElePool.push(ele);
  3761. }
  3762. if (this.curSiteRule.insertPos == 2 || this.curSiteRule.insertPos == "in") {
  3763. this.insert.appendChild(ele);
  3764. } else {
  3765. this.insert.parentNode.insertBefore(ele, this.insert);
  3766. }
  3767. }
  3768. }
  3769.  
  3770. noValidContent(url) {
  3771. if (!this.curSiteRule.nextLinkByUrl) showTips(i18n("noValidContent"), url);
  3772. }
  3773.  
  3774. async insertPage(doc, eles, url, callback, tried) {
  3775. this.oldUrl = this.curUrl;
  3776. let oldTitle = document.title;
  3777. try {
  3778. let oldTitle = this.pageDoc.title;
  3779. } catch (e) {}
  3780. this.pageDoc = doc;
  3781. this.curUrl = url;
  3782. isLoading = true;
  3783. let nextLink = await this.getNextLink(doc);
  3784. this.nextTitle = "";
  3785. if (this.curSiteRule.pageBarText) {
  3786. if (this.curSiteRule.pageBarText == 1 || this.curSiteRule.pageBarText == true) {
  3787. this.nextTitle = doc.title;
  3788. } else {
  3789. try {
  3790. this.nextTitle = ((typeof this.curSiteRule.pageBarText == 'function') ? this.curSiteRule.pageBarText : Function("doc",'"use strict";' + this.curSiteRule.pageBarText))(doc);
  3791. } catch(e) {
  3792. debug(e);
  3793. }
  3794. }
  3795. }
  3796. if (curPage == 1 && !tried && !nextLink && this.curSiteRule.smart && this.curSiteRule.pageElement && this.curSiteRule.action != 0) {
  3797. this.curSiteRule.action = 1;
  3798. this.curUrl = location.href;
  3799. isLoading = false;
  3800. return false;
  3801. }
  3802.  
  3803. if (targetY >= 0) {
  3804. window.scrollTo({ top: targetY, behavior: 'instant'});
  3805. targetY = -1;
  3806. }
  3807. let lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3808. this.getInsert();
  3809. await this.pageInit(doc, eles);
  3810. var self = this, newEles = [];
  3811. if (!eles || eles.length == 0 || !self.insert || !self.insert.parentNode) {
  3812. if (callback) callback(eles);
  3813. loadPageOver();
  3814. } else {
  3815. if (callback) callback(eles);
  3816. loadPageOver();
  3817. const collection = document.createDocumentFragment();
  3818. [].forEach.call(eles, ele => {
  3819. let newEle = ele.cloneNode(true);
  3820. let oldCanvass = ele.querySelectorAll("canvas");
  3821. let newCanvass = newEle.querySelectorAll("canvas");
  3822. if (self.updateUrl) {
  3823. [].forEach.call(newEle.querySelectorAll("img"), img => {
  3824. if (img.getAttribute("src")) img.src = self.canonicalUri(img.getAttribute("src"));
  3825. });
  3826. [].forEach.call(newEle.querySelectorAll("a"), a => {
  3827. if (a.getAttribute("href")) a.href = self.canonicalUri(a.getAttribute("href"));
  3828. });
  3829. }
  3830. for (let i = 0; i < oldCanvass.length; i++) {
  3831. let oldCanvas = oldCanvass[i];
  3832. let newCanvas = newCanvass[i];
  3833. newCanvas.getContext('2d').drawImage(oldCanvas, 0, 0);
  3834. }
  3835. if (!compareNodeName(newEle, ["style", "script"])) self.visibilityItems.push(newEle);
  3836. collection.appendChild(newEle)
  3837. newEles.push(newEle);
  3838. });
  3839. self.insertElement(collection);
  3840. }
  3841. getBody(document).scrollTop = lastScrollTop;
  3842. document.documentElement.scrollTop = lastScrollTop;
  3843. this.pageAction(doc, newEles);
  3844. let enableHistory = this.curSiteRule.history;
  3845. let enableHistoryAfterInsert = false;
  3846. if (enableHistory == 1) {
  3847. enableHistory = true;
  3848. } else if (enableHistory == 2) {
  3849. enableHistory = true;
  3850. enableHistoryAfterInsert = true;
  3851. } else if (enableHistory == 0) {
  3852. enableHistory = false;
  3853. } else {
  3854. enableHistory = rulesData.enableHistory;
  3855. enableHistoryAfterInsert = rulesData.enableHistoryAfterInsert;
  3856. }
  3857. if (enableHistory) {
  3858. this.historyUrl = enableHistoryAfterInsert ? this.curUrl : this.oldUrl;
  3859. if(this.historyUrl != location.href) {
  3860. let isJs = this.hrefIsJs(this.historyUrl);
  3861. if (!isJs) {
  3862. let historyTitle = enableHistoryAfterInsert ? doc.title : oldTitle;
  3863. _unsafeWindow.history.replaceState(undefined, historyTitle, this.historyUrl);
  3864. document.title = historyTitle;
  3865. }
  3866. }
  3867. }
  3868. isLoading = false;
  3869. return true;
  3870. }
  3871. }
  3872. var ruleParser = new RuleParser();
  3873.  
  3874. class SideController {
  3875. //static controller;
  3876. constructor() {
  3877. this.inited = false;
  3878. }
  3879.  
  3880. /*static getInstance() {
  3881. if (!SideController.controller) {
  3882. SideController.controller = new SideController();
  3883. }
  3884. return SideController.controller;
  3885. }*/
  3886.  
  3887. setup() {
  3888. if (ruleParser.curSiteRule.sideController === false) return;
  3889. if (!rulesData.sideController && !ruleParser.curSiteRule.sideController) return;
  3890. this.addToStage();
  3891. }
  3892.  
  3893. init() {
  3894. if (this.inited) return;
  3895. this.inited = true;
  3896. let self = this;
  3897. this.cssText = `
  3898. #pagetual-sideController {
  3899. position: fixed;
  3900. top: calc(50% - 83px);
  3901. left: calc(99% - 40px);
  3902. width: 40px;
  3903. border-radius: 20px;
  3904. box-shadow: rgb(0 0 0) 0px 0px 10px;
  3905. text-align: center;
  3906. background: #ffffffd0!important;
  3907. user-select: none;
  3908. z-index: 2147483646!important;
  3909. padding: 0!important;
  3910. opacity: 0.35;
  3911. transition: opacity .5s ease, background .5s, box-shadow .5s;
  3912. }
  3913. #pagetual-sideController * {
  3914. font-weight: bold;
  3915. font-family: arial;
  3916. font-style: normal;
  3917. font-size: 20px!important;
  3918. color: black!important;
  3919. line-height: normal;
  3920. float: none;
  3921. text-align: center;
  3922. }
  3923. #pagetual-sideController.stop {
  3924. -webkit-filter: invert(100%);
  3925. filter: invert(100%);
  3926. }
  3927. .pagetual-sideController-btn {
  3928. padding: 5px 0;
  3929. cursor: pointer;
  3930. transition: transform .15s ease-in-out, opacity .3s ease;
  3931. }
  3932. #pagetual-sideController .pagetual-sideController-btn:hover {
  3933. transform: scale(1.5);
  3934. color: red!important;
  3935. }
  3936. #pagetual-sideController #pagetual-sideController-move > svg {
  3937. transition: transform .3s ease;
  3938. }
  3939. #pagetual-sideController #pagetual-sideController-move > svg:hover {
  3940. transform: scale(1.2);
  3941. }
  3942. #pagetual-sideController.minSize #pagetual-sideController-move > svg {
  3943. background: white;
  3944. opacity: 0;
  3945. }
  3946. #pagetual-sideController #pagetual-sideController-move > img,
  3947. #pagetual-sideController #pagetual-sideController-move > span {
  3948. width: 35px;
  3949. height: 35px;
  3950. cursor: pointer;
  3951. }
  3952. #pagetual-sideController.minSize #pagetual-sideController-move > img,
  3953. #pagetual-sideController.minSize #pagetual-sideController-move > span {
  3954. border-radius: 50px;
  3955. text-shadow: rgb(255 255 255) 0px 0px 10px;
  3956. }
  3957. #pagetual-sideController #pagetual-sideController-pagenum {
  3958. font-size: 15px!important;
  3959. line-height: 30px;
  3960. text-align: center;
  3961. position: absolute;
  3962. right: calc(50% - 15px);
  3963. top: calc(50% - 15px);
  3964. border: 1px solid #00000099;
  3965. display: inline-block;
  3966. width: 30px;
  3967. height: 30px;
  3968. box-sizing: border-box;
  3969. border-radius: 50%;
  3970. background: white;
  3971. opacity: 0;
  3972. transition: opacity .5s ease;
  3973. pointer-events: none;
  3974. }
  3975. #pagetual-sideController.minSize #pagetual-sideController-pagenum {
  3976. opacity: 0.8;
  3977. }
  3978. #pagetual-sideController:hover {
  3979. opacity: 1;
  3980. }
  3981. #pagetual-sideController>.extra {
  3982. bottom: 170px;
  3983. left: 0px;
  3984. width: 40px;
  3985. position: absolute;
  3986. }
  3987. #pagetual-sideController>.extra>svg {
  3988. width: 40px;
  3989. height: 30px;
  3990. opacity: 0.1;
  3991. cursor: pointer;
  3992. margin: 0 0 5px 0;
  3993. transition: opacity .3s ease;
  3994. }
  3995. #pagetual-sideController.minSize>.extra>svg {
  3996. opacity: 0;
  3997. }
  3998. #pagetual-sideController>.extra>svg:hover {
  3999. opacity: 1;
  4000. }
  4001. #pagetual-sideController.minSize {
  4002. box-shadow: rgb(0 0 0 / 0%) 0px 0px 0px;
  4003. background: #00000000!important;
  4004. pointer-events: none;
  4005. }
  4006. #pagetual-sideController.minSize #pagetual-sideController-move {
  4007. pointer-events: all;
  4008. }
  4009. #pagetual-sideController.minSize .pagetual-sideController-btn {
  4010. opacity: 0;
  4011. }
  4012. `;
  4013. let frame = document.createElement("div");
  4014. frame.id = "pagetual-sideController";
  4015. frame.innerHTML = createHTML(`
  4016. <div class="extra">
  4017. <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>
  4018. <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>
  4019. </div>
  4020. <div id="pagetual-sideController-top" class="pagetual-sideController-btn">⊼</div>
  4021. <div>
  4022. <div id="pagetual-sideController-pre" class="pagetual-sideController-btn">∧</div>
  4023. <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>
  4024. <div id="pagetual-sideController-next" class="pagetual-sideController-btn">∨</div>
  4025. </div>
  4026. <div id="pagetual-sideController-bottom" class="pagetual-sideController-btn">⊻</div>
  4027. `);
  4028. frame.classList.add("stop");
  4029. let top = frame.querySelector("#pagetual-sideController-top");
  4030. let pre = frame.querySelector("#pagetual-sideController-pre");
  4031. let move = frame.querySelector("#pagetual-sideController-move");
  4032. let next = frame.querySelector("#pagetual-sideController-next");
  4033. let bottom = frame.querySelector("#pagetual-sideController-bottom");
  4034. let pagenum = frame.querySelector("#pagetual-sideController-pagenum");
  4035. let scroll = frame.querySelector("#scroll");
  4036. let loadNow = frame.querySelector("#loadNow");
  4037. if (rulesData.sideControllerScroll === false) {
  4038. scroll.style.display = "none";
  4039. }
  4040. if (rulesData.sideControllerLoadNow === false) {
  4041. loadNow.style.display = "none";
  4042. }
  4043. if (sideControllerIcon) move.innerHTML = sideControllerIcon;
  4044.  
  4045. frame.addEventListener("dblclick", e => {
  4046. e.preventDefault();
  4047. e.stopPropagation();
  4048. });
  4049.  
  4050. frame.addEventListener("mouseenter", e => {
  4051. clearTimeout(self.hideTimer);
  4052. frame.classList.remove("minSize");
  4053. });
  4054.  
  4055. frame.addEventListener("mouseleave", e => {
  4056. clearTimeout(self.hideTimer);
  4057. self.hideTimer = setTimeout(() => {
  4058. frame.classList.add("minSize");
  4059. }, 800);
  4060. });
  4061.  
  4062. document.body.addEventListener('touchstart', e => {
  4063. if (e.target === frame || frame.contains(e.target)) {
  4064. frame.classList.remove("minSize");
  4065. } else {
  4066. frame.classList.add("minSize");
  4067. }
  4068. });
  4069.  
  4070. scroll.addEventListener("click", e => {
  4071. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  4072. autoScroll = parseInt(autoScroll) || 0;
  4073. if (autoScroll < 0) autoScroll = 0;
  4074. if (autoScroll && autoScroll != autoScrollRate) {
  4075. autoScrollRate = autoScroll;
  4076. storage.setItem("autoScrollRate", autoScrollRate);
  4077. }
  4078. setListData("autoScroll", location.host + location.pathname, autoScroll);
  4079. startAutoScroll();
  4080. }, true);
  4081.  
  4082. loadNow.addEventListener("click", e => {
  4083. if (autoLoadNum != -1) {
  4084. autoLoadNum = -1;
  4085. return;
  4086. }
  4087. let loadNum = window.prompt(i18n("loadConfirm"), loadNowNum);
  4088. if (loadNum === "" || loadNum === null) return;
  4089. loadNum = Math.abs(parseInt(loadNum)) || 0;
  4090. if (loadNowNum != loadNum) {
  4091. loadNowNum = loadNum;
  4092. storage.setItem("loadNowNum", loadNowNum);
  4093. }
  4094. autoLoadNum = loadNum;
  4095. nextPage();
  4096. }, true);
  4097.  
  4098. pre.addEventListener("click", e => {
  4099. let prePageBar = getPageBar().preBar;
  4100. if (prePageBar) {
  4101. scrollToPageBar(prePageBar);
  4102. } else {
  4103. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  4104. targetY = scrollTop - (window.innerHeight || document.documentElement.clientHeight);
  4105. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4106. }
  4107. }, true);
  4108.  
  4109. next.addEventListener("click", e => {
  4110. let pageBarObj = getPageBar();
  4111. let nextPageBar = pageBarObj.nextBar;
  4112. if (nextPageBar) {
  4113. scrollToPageBar(nextPageBar);
  4114. } else {
  4115. if (pageBarObj.preBar) {
  4116. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  4117. targetY = scrollH || 9999999;
  4118. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4119. } else {
  4120. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  4121. targetY = scrollTop + (window.innerHeight || document.documentElement.clientHeight);
  4122. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4123. }
  4124. }
  4125. }, true);
  4126.  
  4127. top.addEventListener("click", e => {
  4128. getBody(document).scrollTop=0;
  4129. document.documentElement.scrollTop=0;
  4130. e.preventDefault();
  4131. e.stopPropagation();
  4132. }, true);
  4133.  
  4134. bottom.addEventListener("click", e => {
  4135. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  4136. changeStop(true);
  4137. }
  4138. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  4139. getBody(document).scrollTop = scrollH || 9999999;
  4140. document.documentElement.scrollTop = scrollH || 9999999;
  4141. e.preventDefault();
  4142. e.stopPropagation();
  4143. }, true);
  4144.  
  4145. let initX, initY, moving = false;
  4146. let removeTimer;
  4147. move.addEventListener("click", e => {
  4148. if (!moving) {
  4149. changeStop(!isPause);
  4150. }
  4151. }, true);
  4152. move.addEventListener("dblclick", e => {
  4153. clearTimeout(removeTimer);
  4154. document.removeEventListener("mousemove", mouseMoveHandler, true);
  4155. document.removeEventListener("mouseup", mouseUpHandler, true);
  4156. changeStop(!isPause);
  4157. if (isPause) {
  4158. ruleParser.hideAddedElements();
  4159. } else {
  4160. ruleParser.showAddedElements();
  4161. }
  4162. }, true);
  4163.  
  4164. move.oncontextmenu = e => {
  4165. e.preventDefault();
  4166. picker.start();
  4167. };
  4168.  
  4169. let clientX = e => {
  4170. if (e.type.indexOf('mouse') === 0) {
  4171. return e.clientX;
  4172. } else {
  4173. return e.changedTouches[0].clientX;
  4174. }
  4175. };
  4176.  
  4177. let clientY = e => {
  4178. if (e.type.indexOf('mouse') === 0) {
  4179. return e.clientY;
  4180. } else {
  4181. return e.changedTouches[0].clientY;
  4182. }
  4183. };
  4184.  
  4185. let mouseMoveHandler = e => {
  4186. if (moving) {
  4187. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  4188. let windowWidth = window.innerWidth || document.documentElement.clientWidth;
  4189. initX = (clientX(e) - 10 + 40) / windowWidth * 100;
  4190. initY = (clientY(e) - 83 + 83) / windowHeight * 100;
  4191. this.frame.style.top = `calc(${initY}% - 83px)`;
  4192. this.frame.style.left = `calc(${initX}% - 40px)`;
  4193. } else if (Math.abs(clientX(e) - initX) + Math.abs(clientY(e) - initY) > 20) {
  4194. moving = true;
  4195. clearTimeout(removeTimer);
  4196. }
  4197. };
  4198. let mouseUpHandler = e => {
  4199. clearTimeout(removeTimer);
  4200. document.removeEventListener("mousemove", mouseMoveHandler, true);
  4201. document.removeEventListener("mouseup", mouseUpHandler, true);
  4202. document.removeEventListener("touchmove", mouseMoveHandler, true);
  4203. document.removeEventListener("touchend", mouseUpHandler, true);
  4204. if (moving) {
  4205. rulesData.sideControllerPos = {x: parseInt(initX), y: parseInt(initY)};
  4206. storage.setItem("rulesData", rulesData);
  4207. }
  4208. };
  4209. let mouseDownHandler = e => {
  4210. initX = clientX(e);
  4211. initY = clientY(e);
  4212. moving = false;
  4213. clearTimeout(removeTimer);
  4214. removeTimer = setTimeout(() => {
  4215. if (e.type === "touchstart") {
  4216. picker.start();
  4217. } else {
  4218. self.remove();
  4219. }
  4220. }, 1500);
  4221. document.addEventListener("mousemove", mouseMoveHandler, true);
  4222. document.addEventListener("mouseup", mouseUpHandler, true);
  4223. document.addEventListener("touchmove", mouseMoveHandler, true);
  4224. document.addEventListener("touchend", mouseUpHandler, true);
  4225. e.stopPropagation();
  4226. e.preventDefault();
  4227. };
  4228.  
  4229. move.addEventListener("mousedown", mouseDownHandler, true);
  4230. move.addEventListener("touchstart", mouseDownHandler, { passive: false, capture: true });
  4231.  
  4232. this.frame = frame;
  4233. this.pagenum = pagenum;
  4234. if (rulesData.sideControllerPos) {
  4235. this.frame.style.top = `calc(${rulesData.sideControllerPos.y}% - 83px)`;
  4236. this.frame.style.left = `calc(${rulesData.sideControllerPos.x}% - 40px)`;
  4237. }
  4238. }
  4239.  
  4240. addToStage() {
  4241. this.init();
  4242. if (!this.styleEle || !this.styleEle.parentNode) {
  4243. this.styleEle = _GM_addStyle(this.cssText);
  4244. }
  4245. if (!isPause) {
  4246. this.frame.classList.remove("stop");
  4247. }
  4248. this.pagenum.innerHTML = createHTML(curPage);
  4249. this.frame.title = i18n("page") + curPage;
  4250. if (this.frame.parentNode) return;
  4251. getBody(document).appendChild(this.frame);
  4252. clearTimeout(this.hideTimer);
  4253. this.frame.classList.add("minSize");
  4254. }
  4255.  
  4256. remove() {
  4257. if (this.frame && this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  4258. }
  4259. }
  4260. const sideController = new SideController();
  4261.  
  4262. class NextSwitch {
  4263. //static nextSwitch;
  4264. constructor() {
  4265. this.inited = false;
  4266. }
  4267.  
  4268. /*static getInstance() {
  4269. if (!NextSwitch.nextSwitch) {
  4270. NextSwitch.nextSwitch = new NextSwitch();
  4271. }
  4272. return NextSwitch.nextSwitch;
  4273. }*/
  4274.  
  4275. init() {
  4276. if (this.inited) return;
  4277. this.inited = true;
  4278. let self = this;
  4279. this.cssText = `
  4280. #pagetual-nextSwitch {
  4281. position: fixed;
  4282. top: 10px;
  4283. left: calc(50% - 160px);
  4284. background: aliceblue;
  4285. padding: 10px;
  4286. border-radius: 5px;
  4287. text-align: center;
  4288. opacity: 0.95;
  4289. color: #161616;
  4290. z-index: 2147483647;
  4291. font-size: 16px;
  4292. box-shadow: rgb(0 0 0) 0px 0px 10px;
  4293. }
  4294. #pagetual-nextSwitch>.title {
  4295. margin: -5px 45px 10px 45px;
  4296. font-size: 20px;
  4297. font-weight: bold;
  4298. border-bottom: 1px solid black;
  4299. user-select: none;
  4300. color: orangered;
  4301. }
  4302. #pagetual-nextSwitch>.group {
  4303. display: flex;
  4304. flex-direction: column;
  4305. }
  4306. #pagetual-nextSwitch>.group>span {
  4307. color: #161616;
  4308. cursor: pointer;
  4309. margin: 3px;
  4310. font-size: larger;
  4311. }
  4312. #pagetual-nextSwitch>.group>span:hover {
  4313. color: red;
  4314. }
  4315. #pagetual-nextSwitch>.group>span.current {
  4316. border: 2px dotted red;
  4317. border-radius: 10px;
  4318. }
  4319. #pagetual-nextSwitch>.closeSwitch {
  4320. position: absolute;
  4321. top: 3px;
  4322. right: 10px;
  4323. background: none;
  4324. border: none;
  4325. vertical-align: top;
  4326. transition: transform .15s ease-in-out;
  4327. float: right;
  4328. cursor: pointer;
  4329. }
  4330. #pagetual-nextSwitch svg {
  4331. width: 30px;
  4332. height: 30px;
  4333. vertical-align: middle;
  4334. fill: #161616;
  4335. overflow: hidden;
  4336. }
  4337. #pagetual-nextSwitch button:hover {
  4338. transform: scale(1.2);
  4339. }
  4340. `;
  4341. let frame = document.createElement("div");
  4342. frame.id = "pagetual-nextSwitch";
  4343. frame.innerHTML = createHTML(`
  4344. <div class="title">${i18n("nextSwitch")}</div>
  4345. <button type="button" class="closeSwitch">
  4346. <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2754">
  4347. <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">
  4348. </path>
  4349. </svg>
  4350. </button>
  4351. <div class="group"></div>
  4352. `);
  4353. let group = frame.querySelector(".group");
  4354. let closeBtn = frame.querySelector(".closeSwitch");
  4355. closeBtn.addEventListener("click", e => {
  4356. self.close();
  4357. }, true);
  4358. this.frame = frame;
  4359. let currentSpan;
  4360. ruleParser.curSiteRule.nextLink.forEach((link, i) => {
  4361. let span = document.createElement("span");
  4362. let target = getElement(link, document);
  4363. let index = "<b>" + (i + 1) + "</b>: ";
  4364. if (target) {
  4365. let targetInner = target.innerText.trim();
  4366. span.innerHTML = index + (targetInner || link);
  4367. } else {
  4368. span.innerHTML = index + "Not Found";
  4369. }
  4370. span.title = link;
  4371. span.addEventListener("click", e => {
  4372. if (currentSpan) currentSpan.classList.remove("current");
  4373. span.classList.add("current");
  4374. currentSpan = span;
  4375. nextIndex = i;
  4376. setListData("nextSwitch", location.host, nextIndex === 0 ? "" : nextIndex);
  4377. ruleParser.curUrl += "#pagetual";
  4378. ruleParser.oldUrl = ruleParser.curUrl;
  4379. autoLoadNum = -1;
  4380. if (!ruleParser.nextLinkHref) {
  4381. isLoading = false;
  4382. }
  4383. ruleParser.getNextLink(ruleParser.pageDoc || document);
  4384. self.close();
  4385. }, true);
  4386. if (i == nextIndex) {
  4387. span.classList.add("current");
  4388. currentSpan = span;
  4389. }
  4390. group.appendChild(span);
  4391. });
  4392. }
  4393.  
  4394. start() {
  4395. this.init();
  4396. if (!this.styleEle || !this.styleEle.parentNode) {
  4397. this.styleEle = _GM_addStyle(this.cssText);
  4398. }
  4399. document.documentElement.appendChild(this.frame);
  4400. }
  4401.  
  4402. close() {
  4403. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  4404. }
  4405. }
  4406. const nextSwitch = new NextSwitch();
  4407.  
  4408. class Picker {
  4409. //static picker;
  4410. constructor() {
  4411. this.inited = false;
  4412. }
  4413.  
  4414. /*static getInstance() {
  4415. if (!Picker.picker) {
  4416. Picker.picker = new Picker();
  4417. }
  4418. return Picker.picker;
  4419. }*/
  4420.  
  4421. init() {
  4422. if (this.inited) return;
  4423. this.inited = true;
  4424. let self = this;
  4425. this.signList = [];
  4426. this.cssText = `
  4427. body.pagetual-picker,
  4428. body.pagetual-picker *:hover,
  4429. body.pagetual-picker a:hover {
  4430. cursor: crosshair !important;
  4431. }
  4432. #pagetual-picker {
  4433. position: fixed;
  4434. top: 10px;
  4435. left: calc(50% - 178px);
  4436. background: aliceblue;
  4437. padding: 10px;
  4438. border-radius: 5px;
  4439. text-align: center;
  4440. opacity: 0.95;
  4441. color: #161616;
  4442. z-index: 2147483646;
  4443. font-size: 16px;
  4444. overflow: hidden;
  4445. box-shadow: rgb(0 0 0) 0px 0px 10px;
  4446. }
  4447. #pagetual-picker * {
  4448. margin: 0;
  4449. padding: 0;
  4450. font-family: Times New Roman;
  4451. overflow: initial;
  4452. user-select: none;
  4453. line-height: unset;
  4454. min-width: unset;
  4455. min-height: unset;
  4456. }
  4457. #pagetual-picker>.title {
  4458. margin: -5px 45px 10px 45px;
  4459. font-size: 20px;
  4460. font-weight: bold;
  4461. cursor: pointer;
  4462. border-bottom: 1px solid black;
  4463. user-select: none;
  4464. color: orangered;
  4465. height: initial;
  4466. width: initial;
  4467. position: initial;
  4468. transition: transform .3s ease;
  4469. }
  4470. #pagetual-picker>.title:hover {
  4471. transform: scale(1.1);
  4472. }
  4473. #pagetual-picker button {
  4474. background: none;
  4475. border: none;
  4476. vertical-align: top;
  4477. transition: transform .15s ease-in-out;
  4478. float: right;
  4479. cursor: pointer;
  4480. overflow: hidden;
  4481. background-color: unset!important;
  4482. }
  4483. #pagetual-picker button:hover {
  4484. transform: scale(1.2);
  4485. }
  4486. #pagetual-picker>.closePicker {
  4487. position: absolute;
  4488. top: 3px;
  4489. right: 10px;
  4490. }
  4491. #pagetual-picker>.logoIcon {
  4492. position: absolute;
  4493. top: 3px;
  4494. left: 10px;
  4495. }
  4496. #pagetual-picker>.logoIcon.showSign>svg>path {
  4497. fill: gray!important;
  4498. }
  4499. #pagetual-picker textarea{
  4500. display: inline-block;
  4501. width: calc(100% - 65px);
  4502. height: 20px;
  4503. min-width: 250px;
  4504. max-width: calc(65vw - 50px);
  4505. min-height: unset;
  4506. max-height: unset;
  4507. padding: 6px 12px;
  4508. font-size: 16px;
  4509. font-weight: 400;
  4510. line-height: 1.5;
  4511. color: #495057;
  4512. background-color: #fff;
  4513. background-clip: padding-box;
  4514. border: 1px solid #ced4da;
  4515. border-radius: 4px;
  4516. transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
  4517. box-sizing: content-box;
  4518. margin-right: 5px;
  4519. resize: both;
  4520. box-shadow: 0 1px 5px 1px #ddd;
  4521. overflow-wrap: anywhere;
  4522. }
  4523. #pagetual-picker textarea:focus {
  4524. color: black;
  4525. background-color: #fff;
  4526. border-color: #80bdff;
  4527. outline: 0;
  4528. box-shadow: 0 0 0 3.2px rgb(0 123 255 / 25%);
  4529. }
  4530. #pagetual-picker [type=checkbox],
  4531. #pagetual-picker [type=radio] {
  4532. line-height: 20px;
  4533. height: 25px;
  4534. width: 25px;
  4535. margin-left: 5px;
  4536. vertical-align: middle;
  4537. appearance: auto;
  4538. display: inline-block;
  4539. position: initial;
  4540. }
  4541. #pagetual-picker [type=checkbox]:after,
  4542. #pagetual-picker [type=radio]:after,
  4543. #pagetual-picker [type=checkbox]:before,
  4544. #pagetual-picker [type=radio]:before {
  4545. border: none;
  4546. background: none;
  4547. }
  4548. #pagetual-picker label {
  4549. font-size: 18px;
  4550. line-height: 25px;
  4551. vertical-align: middle;
  4552. display: inline-block;
  4553. color: black;
  4554. position: initial;
  4555. cursor: pointer;
  4556. }
  4557. #pagetual-picker .bottom {
  4558. text-align: left;
  4559. margin: 10px 0;
  4560. width: 100%;
  4561. }
  4562. #pagetual-picker .bottom>button {
  4563. float: right;
  4564. }
  4565. #pagetual-picker svg {
  4566. width: 30px;
  4567. height: 30px;
  4568. vertical-align: middle;
  4569. fill: #161616;
  4570. overflow: hidden;
  4571. }
  4572. #pagetual-picker svg * {
  4573. pointer-events: none;
  4574. }
  4575. #pagetual-picker .allpath {
  4576. font-size: 18px;
  4577. margin: 10px auto;
  4578. max-width: 330px;
  4579. word-break: break-all;
  4580. cursor: context-menu;
  4581. overflow: hidden;
  4582. max-height: 42px;
  4583. -moz-transition:max-height 1s ease-in;
  4584. -webkit-transition:max-height 1s ease-in;
  4585. transition:max-height 1s ease-in;
  4586. color: black;
  4587. }
  4588. #pagetual-picker .allpath:hover {
  4589. max-height: calc(100vh - 130px);
  4590. overflow: auto;
  4591. }
  4592. #pagetual-picker .allpath>span.path {
  4593. cursor: pointer;
  4594. }
  4595. #pagetual-picker .allpath>span.path:hover {
  4596. opacity: 0.6;
  4597. }
  4598. #pagetual-picker .allpath>span.path:hover,
  4599. #pagetual-picker .allpath>span.path.checked {
  4600. color: orangered;
  4601. }
  4602. #pagetual-picker .moreConfig {
  4603. display: flex;
  4604. justify-content: space-between;
  4605. border-top: 1px solid;
  4606. padding-top: 10px;
  4607. width: 100%;
  4608. }
  4609. #pagetual-picker .command {
  4610. width: 100%;
  4611. color: black!important;
  4612. text-align: center;
  4613. font-size: large;
  4614. margin-top: 10px;
  4615. box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.12);
  4616. border-radius: 5px;
  4617. }
  4618. #pagetual-picker .command:hover {
  4619. color: orangered;
  4620. }
  4621. #pagetual-picker #showDetail {
  4622. float: initial;
  4623. margin-top: 10px;
  4624. }
  4625. #pagetual-picker.showDetail #showDetail {
  4626. float: right;
  4627. }
  4628. #pagetual-picker #showDetail>svg {
  4629. -moz-transition:transform 0.3s ease;
  4630. -webkit-transition:transform 0.3s ease;
  4631. transition:transform 0.3 ease;
  4632. }
  4633. #pagetual-picker.showDetail #showDetail>svg {
  4634. transform: rotate(180deg);
  4635. }
  4636. #pagetual-picker .tempRule {
  4637. display: none;
  4638. margin-top: 10px;
  4639. height: 300px;
  4640. min-height: 150px;
  4641. }
  4642. #pagetual-picker.showDetail .tempRule {
  4643. display: inline-block;
  4644. word-break: break-all;
  4645. }
  4646. #pagetual-picker #saveDetail {
  4647. display: none;
  4648. position: absolute;
  4649. bottom: 10px;
  4650. right: 8px;
  4651. }
  4652. #pagetual-picker.showDetail #saveDetail {
  4653. display: inline-block;
  4654. }
  4655. #pagetual-picker #saveDetail svg {
  4656. width: 35px;
  4657. height: 35px;
  4658. }
  4659. #pagetual-picker .addProp {
  4660. display: none;
  4661. flex-direction: column;
  4662. position: absolute;
  4663. bottom: 45px;
  4664. right: 12px;
  4665. }
  4666. #pagetual-picker.showDetail .addProp {
  4667. display: flex;
  4668. }
  4669. #pagetual-picker .addProp>button {
  4670. font-size: 30px;
  4671. font-family: Arial,sans-serif;
  4672. line-height: 35px;
  4673. color: #161616;
  4674. }
  4675. #pagetual-picker #edit{
  4676. -webkit-animation: jumpAnimation .6s 5;
  4677. animation: jumpAnimation .6s 5;
  4678. }
  4679. @keyframes jumpAnimation {
  4680. 0% {
  4681. transform: scale(1) translateY(0);
  4682. animation-timing-function: ease-out;
  4683. }
  4684. 50% {
  4685. transform: scale(1.2) translateY(-5px);
  4686. animation-timing-function: ease-in;
  4687. }
  4688. 100% {
  4689. transform: scale(1) translateY(0);
  4690. animation-timing-function: ease-out;
  4691. }
  4692. }
  4693. @-webkit-keyframes jumpAnimation {
  4694. 0% {
  4695. -webkit-transform: scale(1) translateY(0);
  4696. animation-timing-function: ease-out;
  4697. }
  4698. 50% {
  4699. -webkit-transform: scale(1.2) translateY(-5px);
  4700. animation-timing-function: ease-in;
  4701. }
  4702. 100% {
  4703. -webkit-transform: scale(1) translateY(0);
  4704. animation-timing-function: ease-out;
  4705. }
  4706. }
  4707. `;
  4708. this.mainSignDiv = this.createSignDiv();
  4709. this.allSignDiv = [];
  4710. let frame = document.createElement("div");
  4711. frame.id = "pagetual-picker";
  4712. frame.innerHTML = createHTML(`
  4713. <button title="Pagetual" type="button" class="logoIcon">
  4714. <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>
  4715. </button>
  4716. <div class="title" title="${i18n("configure")}">${i18n("picker")}</div>
  4717. <button title="${i18n("closePicker")}" type="button" class="closePicker">
  4718. <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>
  4719. </button>
  4720. <div class="allpath" title="${i18n("switchSelector")}"></div>
  4721. <div>
  4722. <textarea class="selector" spellcheck="false" name="selector" placeholder="${i18n("pickerPlaceholder")}"></textarea>
  4723. <button id="check" title="${i18n("pickerCheck")}" type="button">
  4724. <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>
  4725. </button>
  4726. </div>
  4727. <div class="bottom">
  4728. <input name="xpath" id="checkbox_id" type="checkbox" />
  4729. <label for="checkbox_id">XPath</label>
  4730. <button id="edit" title="${i18n("gotoEdit")}" type="button">
  4731. <svg viewBox="0 0 1024 1024" style="color: orangered;fill: orangered;" version="1.1" xmlns="http://www.w3.org/2000/svg">
  4732. <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">
  4733. </path>
  4734. </svg>
  4735. </button>
  4736. </div>
  4737. <div class="moreConfig">
  4738. <div title="${i18n('forceStateIframe')}">
  4739. <input name="forceState" id="forceStateIframe" type="radio" />
  4740. <label for="forceStateIframe">${i18n('iframe')}</label>
  4741. </div>
  4742. <div title="${i18n('forceStateDynamic')}">
  4743. <input name="forceState" id="forceStateDynamic" type="radio" />
  4744. <label for="forceStateDynamic">${i18n('dynamic')}</label>
  4745. </div>
  4746. <div title="${i18n('forceStateDisable')}">
  4747. <input name="forceState" id="forceStateDisable" type="radio" />
  4748. <label for="forceStateDisable">${i18n('disable')}</label>
  4749. </div>
  4750. </div>
  4751. <button id="nextSwitch" class="command" title="${i18n("nextSwitch")}" type="button">${i18n("nextSwitch")}</button>
  4752. <button id="loadNow" class="command" title="${i18n("loadNow")}" type="button">${i18n("loadNow")}</button>
  4753. <button id="autoScroll" class="command" title="${i18n("toggleAutoScroll")}" type="button"></button>
  4754. <button id="ruleRequest" class="command" title="${i18n("ruleRequest")}" type="button">${i18n("ruleRequest")}</button>
  4755. <div>
  4756. <textarea class="tempRule" spellcheck="false" placeholder="{Rule object}" title="Rule for current site"></textarea>
  4757. <button id="showDetail" title="" type="button">
  4758. <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>
  4759. </button>
  4760. <div class="addProp">
  4761. <button id="addOtherProp" title="${i18n("addOtherProp")}" type="button">+</button>
  4762. <button id="addNextSelector" title="${i18n("addNextSelector")}" type="button">></button>
  4763. <button id="addPageSelector" title="${i18n("addPageSelector")}" type="button">❏</button>
  4764. </div>
  4765. <button id="saveDetail" title="${i18n("save")}" type="button">
  4766. <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>
  4767. </button>
  4768. </div>
  4769. `);
  4770. let forceStateIframe = frame.querySelector("#forceStateIframe");//forceState 1 禁用 2 强嵌 3 动态
  4771. let forceStateDynamic = frame.querySelector("#forceStateDynamic");
  4772. let forceStateDisable = frame.querySelector("#forceStateDisable");
  4773. let clickRadio = e => {
  4774. let radio = e.currentTarget.querySelector('input');
  4775. if (radio.checked) {
  4776. forceState = "";
  4777. } else {
  4778. switch (radio.id) {
  4779. case "forceStateIframe":
  4780. forceState = 2;
  4781. break;
  4782. case "forceStateDynamic":
  4783. forceState = 3;
  4784. break;
  4785. case "forceStateDisable":
  4786. forceState = 1;
  4787. break;
  4788. default:
  4789. return;
  4790. }
  4791. }
  4792. setListData("forceState", location.host, forceState);
  4793. self.close();
  4794. setTimeout(() => {
  4795. location.reload();
  4796. }, 500);
  4797. };
  4798. forceStateIframe.parentNode.addEventListener("mousedown", clickRadio);
  4799. forceStateDynamic.parentNode.addEventListener("mousedown", clickRadio);
  4800. forceStateDisable.parentNode.addEventListener("mousedown", clickRadio);
  4801. if (forceState == 1) forceStateDisable.checked = true;
  4802. else if (forceState == 2) forceStateIframe.checked = true;
  4803. else if (forceState == 3) forceStateDynamic.checked = true;
  4804. let closeBtn = frame.querySelector(".closePicker");
  4805. let logoBtn = frame.querySelector(".logoIcon");
  4806. let title = frame.querySelector(".title");
  4807. let allpath = frame.querySelector(".allpath");
  4808. let selectorInput = frame.querySelector(".selector");
  4809. let xpath = frame.querySelector("#checkbox_id");
  4810. let checkBtn = frame.querySelector("#check");
  4811. let editBtn = frame.querySelector("#edit");
  4812. let nextSwitchBtn = frame.querySelector("#nextSwitch");
  4813. let autoScrollBtn = frame.querySelector("#autoScroll");
  4814. let loadNow = frame.querySelector("#loadNow");
  4815. let tempRule = frame.querySelector(".tempRule");
  4816. let showDetailBtn = frame.querySelector("#showDetail");
  4817. let saveDetailBtn = frame.querySelector("#saveDetail");
  4818. let addOtherProp = frame.querySelector("#addOtherProp");
  4819. let addNextSelector = frame.querySelector("#addNextSelector");
  4820. let addPageSelector = frame.querySelector("#addPageSelector");
  4821. let ruleRequestBtn = frame.querySelector("#ruleRequest");
  4822. ruleRequestBtn.addEventListener("click", e => {
  4823. _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});
  4824. }, true);
  4825. autoScrollBtn.addEventListener("click", e => {
  4826. self.close();
  4827. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  4828. autoScroll = parseInt(autoScroll) || 0;
  4829. if (autoScroll < 0) autoScroll = 0;
  4830. if (autoScroll && autoScroll != autoScrollRate) {
  4831. autoScrollRate = autoScroll;
  4832. storage.setItem("autoScrollRate", autoScrollRate);
  4833. }
  4834. setListData("autoScroll", location.host + location.pathname, autoScroll);
  4835. startAutoScroll();
  4836. }, true);
  4837. addOtherProp.addEventListener("click", e => {
  4838. let propName = prompt(i18n("propName"), "author");
  4839. if (!propName) return;
  4840. let propValue = prompt(i18n("propValue"));
  4841. if (!propValue) return;
  4842. if (propValue === "true") propValue = true;
  4843. else if (propValue === "false") propValue = false;
  4844. else if (/^\d+$/.test(propValue)) propValue = parseInt(propValue);
  4845. if (propName === "author" && propValue) {
  4846. author = propValue;
  4847. storage.setItem("author", propValue);
  4848. }
  4849. let editTemp = self.getTempRule();
  4850. if (!editTemp) return;
  4851. editTemp[propName] = propValue;
  4852. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  4853. }, true);
  4854. addNextSelector.addEventListener("click", e => {
  4855. let editTemp = self.getTempRule();
  4856. if (!editTemp) return;
  4857. let selector = self.selectorInput.value;
  4858. if (selector) {
  4859. editTemp.nextLink = selector;
  4860. }
  4861. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  4862. }, true);
  4863. addPageSelector.addEventListener("click", e => {
  4864. let editTemp = self.getTempRule();
  4865. if (!editTemp) return;
  4866. let selector = self.selectorInput.value;
  4867. if (selector) {
  4868. editTemp.pageElement = selector;
  4869. }
  4870. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  4871. }, true);
  4872. showDetailBtn.addEventListener("click", e => {
  4873. frame.classList.toggle("showDetail");
  4874. }, true);
  4875. saveDetailBtn.addEventListener("click", e => {
  4876. let editTemp = self.getTempRule(true);
  4877. if (tempRule.value && !editTemp) {
  4878. return;
  4879. }
  4880. if(!ruleParser.customRules) {
  4881. ruleParser.customRules = [];
  4882. }
  4883. ruleParser.customRules = ruleParser.customRules.filter(item => {return item.url != editTemp.url || item.name != editTemp.name});
  4884. if (tempRule.value) {
  4885. ruleParser.customRules.unshift(editTemp);
  4886. ruleParser.curSiteRule = editTemp;
  4887. } else {
  4888. ruleParser.curSiteRule = {};
  4889. isPause = true;
  4890. }
  4891. storage.setItem("customRules", ruleParser.customRules);
  4892. if (ruleParser.hpRules && ruleParser.curSiteRule && !ruleParser.curSiteRule.smart) {
  4893. ruleParser.addToHpRules(true);
  4894. }
  4895. if (window.confirm(i18n("reloadPage"))) {
  4896. setTimeout(() => {location.reload()}, 100);
  4897. }
  4898. }, true);
  4899. nextSwitchBtn.addEventListener("click", e => {
  4900. self.close();
  4901. nextSwitch.start();
  4902. }, true);
  4903. loadNow.addEventListener("click", e => {
  4904. self.close();
  4905. let loadNum = window.prompt(i18n("loadConfirm"), "1");
  4906. if (loadNum === "" || loadNum === null) return;
  4907. autoLoadNum = Math.abs(parseInt(loadNum));
  4908. nextPage();
  4909. }, true);
  4910. closeBtn.addEventListener("click", e => {
  4911. self.close();
  4912. }, true);
  4913. this.showSign = true;
  4914. logoBtn.addEventListener("click", e => {
  4915. logoBtn.classList.toggle("showSign");
  4916. self.showSign = !self.showSign;
  4917. getBody(document).classList.toggle("pagetual-picker");
  4918. }, true);
  4919. let moving = false;
  4920. let initX = 0, initY = 0, initPos = {x: 0, y: 0};
  4921. let moveHanlder = e => {
  4922. if (moving) {
  4923. frame.style.left = e.clientX - initX + "px";
  4924. frame.style.top = e.clientY - initY + "px";
  4925. e.stopPropagation();
  4926. e.preventDefault();
  4927. } else if(Math.abs(e.clientX - initPos.x) + Math.abs(e.clientY - initPos.y) > 20) {
  4928. moving = true;
  4929. }
  4930. };
  4931. let upHanlder = e => {
  4932. if (moving) {
  4933. moving = false;
  4934. } else {
  4935. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  4936. }
  4937. document.removeEventListener("mousemove", moveHanlder, true);
  4938. title.removeEventListener("mouseup", upHanlder, true);
  4939. e.stopPropagation();
  4940. e.preventDefault();
  4941. };
  4942. title.addEventListener("mousedown", e => {
  4943. initPos = {x: e.clientX, y: e.clientY};
  4944. initX = e.clientX - parseInt(getComputedStyle(frame).left);
  4945. initY = e.clientY - parseInt(getComputedStyle(frame).top);
  4946. document.addEventListener("mousemove", moveHanlder, true);
  4947. title.addEventListener("mouseup", upHanlder, true);
  4948. });
  4949. frame.addEventListener("mouseenter", e => {
  4950. if (!self.showSign || moving) return;
  4951. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  4952. self.checkInputSelector(false);
  4953. });
  4954. frame.addEventListener("mouseleave", e => {
  4955. if (!self.showSign) {
  4956. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  4957. self.clearSigns();
  4958. return;
  4959. }
  4960. if (moving) return;
  4961. document.documentElement.appendChild(self.mainSignDiv);
  4962. self.clearSigns();
  4963. });
  4964. checkBtn.addEventListener("click", e => {
  4965. self.checkInputSelector();
  4966. if (this.selectorInput.value && self.foundEle) {
  4967. debug(self.foundEle);
  4968. self.foundEle[0].scrollIntoView({ behavior: "smooth" });
  4969. _GM_setClipboard(this.selectorInput.value);
  4970. showTips(i18n("copied"));
  4971. } else showTips("Null");
  4972. });
  4973. xpath.addEventListener("click", e => {
  4974. if (!selectorInput.value) {
  4975. self.setSelectorDiv("");
  4976. return;
  4977. }
  4978. let element = getElement(selectorInput.value, document);
  4979. let selector = self.getSelectorFromEle(element);
  4980. selectorInput.value = selector;
  4981. self.setSelectorDiv(selector);
  4982. });
  4983. editBtn.addEventListener("click", e => {
  4984. rulesData.editTemp = self.getTempRule();
  4985. storage.setItem("rulesData", rulesData);
  4986. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  4987. });
  4988. editBtn.oncontextmenu = e => {
  4989. e.preventDefault();
  4990. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  4991. };
  4992. this.frame = frame;
  4993. this.xpath = xpath;
  4994. this.allpath = allpath;
  4995. this.selectorInput = selectorInput;
  4996. this.nextSwitchBtn = nextSwitchBtn;
  4997. this.autoScrollBtn = autoScrollBtn;
  4998. this.loadNow = loadNow;
  4999. this.tempRule = tempRule;
  5000. this.logoBtn = logoBtn;
  5001. let setTitleTimer;
  5002. this.moveHandler = e => {
  5003. if (!self.showSign || e.target === document) return;
  5004. let target = self.getTarget(e.target);
  5005. self.adjustSignDiv(self.mainSignDiv, target);
  5006. clearTimeout(setTitleTimer);
  5007. setTitleTimer = setTimeout(() => {
  5008. if (self.inPicker && target.hasAttributes()) {
  5009. let title = target.nodeName.toLowerCase() + "\n";
  5010. for (const attr of target.attributes) {
  5011. title += `【${attr.name}】${attr.value ? " ➡️ " + attr.value : ""}\n`;
  5012. }
  5013. getBody(document).title = title;
  5014. }
  5015. }, 100);
  5016. };
  5017. this.clickHandler = e => {
  5018. if (!self.showSign) return;
  5019. if (self.inPicker) {
  5020. e.stopPropagation();
  5021. e.preventDefault();
  5022. }
  5023. let target = self.getTarget(e.target);
  5024. let selector = self.getSelectorFromEle(target);
  5025. selectorInput.value = selector;
  5026. self.setSelectorDiv(selector);
  5027. };
  5028. }
  5029.  
  5030. getTempRule(detail) {
  5031. if (this.tempRule.value) {
  5032. try {
  5033. this.editTemp = JSON.parse(this.tempRule.value);
  5034. } catch (e) {
  5035. this.editTemp = null;
  5036. if (detail) {
  5037. let pos = e && e.message && e.message.match(/position (\d+)/);
  5038. if (pos) {
  5039. pos = parseInt(pos[1]);
  5040. this.tempRule.value = this.tempRule.value.slice(0, pos) + "➡️" + this.tempRule.value.slice(pos);
  5041. }
  5042. showTips(i18n("errorJson"));
  5043. return null;
  5044. }
  5045. }
  5046. }
  5047. if (!this.editTemp) {
  5048. if (ruleParser.curSiteRule.url && !ruleParser.curSiteRule.smart) {
  5049. this.editTemp = ruleParser.curSiteRule;
  5050. } else {
  5051. this.editTemp = {
  5052. name: document.title,
  5053. url: "^" + (location.origin + location.pathname).replace(/[^\/]*$/, "").replace(/^https?/, "https?").replace(/\./g, "\\."),
  5054. example: location.href
  5055. };
  5056. if (author) this.editTemp.author = author;
  5057. }
  5058. delete this.editTemp.from;
  5059. delete this.editTemp.type;
  5060. delete this.editTemp.updatedAt;
  5061. }
  5062. if (this.selectorInput.value && (!this.frame.classList.contains("showDetail") || !this.editTemp || !this.editTemp.pageElement)) {
  5063. if (this.foundEle && this.foundEle.length === 1) {
  5064. let foundEleRect = this.foundEle[0].getBoundingClientRect();
  5065. if (foundEleRect.height < 100) {
  5066. showTips("Next Link", "", 500);
  5067. this.editTemp.nextLink = this.selectorInput.value;
  5068. return this.editTemp;
  5069. }
  5070. }
  5071. showTips("Page Element", "", 500);
  5072. this.editTemp.pageElement = this.selectorInput.value;
  5073. }
  5074. return this.editTemp;
  5075. }
  5076.  
  5077. getTarget(ele) {
  5078. while (ele.parentNode && (ele.offsetWidth === 0 || ele.offsetHeight === 0)) {
  5079. ele = ele.parentNode;
  5080. }
  5081. return ele;
  5082. }
  5083.  
  5084. close() {
  5085. this.clearSigns();
  5086. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  5087. if (this.mainSignDiv.parentNode) this.mainSignDiv.parentNode.removeChild(this.mainSignDiv);
  5088. getBody(document).classList.remove("pagetual-picker");
  5089. getBody(document).removeEventListener("mousemove", this.moveHandler, true);
  5090. getBody(document).removeEventListener("click", this.clickHandler, true);
  5091. getBody(document).title = "";
  5092. this.inPicker = false;
  5093. }
  5094.  
  5095. setImportant(ele, prop, value) {
  5096. ele.style.setProperty(prop, value, "important");
  5097. }
  5098.  
  5099. createSignDiv() {
  5100. let signDiv = document.createElement("div");
  5101. this.setImportant(signDiv, "position", "absolute");
  5102. this.setImportant(signDiv, "pointer-events", "none");
  5103. this.setImportant(signDiv, "z-index", "2147483645");
  5104. this.setImportant(signDiv, "background", "rgba(120, 170, 210, 0.6)");
  5105. this.setImportant(signDiv, "transition", "all 0.15s ease-out");
  5106. this.setImportant(signDiv, "box-shadow", "rgb(0 0 0) 0px 0px 3px 0px");
  5107. return signDiv;
  5108. }
  5109.  
  5110. adjustSignDiv(div, target) {
  5111. let rect = target.getBoundingClientRect();
  5112. this.setImportant(div, "width", rect.width + "px");
  5113. this.setImportant(div, "height", rect.height + "px");
  5114. this.setImportant(div, "left", rect.left + window.scrollX + "px");
  5115. this.setImportant(div, "top", rect.top + window.scrollY + "px");
  5116. }
  5117.  
  5118. getSelectorFromEle(ele) {
  5119. return this.xpath.checked ? createXPathFromElement(ele) : geneSelector(ele, true);
  5120. }
  5121.  
  5122. fillTempRuleTextarea() {
  5123. if (!this.frame.classList.contains("showDetail") || !this.editTemp || !this.editTemp.pageElement) this.tempRule.value = JSON.stringify(this.getTempRule(), null, 4);
  5124. }
  5125.  
  5126. setSelectorDiv(selector) {
  5127. let self = this;
  5128. this.allpath.innerHTML = createHTML("");
  5129. if (selector) {
  5130. if (this.xpath.checked) {
  5131. let span = document.createElement("span");
  5132. span.innerText = selector;
  5133. span.addEventListener("click", e => {
  5134. self.selectorInput.value = selector;
  5135. self.checkInputSelector();
  5136. }, true);
  5137. this.allpath.appendChild(span);
  5138. } else {
  5139. selector.split(">").forEach((item, index) => self.geneSelectorItem(item, index));
  5140. }
  5141. }
  5142. this.checkInputSelector();
  5143. }
  5144.  
  5145. geneSelectorItem(item, index) {
  5146. let self = this;
  5147. item = item.trim();
  5148. if (!item) return;
  5149. if (index !== 0) {
  5150. let span = document.createElement("span");
  5151. span.innerText = " > ";
  5152. this.allpath.appendChild(span);
  5153. }
  5154. let span = document.createElement("span");
  5155. span.className = "path";
  5156. span.innerText = item;
  5157. span.addEventListener("click", e => {
  5158. let selector = "";
  5159. let target = e.target;
  5160. while (target) {
  5161. selector = target.innerText + selector;
  5162. target = target.previousElementSibling;
  5163. }
  5164. self.selectorInput.value = selector;
  5165. self.checkInputSelector();
  5166. if (self.checkedPath) {
  5167. self.checkedPath.classList.remove("checked");
  5168. }
  5169. span.classList.add("checked");
  5170. self.checkedPath = span;
  5171. }, true);
  5172. this.allpath.appendChild(span);
  5173. }
  5174.  
  5175. checkInputSelector(fill = true) {
  5176. let self = this;
  5177. this.clearSigns();
  5178. if (!this.selectorInput.value) return;
  5179. let eles = getAllElements(this.selectorInput.value, document);
  5180. this.foundEle = null;
  5181. if (eles && eles.length > 0) {
  5182. this.foundEle = eles;
  5183. eles.forEach(ele => {
  5184. let sign = self.createSignDiv();
  5185. document.documentElement.appendChild(sign);
  5186. self.adjustSignDiv(sign, ele);
  5187. self.signList.push(sign);
  5188. });
  5189. if (fill) this.fillTempRuleTextarea();
  5190. }
  5191. }
  5192.  
  5193. clearSigns() {
  5194. this.signList.forEach(sign => {
  5195. if (sign.parentNode) sign.parentNode.removeChild(sign);
  5196. });
  5197. this.signList = [];
  5198. }
  5199.  
  5200. start() {
  5201. this.init();
  5202. if (this.inPicker) return;
  5203. this.inPicker = true;
  5204. if (!this.styleEle || !this.styleEle.parentNode) {
  5205. this.styleEle = _GM_addStyle(this.cssText);
  5206. }
  5207. document.documentElement.appendChild(this.frame);
  5208. document.documentElement.appendChild(this.mainSignDiv);
  5209. getBody(document).classList.add("pagetual-picker");
  5210.  
  5211. this.logoBtn.classList.remove("showSign");
  5212. this.showSign = true;
  5213.  
  5214. getBody(document).addEventListener("mousemove", this.moveHandler, true);
  5215. getBody(document).addEventListener("click", this.clickHandler, true);
  5216. this.xpath.checked = isXPath(ruleParser.curSiteRule.pageElement);
  5217. this.tempRule.value = "";
  5218. this.editTemp = null;
  5219. this.frame.classList.remove("showDetail");
  5220.  
  5221. this.loadNow.style.display = ruleParser.nextLinkHref ? "block" : "none";
  5222. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  5223. this.nextSwitchBtn.style.display = "block";
  5224. } else {
  5225. this.nextSwitchBtn.style.display = "none";
  5226. }
  5227. this.autoScrollBtn.innerText = i18n(autoScroll ? "disableAutoScroll" : "enableAutoScroll");
  5228.  
  5229. let pageElementSel = ruleParser.curSiteRule.pageElement || "";
  5230. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  5231. pageElementSel = pageElementSel[nextIndex < pageElementSel.length ? nextIndex : 0];
  5232. }
  5233. this.setSelectorDiv(pageElementSel);
  5234. this.fillTempRuleTextarea();
  5235. }
  5236. }
  5237. const picker = new Picker();
  5238.  
  5239. var editor, editorChanged = false, customRulesInput;
  5240. function createEdit() {
  5241. var options = {
  5242. mode: 'code',
  5243. modes: ['code', 'tree'],
  5244. templates: [
  5245. {
  5246. text: 'New site',
  5247. title: 'Insert a new site',
  5248. className: 'jsoneditor-type-object',
  5249. field: 'SiteTemplate',
  5250. value: {
  5251. 'name': 'Site name',
  5252. 'url': 'Site url'
  5253. }
  5254. }
  5255. ],
  5256. schema: {
  5257. "title": "Sites data",
  5258. "description": "Object containing site config",
  5259. "type": "array",
  5260. "items": {
  5261. "type": 'object',
  5262. "properties": {
  5263. "name": {
  5264. "title": "Site Name",
  5265. "description": "The site's name.",
  5266. "examples": [
  5267. "Google"
  5268. ],
  5269. "type": "string"
  5270. },
  5271. "url": {
  5272. "title": "Site Url",
  5273. "description": "The Regexp of site's url.",
  5274. "examples": [
  5275. "^https:\/\/yande\\.re\/"
  5276. ],
  5277. "type": "string"
  5278. }
  5279. },
  5280. "required": ["name", "url"]
  5281. }
  5282. },
  5283. onChange: () => {
  5284. editorChanged = true;
  5285. }
  5286. };
  5287. setTimeout(() => {
  5288. var container = document.getElementById("jsoneditor");
  5289. container.style.height = '800px';
  5290. container.innerHTML = "";
  5291. try {
  5292. editor = new _unsafeWindow.JSONEditor(container, options);
  5293. editor.set(ruleParser.customRules);
  5294. } catch (e) {
  5295. editor = null;
  5296. container.style.display = 'none';
  5297. customRulesInput.style.display = "";
  5298. }
  5299. }, 500);
  5300. }
  5301.  
  5302. function checkGuidePage(href) {
  5303. if (guidePage.test(href)) {
  5304. if (typeof _unsafeWindow.JSONEditor !== 'undefined') {
  5305. createEdit();
  5306. } else {
  5307. let timeout = 30;
  5308. let checkEditorReady = setInterval(() => {
  5309. if (typeof _unsafeWindow.JSONEditor !== 'undefined') {
  5310. createEdit();
  5311. clearInterval(checkEditorReady);
  5312. } else if (timeout-- <= 0) {
  5313. editor = null;
  5314. customRulesInput.style.display = "";
  5315. clearInterval(checkEditorReady);
  5316. }
  5317. }, 100);
  5318. }
  5319. return true;
  5320. }
  5321. return false;
  5322. }
  5323.  
  5324. function startAutoScroll() {
  5325. clearInterval(autoScrollInterval);
  5326. if (autoScroll <= 0) return;
  5327. let scrollRange_o = 1;
  5328. if (autoScroll > 1000) {
  5329. scrollRange_o = parseInt(autoScroll / 1000);
  5330. }
  5331. let devicePixelRatio = window.devicePixelRatio;
  5332. let scrollRange = Math.ceil(scrollRange_o / devicePixelRatio);
  5333. autoScrollInterval = setInterval(() => {
  5334. if (isPause) return;
  5335. if (devicePixelRatio !== window.devicePixelRatio) {
  5336. devicePixelRatio = window.devicePixelRatio;
  5337. scrollRange = Math.ceil(scrollRange_o / devicePixelRatio);
  5338. }
  5339. window.scroll(window.scrollX, window.scrollY + scrollRange);
  5340. }, parseInt(1000 / autoScroll));
  5341. }
  5342.  
  5343. var inUpdate = false;
  5344. var importHandler, configCon;
  5345. function initConfig(href) {
  5346. if (location.hostname === "github.com") {
  5347. 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) {
  5348. let issue_body = document.getElementById("issue_body");
  5349. if (!issue_body) return true;
  5350. issue_body.value = issue_body.value.replace("\n", "\n" + location.hash.slice(1) + "\n");
  5351. let starButton = document.createElement("a");
  5352. starButton.href = "https://github.com/hoothin/UserScripts#star";
  5353. starButton.className = "js-toggler-target rounded-left-2 btn-with-aria-count btn-sm btn";
  5354. 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>');
  5355. starButton.style.float = "right";
  5356. document.querySelector(".Layout-main>h2").appendChild(starButton);
  5357. return true;
  5358. } else if (location.href === "https://github.com/hoothin/UserScripts#star") {
  5359. let starButton = document.querySelector(".starring-container:not(.on)>.unstarred>form>button");
  5360. if (starButton) emuClick(starButton);
  5361. return true;
  5362. }
  5363. }
  5364. let isGuidePage = checkGuidePage(href);
  5365. if (!isGuidePage) {
  5366. if (href.indexOf("PagetualGuide") != -1) return true;
  5367. if (location.hostname === "pagetual.hoothin.com") return true;
  5368. }
  5369.  
  5370. var click2import, importUrlPres;
  5371.  
  5372. let inConfig = isGuidePage;
  5373. if (!inConfig) {
  5374. for (let i = 0; i < configPage.length; i++) {
  5375. if (configPage[i] == location.href) {
  5376. inConfig = true;
  5377. break;
  5378. }
  5379. }
  5380. }
  5381. configCon = document.getElementById("configCon");
  5382. if (configCon) {
  5383. configCon.parentNode.removeChild(configCon);
  5384. }
  5385. if (ruleImportUrlReg.test(href) || inConfig) {
  5386. let importing = false;
  5387. if (!inUpdate && rulesData.uninited) {
  5388. setTimeout(() => {
  5389. if (!inUpdate && !importing) showTips(i18n("firstAlert"));
  5390. }, 3000);
  5391. showTips(i18n("firstAlert"));
  5392. }
  5393. let defaultOption = document.querySelector('#discussion_rating_4');
  5394. if (defaultOption) defaultOption.checked = true;
  5395. let createImportBtn = (pre) => {
  5396. let importBtn = document.createElement("button");
  5397. importBtn.id = "pagetualImport";
  5398. importBtn.innerText = i18n("import");
  5399. importBtn.style.marginTop = "100px";
  5400. importBtn.style.float = "right";
  5401. importBtn.style.position = "relative";
  5402. importBtn.style.display = "block";
  5403. importBtn.style.fontSize = "20px";
  5404. importBtn.addEventListener("click", e => {
  5405. let parentNode = importBtn.parentNode;
  5406. if (!parentNode) return;
  5407. parentNode.removeChild(importBtn);
  5408. try {
  5409. let rules = parentNode.innerText.trim();
  5410. let isContent = /['"]name['"]/i.test(rules);
  5411. if (isContent) {
  5412. let ruleList = JSON.parse(`[${rules}]`);
  5413. for (let i in ruleList) {
  5414. let hasRule = false;
  5415. let r = ruleList[i];
  5416. for (let j in ruleParser.customRules) {
  5417. if (ruleParser.customRules[j].name == r.name) {
  5418. ruleParser.customRules[j] = r;
  5419. hasRule = true;
  5420. break;
  5421. }
  5422. }
  5423. if (!hasRule) ruleParser.customRules.push(r);
  5424. ruleParser.hpRules.unshift(r);
  5425. }
  5426. storage.setItem("customRules", ruleParser.customRules);
  5427. storage.setItem("hpRules", ruleParser.hpRules);
  5428. storage.setItem("smartRules", []);
  5429. showTips(i18n("importSucc"));
  5430. } else {
  5431. rules = rules.split("\n");
  5432. let diff = false;
  5433. for (let c = 0; c < rules.length; c++) {
  5434. let urlArr = rules[c].split("|"), url, type = 1;
  5435. if (urlArr.length == 1) {
  5436. url = urlArr[0].trim();
  5437. if (!/^http/.test(url)) {
  5438. showTips(i18n("errorWrongUrl"));
  5439. return;
  5440. }
  5441. } else if (urlArr.length == 2) {
  5442. type = urlArr[0].trim();
  5443. url = urlArr[1].trim();
  5444. if (!/^http/.test(url)) {
  5445. showTips(i18n("errorWrongUrl"));
  5446. return;
  5447. }
  5448. } else {
  5449. break;
  5450. }
  5451. let maxId = 1, hasUrl = false;
  5452. if (!rulesData.urls) {
  5453. rulesData.urls = [];
  5454. maxId = 1;
  5455. } else {
  5456. rulesData.urls.forEach(u => {
  5457. if (maxId < u.id) {
  5458. maxId = u.id;
  5459. }
  5460. if (u.url == url) {
  5461. hasUrl = true;
  5462. }
  5463. });
  5464. if (hasUrl) break;
  5465. }
  5466. diff = true;
  5467. if (!rulesData.sort) rulesData.sort = [1];
  5468. rulesData.urls.push({id: maxId + 1, url: url, type: type});
  5469. rulesData.sort.unshift(maxId + 1);
  5470. }
  5471. if (!diff) {
  5472. showTips(i18n("errorAlreadyExists"));
  5473. setTimeout(() => {
  5474. showTips(i18n("beginUpdate"), "", 50000);
  5475. updateRules(() => {
  5476. showTips(i18n("updateSucc"));
  5477. location.reload();
  5478. }, (rule, err) => {
  5479. showTips(`Failed to update ${rule.url} rules!`);
  5480. debug(err);
  5481. });
  5482. }, 500);
  5483. return;
  5484. }
  5485. storage.setItem("rulesData", rulesData);
  5486.  
  5487. if (rulesData.urls) ruleUrls = ruleUrls.concat(rulesData.urls);
  5488. if (rulesData.sort) {
  5489. let urls = [];
  5490. rulesData.sort.forEach(id => {
  5491. for (let s = 0; s < ruleUrls.length; s++) {
  5492. if (id == ruleUrls[s].id) {
  5493. urls.push(ruleUrls[s]);
  5494. break;
  5495. }
  5496. }
  5497. });
  5498. ruleUrls = urls;
  5499. }
  5500. showTips(i18n("beginUpdate"), "", 30000);
  5501. updateRules(() => {
  5502. showTips(i18n("updateSucc"));
  5503. location.reload();
  5504. }, (rule, err) => {
  5505. showTips(`Failed to update ${rule.url} rules!`);
  5506. debug(err);
  5507. });
  5508. importing = true;
  5509. }
  5510. } catch (e) {
  5511. _GM_notification(e.toString());
  5512. }
  5513. });
  5514. if (pre) {
  5515. let clientHeight = 35 - pre.clientHeight;
  5516. if (clientHeight > -20) clientHeight = -20;
  5517. importBtn.style.marginTop = `${clientHeight}px`;
  5518. pre.appendChild(importBtn);
  5519. }
  5520. return importBtn;
  5521. };
  5522. [].forEach.call(document.querySelectorAll('pre[name=pagetual],pre[name=user-content-pagetual]'), pre => {
  5523. let importBtn = createImportBtn(pre);
  5524. });
  5525. if (!importHandler) {
  5526. importHandler = e => {
  5527. if (compareNodeName(e.target, ["pre"])) {
  5528. let nameAttr = e.target.getAttribute("name");
  5529. if (nameAttr == "pagetual" || nameAttr == "user-content-pagetual") {
  5530. if (e.target.querySelector('#pagetualImport')) return;
  5531. let importBtn = createImportBtn(e.target);
  5532. }
  5533. }
  5534. };
  5535. }
  5536. document.removeEventListener("mouseover", importHandler);
  5537. document.addEventListener("mouseover", importHandler);
  5538.  
  5539. if (inConfig) {
  5540. if (!inUpdate && _GM_info.script && _GM_info.script.version && _GM_info.script.version !== '1.0.0') {
  5541. let versionEle = document.querySelector('.markdown-body>h1[id],article>h1');
  5542. let latestVer = versionEle && versionEle.innerText.match(/\d[\d\.]+/)[0];
  5543. if (latestVer && latestVer != _GM_info.script.version) {
  5544. showTips(i18n('outOfDate'), "", 3000);
  5545. }
  5546. }
  5547. _GM_addStyle(`
  5548. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  5549. cursor: pointer;
  5550. user-select: none;
  5551. display: inline-block;
  5552. margin-right: 5px;
  5553. -moz-transition:color 0.3s ease, transform 0.3s;
  5554. -webkit-transition:color 0.3s ease, transform 0.3s;
  5555. transition:color 0.3s ease, transform 0.3s;
  5556. }
  5557. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  5558. color:red;
  5559. transform: scale(1.5);
  5560. -webkit-transform: scale(1.5);
  5561. }
  5562. .updateDate{
  5563. cursor: pointer;
  5564. user-select: none;
  5565. -moz-transition:color 0.3s ease, transform 0.3s;
  5566. -webkit-transition:color 0.3s ease, transform 0.3s;
  5567. transition:color 0.3s ease, transform 0.3s;
  5568. transform-origin: left;
  5569. -webkit-transform-origin: left;
  5570. }
  5571. .updateDate:hover{
  5572. color:red;
  5573. transform: scale(1.1);
  5574. -webkit-transform: scale(1.1);
  5575. }
  5576. input[type=number]::-webkit-inner-spin-button,
  5577. input[type=number]::-webkit-outer-spin-button {
  5578. -webkit-appearance: none;
  5579. margin: 0;
  5580. }
  5581. input[type=number] {
  5582. -moz-appearance:textfield;
  5583. }
  5584. table td>h3 {
  5585. margin: 16px!important;
  5586. padding: 0!important;
  5587. }
  5588. table td>h4 {
  5589. padding: 0!important;
  5590. }
  5591. #saveBtn {
  5592. width: 60vw;
  5593. position: fixed;
  5594. z-index: 999;
  5595. bottom: 0;
  5596. left: 20vw;
  5597. font-size: xx-large;
  5598. opacity: 0.6;
  5599. cursor: pointer;
  5600. -moz-transition:all 0.3s ease;
  5601. -webkit-transition:all 0.3s ease;
  5602. transition:all 0.3s ease;
  5603. }
  5604. #configCon #saveBtn:hover {
  5605. opacity: 1;
  5606. margin-bottom: 0px;
  5607. }
  5608. #configCon #saveBtn {
  5609. margin-bottom: -40px;
  5610. }
  5611. #configCon.showSave #saveBtn {
  5612. margin-bottom: 0px;
  5613. }
  5614. `);
  5615. click2import = document.querySelector("[name='user-content-click2import'],[name='click2import']");
  5616. if (click2import) click2import.innerText = i18n("click2ImportRule")
  5617. configCon = document.querySelector(".markdown-body,.theme-default-content");
  5618. if (!configCon) {
  5619. setTimeout(() => {
  5620. location.reload();
  5621. }, 1000);
  5622. return true;
  5623. }
  5624. let insertPos = configCon.querySelector("hr,#jsoneditor");
  5625. configCon = document.createElement("div");
  5626. configCon.id = "configCon";
  5627. insertPos.parentNode.insertBefore(configCon, insertPos);
  5628.  
  5629. importUrlPres = document.querySelectorAll("pre[name='user-content-pagetual'],pre[name='pagetual']");
  5630. if (importUrlPres) {
  5631. [].forEach.call(importUrlPres, importUrlPre => {
  5632. importUrlPre.style.overflow = "hidden";
  5633. importUrlPre.style.display = rulesData.uninited ? "block" : "none";
  5634. });
  5635. }
  5636. if (click2import) click2import.style.display = rulesData.uninited ? "block" : "none";
  5637. let otherconfig = document.querySelector("a[name='user-content-otherconfig'],a[name='otherconfig']");
  5638. if (otherconfig) otherconfig.parentNode.removeChild(otherconfig);
  5639. let rulesExample = document.querySelector("#user-content-rules-example+a,#rules-example>a");
  5640. if (rulesExample) {
  5641. rulesExample.innerText = i18n("rulesExample");
  5642. if (lang == "zh-CN") {
  5643. rulesExample.href = rulesExample.href.replace("en", "cn");
  5644. } else if (lang == "zh-TW" || lang == "zh-HK") {
  5645. rulesExample.href = rulesExample.href.replace("/en", "");
  5646. }
  5647. }
  5648.  
  5649. let newPos, lastPos = 0;
  5650. window.addEventListener('scroll', function(e) {
  5651. newPos = window.scrollY;
  5652. if (newPos > lastPos) {
  5653. configCon.classList.add("showSave");
  5654. } else {
  5655. configCon.classList.remove("showSave");
  5656. }
  5657. lastPos = newPos;
  5658. });
  5659. } else return false;
  5660. } else return false;
  5661. let ruleBarInsertPos = document.createTextNode(' ');
  5662. configCon.appendChild(ruleBarInsertPos);
  5663. class Rulebar {
  5664. init(ruleUrl) {
  5665. let id = ruleUrl.id;
  5666. this.ruleUrl = ruleUrl;
  5667. this.item = document.createElement("p");
  5668. this.item.dataset.id = id;
  5669. let url = document.createElement("a");
  5670. url.href = ruleUrl.url;
  5671. url.innerHTML = ruleUrl.url;
  5672. url.title = ruleUrl.url;
  5673. let up = document.createElement("span");
  5674. up.innerHTML = "↑ ";
  5675. up.title = i18n("sortTitle");
  5676. let down = document.createElement("span");
  5677. down.innerHTML = "↓ ";
  5678. down.title = i18n("sortTitle");
  5679. let del = document.createElement("span");
  5680. del.innerHTML = "× ";
  5681. up.onclick = e => {
  5682. this.moveUp();
  5683. };
  5684. down.onclick = e => {
  5685. this.moveDown();
  5686. };
  5687. del.onclick = e => {
  5688. this.del();
  5689. };
  5690. this.item.appendChild(up);
  5691. this.item.appendChild(down);
  5692. this.item.appendChild(del);
  5693. this.item.appendChild(url);
  5694. if (ruleParser.rules) {
  5695. url.style.maxWidth = "calc(100% - 150px)";
  5696. url.style.overflow = "hidden";
  5697. url.style.display = "inline-block";
  5698. url.style.textOverflow = "ellipsis";
  5699. url.style.verticalAlign = "bottom";
  5700. url.style.whiteSpace = "nowrap";
  5701. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == id ? 1 : 0), 0);
  5702. let idSpan = document.createElement("span");
  5703. idSpan.style.float = "right";
  5704. idSpan.innerHTML = `[rules: ${rulesLength}]`;
  5705. this.item.appendChild(idSpan);
  5706. this.idSpan = idSpan;
  5707. }
  5708. configCon.insertBefore(this.item, ruleBarInsertPos);
  5709. }
  5710. updateNum() {
  5711. if (ruleParser.rules) {
  5712. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == this.item.dataset.id ? 1 : 0), 0);
  5713. this.idSpan.innerHTML = `[rules: ${rulesLength}]`;
  5714. }
  5715. }
  5716. saveSort() {
  5717. let sort = [];
  5718. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i => {
  5719. sort.push(i.dataset.id);
  5720. });
  5721. rulesData.sort = sort;
  5722. let urls = [];
  5723. sort.forEach(id => {
  5724. for (let s = 0; s < ruleUrls.length; s++) {
  5725. if (id == ruleUrls[s].id) {
  5726. urls.push(ruleUrls[s]);
  5727. break;
  5728. }
  5729. }
  5730. });
  5731. ruleUrls = urls;
  5732. storage.setItem("rulesData", rulesData);
  5733. showTips(i18n("sortTitle"));
  5734. }
  5735. moveUp() {
  5736. let preE = this.item.previousElementSibling;
  5737. if (compareNodeName(preE, ["p"]) && preE.children.length > 1) {
  5738. this.item.parentNode.insertBefore(this.item, preE);
  5739. this.saveSort();
  5740. }
  5741. }
  5742. moveDown() {
  5743. let nextE = this.item.nextElementSibling;
  5744. if (compareNodeName(nextE, ["p"]) && nextE.children.length > 1) {
  5745. this.item.parentNode.insertBefore(nextE, this.item);
  5746. this.saveSort();
  5747. }
  5748. }
  5749. del() {
  5750. if (this.ruleUrl.id < 2) {
  5751. showTips(i18n("cantDel"));
  5752. } else if (window.confirm(i18n("confirmDel"))) {
  5753. for (let u = 0; u < rulesData.urls.length; u++) {
  5754. if (this.ruleUrl.id == rulesData.urls[u].id) {
  5755. rulesData.urls.splice(u, 1);
  5756. break;
  5757. }
  5758. }
  5759. for (let u = 0; u < ruleUrls.length; u++) {
  5760. if (this.ruleUrl.id == ruleUrls[u].id) {
  5761. ruleUrls.splice(u, 1);
  5762. break;
  5763. }
  5764. }
  5765. for (let u = 0; u < rulesData.sort.length; u++) {
  5766. if (this.ruleUrl.id == rulesData.sort[u]) {
  5767. rulesData.sort.splice(u, 1);
  5768. break;
  5769. }
  5770. }
  5771. rulesData.ruleVersion = 0;
  5772. storage.setItem("rulesData", rulesData);
  5773. ruleParser.rules = ruleParser.rules.filter(item => {return item.from != this.ruleUrl.id});
  5774. storage.setItem("rules", ruleParser.rules);
  5775. this.item.parentNode.removeChild(this.item);
  5776. //location.reload();
  5777. }
  5778. }
  5779. }
  5780. let langSelect = document.createElement("select");
  5781. langSelect.style.float = "right";
  5782. langSelect.style.position = "relative";
  5783. langSelect.style.zIndex = "1";
  5784. let option = document.createElement("option");
  5785. option.value = "";
  5786. option.innerText = "Language";
  5787. langSelect.appendChild(option);
  5788. for (let key in langList) {
  5789. let option = document.createElement("option");
  5790. option.value = key;
  5791. option.innerText = langList[key];
  5792. langSelect.appendChild(option);
  5793. }
  5794. langSelect.value = rulesData.lang || "";
  5795. configCon.appendChild(langSelect);
  5796.  
  5797. let updateP = document.createElement("p"), i = 0;
  5798. let now = new Date().getTime();
  5799.  
  5800.  
  5801. let pastDate = (new Date(updateDate)).toString(), passStr;
  5802. let passTime = (now - updateDate) / 1000;
  5803. if (isNaN(passTime)) {
  5804. passStr = i18n("firstUpdate");
  5805. } else {
  5806. if (passTime < 60) {
  5807. passStr = i18n("passSec", parseInt(passTime));
  5808. } else if (passTime < 60 * 60) {
  5809. passStr = i18n("passMin", parseInt(passTime / 60));
  5810. } else if (passTime < 60 * 60 * 24) {
  5811. passStr = i18n("passHour", parseInt(passTime / 3600));
  5812. } else {
  5813. passStr = i18n("passDay", parseInt(passTime / 86400));
  5814. }
  5815. passStr += " 🖱 " + i18n("click2update");
  5816. }
  5817.  
  5818. let rulebarList = [], updateFail = false;
  5819. updateP.className = "updateDate";
  5820. updateP.innerHTML = passStr;
  5821. updateP.title = i18n("update") + " - " + pastDate;
  5822. configCon.appendChild(updateP);
  5823. if (ruleUrls) {
  5824. ruleUrls.forEach(ruleUrl => {
  5825. let rulebar = new Rulebar();
  5826. rulebar.init(ruleUrl);
  5827. rulebarList.push(rulebar);
  5828. });
  5829. }
  5830. let customUrlsTitle = document.createElement("h2");
  5831. customUrlsTitle.innerHTML = i18n("customUrls");
  5832. configCon.appendChild(customUrlsTitle);
  5833. let customUrlsInput = document.createElement("textarea");
  5834. customUrlsInput.style.width = "100%";
  5835. customUrlsInput.style.position = "relative";
  5836. customUrlsInput.placeholder = "http://wedata.net/databases/AutoPagerize/items_all.json \nhttps://hoothin.github.io/UserScripts/Pagetual/pagetualRules.json";
  5837. customUrlsInput.spellcheck = false;
  5838. configCon.appendChild(customUrlsInput);
  5839.  
  5840. let btns = document.createElement("div");
  5841. btns.style.display = "flex";
  5842. configCon.appendChild(btns);
  5843. let upBtnImg = document.createElement("div");
  5844. upBtnImg.style.width = "33%";
  5845. let upBtnImgTitle = document.createElement("h2");
  5846. upBtnImgTitle.style.whiteSpace = "nowrap";
  5847. upBtnImgTitle.style.overflow = "auto";
  5848. upBtnImgTitle.innerHTML = i18n("upBtnImg");
  5849. upBtnImg.appendChild(upBtnImgTitle);
  5850. let upBtnImgInput = document.createElement("input");
  5851. upBtnImgInput.style.width = "100%";
  5852. upBtnImgInput.style.position = "relative";
  5853. upBtnImgInput.placeholder = "data:image/png;base64,UpBtn";
  5854. upBtnImgInput.value = rulesData.upBtnImg || '';
  5855. upBtnImgInput.spellcheck = false;
  5856. upBtnImg.appendChild(upBtnImgInput);
  5857. btns.appendChild(upBtnImg);
  5858.  
  5859. let downBtnImg = document.createElement("div");
  5860. downBtnImg.style.width = "33%";
  5861. let downBtnImgTitle = document.createElement("h2");
  5862. downBtnImgTitle.style.whiteSpace = "nowrap";
  5863. downBtnImgTitle.style.overflow = "auto";
  5864. downBtnImgTitle.innerHTML = i18n("downBtnImg");
  5865. downBtnImg.appendChild(downBtnImgTitle);
  5866. let downBtnImgInput = document.createElement("input");
  5867. downBtnImgInput.style.width = "100%";
  5868. downBtnImgInput.style.position = "relative";
  5869. downBtnImgInput.placeholder = "data:image/png;base64,DownBtn";
  5870. downBtnImgInput.value = rulesData.downBtnImg || '';
  5871. downBtnImgInput.spellcheck = false;
  5872. downBtnImg.appendChild(downBtnImgInput);
  5873. btns.appendChild(downBtnImg);
  5874.  
  5875. let sideControllerIconDiv = document.createElement("div");
  5876. sideControllerIconDiv.style.width = "33%";
  5877. let sideControllerIconTitle = document.createElement("h2");
  5878. sideControllerIconTitle.style.whiteSpace = "nowrap";
  5879. sideControllerIconTitle.style.overflow = "auto";
  5880. sideControllerIconTitle.innerHTML = i18n("sideControllerIcon");
  5881. sideControllerIconDiv.appendChild(sideControllerIconTitle);
  5882. let sideControllerIconInput = document.createElement("input");
  5883. sideControllerIconInput.style.width = "100%";
  5884. sideControllerIconInput.style.position = "relative";
  5885. sideControllerIconInput.placeholder = "📄";
  5886. sideControllerIconInput.value = rulesData.sideControllerIcon || '';
  5887. sideControllerIconInput.spellcheck = false;
  5888. sideControllerIconDiv.appendChild(sideControllerIconInput);
  5889. btns.appendChild(sideControllerIconDiv);
  5890.  
  5891. let otherBtns = document.createElement("div");
  5892. otherBtns.style.display = "flex";
  5893. configCon.appendChild(otherBtns);
  5894. let loadingText = document.createElement("div");
  5895. loadingText.style.width = "100%";
  5896. let loadingTextTitle = document.createElement("h2");
  5897. loadingTextTitle.style.whiteSpace = "nowrap";
  5898. loadingTextTitle.style.overflow = "auto";
  5899. loadingTextTitle.innerHTML = i18n("loadingTextTitle");
  5900. loadingText.appendChild(loadingTextTitle);
  5901. let loadingTextInput = document.createElement("input");
  5902. loadingTextInput.value = rulesData.loadingText || '';
  5903. loadingTextInput.placeholder = i18n("loadingText");
  5904. loadingTextInput.style.width = "100%";
  5905. loadingTextInput.style.position = "relative";
  5906. loadingTextInput.style.margin = "0";
  5907. loadingTextInput.spellcheck = false;
  5908. loadingText.appendChild(loadingTextInput);
  5909. otherBtns.appendChild(loadingText);
  5910.  
  5911. let opacity = document.createElement("div");
  5912. let opacityTitle = document.createElement("h2");
  5913. opacityTitle.style.whiteSpace = "nowrap";
  5914. opacityTitle.style.overflow = "visible";
  5915. opacityTitle.innerHTML = i18n("opacity");
  5916. opacity.appendChild(opacityTitle);
  5917. let opacityInput = document.createElement("input");
  5918. opacityInput.value = rulesData.opacity * 100;
  5919. opacityInput.type = "number";
  5920. opacityInput.min = 0;
  5921. opacityInput.max = 100;
  5922. opacityInput.style.width = "110px";
  5923. opacityInput.style.position = "relative";
  5924. opacityInput.style.margin = "0";
  5925. opacityInput.placeholder = i18n("opacityPlaceholder");
  5926. opacityInput.spellcheck = false;
  5927. opacityInput.oninput = e => {
  5928. if (opacityInput.value > 100) opacityInput.value = 100;
  5929. else if (opacityInput.value < 0) opacityInput.value = 0;
  5930. };
  5931. opacity.appendChild(opacityInput);
  5932. otherBtns.appendChild(opacity);
  5933.  
  5934. let pageElementCss = document.createElement("div");
  5935. pageElementCss.style.marginBottom = "30px";
  5936. let pageElementCssTitle = document.createElement("h2");
  5937. pageElementCssTitle.innerHTML = i18n("pageElementCss");
  5938. pageElementCss.appendChild(pageElementCssTitle);
  5939. let pageElementCssInput = document.createElement("input");
  5940. pageElementCssInput.value = rulesData.pageElementCss || '';
  5941. pageElementCssInput.style.width = "100%";
  5942. pageElementCssInput.style.position = "relative";
  5943. pageElementCssInput.style.margin = "0";
  5944. pageElementCssInput.placeholder = "font-size: xx-large;";
  5945. pageElementCssInput.spellcheck = false;
  5946. pageElementCss.appendChild(pageElementCssInput);
  5947. configCon.appendChild(pageElementCss);
  5948.  
  5949. let customCss = document.createElement("div");
  5950. customCss.style.marginBottom = "50px";
  5951. let customCssTitle = document.createElement("h2");
  5952. customCssTitle.innerHTML = i18n("customCss");
  5953. customCss.appendChild(customCssTitle);
  5954. let customCssInput = document.createElement("textarea");
  5955. customCssInput.value = rulesData.customCss || '';
  5956. customCssInput.style.width = "100%";
  5957. customCssInput.style.position = "relative";
  5958. customCssInput.style.margin = "0";
  5959. customCssInput.placeholder = ".pagetual {\n}";
  5960. customCssInput.spellcheck = false;
  5961. customCss.appendChild(customCssInput);
  5962. configCon.appendChild(customCss);
  5963.  
  5964. let configTable = document.createElement("table");
  5965. configTable.style.width = "100%";
  5966. let configTbody = document.createElement("tbody");
  5967. configTbody.style.width = "99%";
  5968. configTbody.style.display = "inline-table";
  5969. configTable.appendChild(configTbody);
  5970. configCon.appendChild(configTable);
  5971. function createCheckbox(innerText, val, tag, parentCheck, otherType, alwaysShow) {
  5972. if (typeof val == 'undefined') val = "";
  5973. let title = document.createElement(tag || "h3");
  5974. title.innerHTML = innerText;
  5975. title.style.overflowWrap = "normal";
  5976. let input = document.createElement("input");
  5977. if (otherType === 'key') {
  5978. input.type = 'text';
  5979. input.setAttribute('readOnly', 'readonly');
  5980. input.addEventListener("keydown", e => {
  5981. if (e.key === 'Escape' || e.key === 'Backspace') input.value = '';
  5982. else input.value = e.key;
  5983. e.stopPropagation();
  5984. e.preventDefault();
  5985. });
  5986. } else {
  5987. input.type = otherType || "checkbox";
  5988. }
  5989. input.style.width = "35px";
  5990. input.style.height = "20px";
  5991. input.style.float = "left";
  5992. input.style.margin = "0 2px";
  5993. input.value = val;
  5994. input.checked = val;
  5995. let td = document.createElement("td");
  5996. td.appendChild(input);
  5997. if (parentCheck) {
  5998. title.appendChild(input);
  5999. title.style.margin = "0";
  6000. td.appendChild(title);
  6001. let parent = parentCheck.parentNode.nextElementSibling;
  6002. let tr = parent.querySelector("tr");
  6003. if (!tr) {
  6004. tr = document.createElement("tr");
  6005. parent.appendChild(tr);
  6006. }
  6007. tr.appendChild(td);
  6008. if (!alwaysShow) {
  6009. if (!parentCheck.checked) {
  6010. td.style.display = "none";
  6011. }
  6012. parentCheck.addEventListener("click", e => {
  6013. td.style.display = parentCheck.checked ? "" : "none";
  6014. });
  6015. }
  6016. } else {
  6017. let tr = document.createElement("tr");
  6018. tr.appendChild(td);
  6019. td = document.createElement("td");
  6020. td.appendChild(title);
  6021. tr.appendChild(td);
  6022. configTable.children[0].appendChild(tr);
  6023. }
  6024. let xNodePos = innerText.indexOf('【X】');
  6025. if (xNodePos !== -1) {
  6026. input.style.float = "";
  6027. let xNode = title.firstChild.splitText(xNodePos);
  6028. xNode.splitText(3);
  6029. xNode.parentNode.replaceChild(input, xNode);
  6030. }
  6031. return input;
  6032. }
  6033.  
  6034. let setConfigPageInput = createCheckbox(i18n("setConfigPage"), false);
  6035. let enableWhiteListInput = createCheckbox(i18n("autoRun"), rulesData.enableWhiteList != true);
  6036. let sideControllerInput = createCheckbox(i18n("sideController"), rulesData.sideController);
  6037. let sideControllerAlwaysInput = createCheckbox(i18n("sideControllerAlways"), rulesData.sideControllerAlways, "h4", sideControllerInput);
  6038. let sideControllerScrollInput = createCheckbox(i18n("sideControllerScroll"), rulesData.sideControllerScroll !== false, "h4", sideControllerInput);
  6039. let sideControllerLoadNowInput = createCheckbox(i18n("loadNow"), rulesData.sideControllerLoadNow !== false, "h4", sideControllerInput);
  6040. let enableDebugInput = createCheckbox(i18n("enableDebug"), rulesData.enableDebug != false);
  6041. let enableHistoryInput = createCheckbox(i18n("enableHistory"), rulesData.enableHistory === true);
  6042. let enableHistoryAfterInsertInput = createCheckbox(i18n("enableHistoryAfterInsert"), rulesData.enableHistoryAfterInsert === true, "h4", enableHistoryInput);
  6043. let openInNewTabInput = createCheckbox(i18n("openInNewTab"), rulesData.openInNewTab != false);
  6044. let hidePageBarInput = createCheckbox(i18n("hideBarTips"), rulesData.opacity == 0);
  6045. let hidePageBarArrowInput = createCheckbox(i18n("hideBarArrow"), rulesData.hideBarArrow);
  6046. let hideLoadingIconInput = createCheckbox(i18n("hideLoadingIcon"), rulesData.hideLoadingIcon != false);
  6047. let initRunInput = createCheckbox(i18n("initRun"), rulesData.initRun != false);
  6048. let autoLoadNumInput = createCheckbox(i18n("autoLoadNum"), rulesData.autoLoadNum, "h4", initRunInput, "number");
  6049. let preloadInput = createCheckbox(i18n("preload"), rulesData.preload != false);
  6050. let rateInput = createCheckbox(i18n("turnRate"), rulesData.rate, "h4", preloadInput, "number", true);
  6051. let dbClick2StopInput = createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  6052. let manualModeInput = createCheckbox(i18n("manualMode"), rulesData.manualMode);
  6053. let clickModeInput = createCheckbox(i18n("clickMode"), rulesData.clickMode);
  6054. let pageBarMenuInput = createCheckbox(i18n("pageBarMenu"), rulesData.pageBarMenu != false);
  6055. let arrowToScrollInput = createCheckbox(i18n("arrowToScroll"), rulesData.arrowToScroll);
  6056. let contentVisibilityInput = createCheckbox(i18n("contentVisibility"), rulesData.contentVisibility);
  6057. let wedata2githubInput = createCheckbox(i18n("wedata2github"), rulesData.wedata2github);
  6058. let customFirstInput = createCheckbox(i18n("customFirst"), rulesData.customFirst);
  6059. let lastPageTipsInput = createCheckbox(i18n("lastPageTips"), rulesData.lastPageTips);
  6060. let updateNotificationInput = createCheckbox(i18n("updateNotification"), rulesData.updateNotification != false);
  6061.  
  6062. let hideBarInput = createCheckbox(i18n("hideBar"), rulesData.hideBar && !rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  6063. hideBarInput.name = 'hideBar';
  6064. let hideBarButNoStopInput = createCheckbox(i18n("hideBarButNoStop"), rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  6065. hideBarButNoStopInput.name = 'hideBar';
  6066. hideBarInput.addEventListener('mouseup', e => {
  6067. if (hideBarInput.checked) {
  6068. setTimeout(() => {hideBarInput.checked = false}, 0);
  6069. }
  6070. });
  6071. hideBarButNoStopInput.addEventListener('mouseup', e => {
  6072. if (hideBarButNoStopInput.checked) {
  6073. setTimeout(() => {hideBarButNoStopInput.checked = false}, 0);
  6074. }
  6075. });
  6076. hidePageBarInput.addEventListener('click', e => {
  6077. opacityInput.value = hidePageBarInput.checked ? 0 : 100;
  6078. });
  6079.  
  6080. let dbClick2StopCtrlInput = createCheckbox(i18n("dbClick2StopCtrl"), rulesData.dbClick2StopCtrl, "h4", dbClick2StopInput);
  6081. let dbClick2StopAltInput = createCheckbox(i18n("dbClick2StopAlt"), rulesData.dbClick2StopAlt, "h4", dbClick2StopInput);
  6082. let dbClick2StopShiftInput = createCheckbox(i18n("dbClick2StopShift"), rulesData.dbClick2StopShift, "h4", dbClick2StopInput);
  6083. let dbClick2StopMetaInput = createCheckbox(i18n("dbClick2StopMeta"), rulesData.dbClick2StopMeta, "h4", dbClick2StopInput);
  6084. let dbClick2StopKeyInput = createCheckbox(i18n("dbClick2StopKey"), rulesData.dbClick2StopKey, "h4", dbClick2StopInput, "key");
  6085.  
  6086. let otherConfigPage = (rulesData.configPage || configPage[0]) != location.href;
  6087. if (!otherConfigPage) {
  6088. setConfigPageInput.parentNode.parentNode.style.display = "none";
  6089. }
  6090.  
  6091. updateP.onclick = e => {
  6092. updateFail = false;
  6093. //ruleParser.rules = [];
  6094. showTips(i18n("beginUpdate"), "", 30000);
  6095. updateRules(() => {
  6096. if (!updateFail) {
  6097. showTips(i18n("updateSucc"));
  6098. if (importUrlPres) {
  6099. [].forEach.call(importUrlPres, importUrlPre => {
  6100. importUrlPre.style.display = "none";
  6101. });
  6102. }
  6103. if (click2import) click2import.style.display = "none";
  6104. }
  6105. updateP.innerHTML = i18n("passSec", 0);
  6106. updateP.title = i18n("update");
  6107. rulebarList.forEach(rulebar => {
  6108. rulebar.updateNum();
  6109. });
  6110. }, (rule, err) => {
  6111. if (rule.id == 1) {
  6112. showTips(`Failed to update wedata rules! Try to switch to wedata mirror!`);
  6113. wedata2githubInput.scrollIntoView({ behavior: "smooth" });
  6114. } else {
  6115. showTips(`Failed to update ${rule.url} rules!`);
  6116. }
  6117. debug(err);
  6118. updateFail = true;
  6119. });
  6120. };
  6121. let customRulesTitle = document.createElement("h2");
  6122. 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');
  6123. configCon.appendChild(customRulesTitle);
  6124. customRulesInput = document.createElement("textarea");
  6125. customRulesInput.spellcheck = false;
  6126. configCon.appendChild(customRulesInput);
  6127. if (rulesData.editTemp) {
  6128. if (!ruleParser.customRules) {
  6129. ruleParser.customRules = [];
  6130. }
  6131. for (let i in ruleParser.customRules) {
  6132. if (ruleParser.customRules[i].url == rulesData.editTemp.url) {
  6133. ruleParser.customRules.splice(i, 1);
  6134. break;
  6135. }
  6136. }
  6137. ruleParser.customRules.unshift(rulesData.editTemp);
  6138. rulesData.editTemp = null;
  6139. storage.setItem("rulesData", rulesData);
  6140. customRulesInput.previousElementSibling.scrollIntoView();
  6141. }
  6142. customRulesInput.style.width = "100%";
  6143. customRulesInput.style.height = "800px";
  6144. 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]`;
  6145. let preCustom = getFormatJSON(ruleParser.customRules);
  6146. customRulesInput.value = preCustom;
  6147. if (isGuidePage) customRulesInput.style.display = "none";
  6148. let blacklistInput = document.createElement("textarea");
  6149. blacklistInput.style.width = "100%";
  6150. blacklistInput.style.height = "500px";
  6151. blacklistInput.style.display = "none";
  6152. blacklistInput.spellcheck = false;
  6153. 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";
  6154. blacklistInput.value = rulesData.blacklist ? rulesData.blacklist.join("\n") : "";
  6155. let blacklistBtn = document.createElement("button");
  6156. blacklistBtn.innerText = i18n("editBlacklist");
  6157. blacklistBtn.style.width = "100%";
  6158. blacklistBtn.onclick = e => {
  6159. blacklistInput.style.display = blacklistInput.style.display == "none" ? "" : "none";
  6160. };
  6161. configCon.appendChild(blacklistBtn);
  6162. configCon.appendChild(blacklistInput);
  6163. let saveBtn = document.createElement("button");
  6164. saveBtn.innerHTML = i18n("save");
  6165. saveBtn.id = "saveBtn";
  6166. configCon.appendChild(saveBtn);
  6167. saveBtn.onclick = e => {
  6168. try {
  6169. let customRules;
  6170. if (editor) {
  6171. if (editorChanged) {
  6172. editorChanged = false;
  6173. storage.setItem("hpRules", []);
  6174. storage.setItem("smartRules", []);
  6175. }
  6176. customRules = editor.get();
  6177. if (!customRules) {
  6178. customRules = "";
  6179. } else {
  6180. if (Array && Array.isArray && !Array.isArray(customRules)) {
  6181. showTips(i18n("errorRulesMustBeArray"));
  6182. return;
  6183. }
  6184. }
  6185. } else {
  6186. if (customRulesInput.value != preCustom) {
  6187. storage.setItem("hpRules", []);
  6188. storage.setItem("smartRules", []);
  6189. }
  6190. if (customRulesInput.value == "") {
  6191. customRules = "";
  6192. } else {
  6193. customRules = JSON.parse(customRulesInput.value);
  6194. if (Array && Array.isArray && !Array.isArray(customRules)) {
  6195. showTips(i18n("errorRulesMustBeArray"));
  6196. return;
  6197. }
  6198. customRulesInput.value = JSON.stringify(customRules, null, 4);
  6199. }
  6200. }
  6201. debug(customRules);
  6202. storage.setItem("customRules", customRules);
  6203. } catch(e) {
  6204. debug(e);
  6205. let pos = e && e.message && e.message.match(/position (\d+)/);
  6206. if (pos && !editor) {
  6207. pos = parseInt(pos[1]);
  6208. customRulesInput.value = customRulesInput.value.slice(0, pos) + "➡️" + customRulesInput.value.slice(pos);
  6209. }
  6210. showTips(i18n("errorJson"));
  6211. return;
  6212. }
  6213. rulesData.lang = langSelect.value || "";
  6214. if (setConfigPageInput.checked) rulesData.configPage = location.href;
  6215. rulesData.wedata2github = wedata2githubInput.checked;
  6216. let opacity = parseInt(opacityInput.value) || 0;
  6217. if (opacity > 100) opacity = 100;
  6218. else if (opacity < 0) opacity = 0;
  6219. rulesData.opacity = opacity / 100;
  6220. rulesData.blacklist = blacklistInput.value ? blacklistInput.value.trim().split("\n") : "";
  6221. rulesData.hideBar = hideBarInput.checked;
  6222. rulesData.hideBarButNoStop = hideBarButNoStopInput.checked;
  6223. rulesData.dbClick2Stop = dbClick2StopInput.checked;
  6224. rulesData.enableWhiteList = !enableWhiteListInput.checked;
  6225. rulesData.enableDebug = enableDebugInput.checked;
  6226. rulesData.updateNotification = updateNotificationInput.checked;
  6227. rulesData.enableHistory = enableHistoryInput.checked;
  6228. rulesData.enableHistoryAfterInsert = enableHistoryAfterInsertInput.checked;
  6229. rulesData.openInNewTab = openInNewTabInput.checked;
  6230. rulesData.hideLoadingIcon = hideLoadingIconInput.checked;
  6231. rulesData.hideBarArrow = hidePageBarArrowInput.checked;
  6232. rulesData.customFirst = customFirstInput.checked;
  6233. rulesData.lastPageTips = lastPageTipsInput.checked;
  6234. rulesData.initRun = initRunInput.checked;
  6235. rulesData.autoLoadNum = autoLoadNumInput.value !== "0" ? autoLoadNumInput.value : '';
  6236. rulesData.rate = parseFloat(rateInput.value) || 0;
  6237. rulesData.preload = preloadInput.checked;
  6238. rulesData.manualMode = manualModeInput.checked;
  6239. rulesData.clickMode = clickModeInput.checked;
  6240. rulesData.pageBarMenu = pageBarMenuInput.checked;
  6241. rulesData.arrowToScroll = arrowToScrollInput.checked;
  6242. rulesData.contentVisibility = contentVisibilityInput.checked;
  6243. if (rulesData.sideController != sideControllerInput.checked) {
  6244. rulesData.sideControllerPos = false;
  6245. }
  6246. rulesData.sideController = sideControllerInput.checked;
  6247. rulesData.sideControllerScroll = sideControllerScrollInput.checked;
  6248. rulesData.sideControllerLoadNow = sideControllerLoadNowInput.checked;
  6249. rulesData.sideControllerAlways = sideControllerAlwaysInput.checked;
  6250. rulesData.pageElementCss = pageElementCssInput.value;
  6251. rulesData.customCss = customCssInput.value;
  6252. rulesData.upBtnImg = upBtnImgInput.value;
  6253. rulesData.downBtnImg = downBtnImgInput.value;
  6254. rulesData.sideControllerIcon = sideControllerIconInput.value;
  6255. rulesData.loadingText = loadingTextInput.value;
  6256. rulesData.dbClick2StopCtrl = dbClick2StopCtrlInput.checked;
  6257. rulesData.dbClick2StopAlt = dbClick2StopAltInput.checked;
  6258. rulesData.dbClick2StopShift = dbClick2StopShiftInput.checked;
  6259. rulesData.dbClick2StopMeta = dbClick2StopMetaInput.checked;
  6260. rulesData.dbClick2StopKey = dbClick2StopKeyInput.value;
  6261. storage.setItem("rulesData", rulesData);
  6262. let customUrls = customUrlsInput.value.trim(), urlImported = false;
  6263. if (customUrls) {
  6264. customUrls = customUrls.split(/\n/);
  6265. for (let c = 0; c < customUrls.length; c++) {
  6266. let url;
  6267. if (/^0\s*\|/.test(customUrls[c])) {
  6268. url = customUrls[c].replace(/^0\s*\|\s*/, "").trim();
  6269. if (!/^http/.test(url)) {
  6270. showTips(i18n("errorWrongUrl"));
  6271. return;
  6272. }
  6273. } else {
  6274. url = customUrls[c].trim();
  6275. if (!/^http/.test(url)) {
  6276. showTips(i18n("errorWrongUrl"));
  6277. return;
  6278. }
  6279. }
  6280. let maxId = 1, hasUrl = false;
  6281. if (!rulesData.urls) {
  6282. rulesData.urls = [];
  6283. }
  6284. ruleUrls.forEach(u => {
  6285. if (maxId < u.id) {
  6286. maxId = u.id;
  6287. }
  6288. if (u.url == url) {
  6289. hasUrl = true;
  6290. }
  6291. });
  6292. if (hasUrl) break;
  6293. if (!rulesData.sort) rulesData.sort = [1];
  6294. let newRule = {id: maxId + 1, url: url};
  6295. ruleUrls.push(newRule);
  6296. rulesData.urls.push(newRule);
  6297. rulesData.sort.push(maxId + 1);
  6298. storage.setItem("rulesData", rulesData);
  6299. let rulebar = new Rulebar();
  6300. rulebar.init(newRule);
  6301. rulebarList.push(rulebar);
  6302. }
  6303. }
  6304. showTips(i18n("settingsSaved"));
  6305. };
  6306. return true;
  6307. }
  6308.  
  6309. function updateRules (success, fail, keepCache) {
  6310. if (!storage.supportCrossSave()) {
  6311. fail({url:''}, "Not support cross storage");
  6312. showTips("Current platform do not support cross storage!");
  6313. return;
  6314. }
  6315. if (inUpdate) return;
  6316. inUpdate = true;
  6317. let ruleIndex = ruleUrls.length - 1;
  6318. if (!keepCache) {
  6319. storage.setItem("hpRules", []);
  6320. storage.setItem("smartRules", []);
  6321. }
  6322. let allOk = true;
  6323. let preLength = ruleParser.rules.length;
  6324. let fetchVersion = -1;
  6325. async function needUpdate(url, id) {
  6326. if (!/^https:\/\/hoothin\.github\.io\/|\/hoothin\/UserScripts\/.*\/Pagetual\/pagetualRules\.json/i.test(url)) {
  6327. return true;
  6328. }
  6329. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == id ? 1 : 0), 0);
  6330. if (rulesLength === 0) return true;
  6331. if (fetchVersion >= 0) {
  6332. return fetchVersion > (rulesData.ruleVersion || 0);
  6333. }
  6334. fetchVersion = await new Promise(resolve => {
  6335. _GM_xmlhttpRequest({
  6336. url: url.replace(/\/\w+\.json/i, "/version"),
  6337. method: 'GET',
  6338. timeout: 20000,
  6339. headers: {
  6340. 'accept': 'application/json,text/html'
  6341. },
  6342. onload: function(res) {
  6343. let version = parseInt(res.response || res.responseText);
  6344. resolve(version || -1);
  6345. },
  6346. onerror: function(e) {
  6347. resolve(-1);
  6348. },
  6349. ontimeout: function(e) {
  6350. resolve(-1);
  6351. }
  6352. });
  6353. });
  6354. return fetchVersion > (rulesData.ruleVersion || 0);
  6355. }
  6356. async function addNextRule() {
  6357. if (ruleIndex < 0) {
  6358. let now = new Date().getTime();
  6359. storage.setItem("ruleLastUpdate", now);
  6360. storage.setItem("rules", ruleParser.rules);
  6361. let curLength = ruleParser.rules.length;
  6362. if (curLength !== preLength && rulesData.updateNotification) {
  6363. _GM_notification({
  6364. text: `Rules has updated( ${preLength} => ${curLength} )`,
  6365. title: "Pagetual rules updated",
  6366. onclick: (event) => {
  6367. event.preventDefault();
  6368. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  6369. }
  6370. });
  6371. }
  6372. inUpdate = false;
  6373. let rulesDataChanged = false;
  6374. if (fetchVersion >= 0 && rulesData.ruleVersion !== fetchVersion) {
  6375. rulesData.ruleVersion = fetchVersion;
  6376. rulesDataChanged = true;
  6377. }
  6378. if (rulesData.uninited && allOk && ruleUrls.length > 1) {
  6379. rulesData.uninited = false;
  6380. rulesDataChanged = true;
  6381. }
  6382. if (rulesDataChanged) {
  6383. storage.setItem("rulesData", rulesData);
  6384. }
  6385. success();
  6386. } else {
  6387. let rule = ruleUrls[ruleIndex--];
  6388. if (await needUpdate(rule.url, rule.id)) {
  6389. ruleParser.addRuleByUrl(rule.url, rule.id, (json, err) => {
  6390. if (!json) {
  6391. allOk = false;
  6392. fail(rule, err);
  6393. }
  6394. addNextRule();
  6395. });
  6396. } else {
  6397. addNextRule();
  6398. }
  6399. }
  6400. }
  6401. addNextRule();
  6402. }
  6403.  
  6404. function objIsArr(obj) {
  6405. return obj &&
  6406. typeof obj === 'object' &&
  6407. typeof obj.length === 'number' &&
  6408. !(obj.propertyIsEnumerable('length'));
  6409. }
  6410.  
  6411. function isVisible(el, win) {
  6412. if(!el || !el.offsetParent)return false;
  6413. var loopable = true,
  6414. visible = el.nodeName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  6415. while(loopable && visible) {
  6416. el = el.parentNode;
  6417.  
  6418. if(el && !compareNodeName(el, ["body"])) {
  6419. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  6420. }else {
  6421. loopable = false;
  6422. }
  6423. }
  6424. return visible;
  6425. }
  6426.  
  6427. function getElementTop(ele) {
  6428. if (!ele) return 0;
  6429. if (ele.getBoundingClientRect) {
  6430. return ele.getBoundingClientRect().top + document.documentElement.scrollTop;
  6431. }
  6432. var actualTop = ele.offsetTop;
  6433. var current = ele.offsetParent;
  6434. while (current) {
  6435. actualTop += current.offsetTop;
  6436. current = current.offsetParent;
  6437. }
  6438. return actualTop;
  6439. }
  6440.  
  6441. function getElementLeft(ele) {
  6442. if (!ele) return 0;
  6443. if (ele.getBoundingClientRect) {
  6444. return ele.getBoundingClientRect().left + document.documentElement.scrollLeft;
  6445. }
  6446. var actualLeft = ele.offsetLeft;
  6447. var current = ele.offsetParent;
  6448. while (current) {
  6449. actualLeft += current.offsetLeft;
  6450. current = current.offsetParent;
  6451. }
  6452. return actualLeft;
  6453. }
  6454.  
  6455. function getElementBottom(ele) {
  6456. return getElementTop(ele) + (ele.offsetHeight || ele.scrollHeight);
  6457. }
  6458.  
  6459. function getFormatJSON(obj){
  6460. if(!objIsArr(obj) || obj.length === 0)return "";
  6461. return JSON.stringify(obj, null, 4);
  6462. }
  6463.  
  6464. function globMatch(first, second) {
  6465. if (first === '*') {
  6466. return true;
  6467. }
  6468. if (first.length == 0 && second.length == 0){
  6469. return true;
  6470. }
  6471.  
  6472. if (first.length > 1 && first[0] == '*' &&
  6473. second.length == 0){
  6474. return false;
  6475. }
  6476.  
  6477. if ((first.length > 1 && first[0] == '?') ||
  6478. (first.length != 0 && second.length != 0 &&
  6479. first[0] == second[0])){
  6480. return globMatch(first.substring(1),
  6481. second.substring(1));
  6482. }
  6483.  
  6484. if (first.length > 0 && first[0] == '*'){
  6485. return globMatch(first.substring(1), second) ||
  6486. globMatch(first, second.substring(1));
  6487. }
  6488.  
  6489. return false;
  6490. }
  6491.  
  6492. let pageReady = false;
  6493. function initRules(callback) {
  6494. charset = (document.characterSet || document.charset || document.inputEncoding);
  6495. let equiv = document.querySelector('[http-equiv="Content-Type"]');
  6496. if (equiv && equiv.content) {
  6497. let innerCharSet = equiv.content.match(/charset\=([^;]+)/);
  6498. if (!innerCharSet) {
  6499. charsetValid = false;
  6500. } else if (innerCharSet[1].replace("-", "").toLowerCase() != charset.replace("-", "").toLowerCase()) {
  6501. charsetValid = false;
  6502. }
  6503. } else charsetValid = false;
  6504. storage.getItem("rulesData", data => {
  6505. /*0 wedata格式,1 pagetual格式*/
  6506. ruleUrls = [{
  6507. id: 1,
  6508. url: data && data.wedata2github ? 'https://hoothin.github.io/UserScripts/Pagetual/items_all.json' : 'http://wedata.net/databases/AutoPagerize/items_all.json',
  6509. type: 0,
  6510. }];
  6511. if (data) {
  6512. rulesData = data;
  6513. if (data.urls) ruleUrls = ruleUrls.concat(data.urls);
  6514. if (data.sort) {
  6515. let urls = [];
  6516. data.sort.forEach(id => {
  6517. for (let s = 0; s < ruleUrls.length; s++) {
  6518. if (id == ruleUrls[s].id) {
  6519. urls.push(ruleUrls[s]);
  6520. break;
  6521. }
  6522. }
  6523. });
  6524. ruleUrls = urls;
  6525. }
  6526. }
  6527. if (rulesData.lang) {
  6528. setLang(rulesData.lang);
  6529. }
  6530. if (rulesData.firstRun) {
  6531. rulesData.firstRun = false;
  6532. storage.setItem("rulesData", rulesData);
  6533. setTimeout(() => {
  6534. storage.getItem("rulesData", data => {
  6535. if (data.firstRun === false) {
  6536. _GM_openInTab(firstRunPage, {active: true});
  6537. }
  6538. });
  6539. }, 100);
  6540. }
  6541. _GM_registerMenuCommand(i18n("configure"), () => {
  6542. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  6543. });
  6544. if (rulesData.blacklist && rulesData.blacklist.length > 0) {
  6545. let href = location.href.slice(0, 500);
  6546. let commentStart = false;
  6547. for (let i = 0; i < rulesData.blacklist.length; i++) {
  6548. let curGlob = rulesData.blacklist[i];
  6549. if (!curGlob) continue;
  6550. if (curGlob.indexOf("//") == 0) continue;
  6551. if (commentStart) {
  6552. if (/\*\/$/.test(curGlob)) {
  6553. commentStart = false;
  6554. }
  6555. continue;
  6556. }
  6557. if (curGlob.indexOf("/*") == 0) {
  6558. commentStart = true;
  6559. continue;
  6560. }
  6561. if (curGlob.indexOf("/") == 0) {
  6562. let regMatch = curGlob.match(/^\/(.*)\/(\w*)$/);
  6563. if (regMatch && new RegExp(regMatch[1], regMatch[2]).test(href)) {
  6564. forceState == 1;
  6565. return;
  6566. }
  6567. } else if (globMatch(curGlob, href)) {
  6568. forceState == 1;
  6569. return;
  6570. }
  6571. }
  6572. }
  6573. _GM_registerMenuCommand(i18n("editCurrent"), () => {
  6574. picker.start();
  6575. });
  6576. ruleParser.initSavedRules(async () => {
  6577. let upBtnImg = rulesData.upBtnImg, downBtnImg = rulesData.downBtnImg, _sideControllerIcon = rulesData.sideControllerIcon;
  6578. if (upBtnImg && downBtnImg) {
  6579. downSvgCSS = downSvgCSS.replace("transform: rotate(180deg);", "");
  6580. } else if (upBtnImg && !downBtnImg) {
  6581. downBtnImg = upBtnImg;
  6582. } else if(downBtnImg && !upBtnImg) {
  6583. upBtnImg = downBtnImg;
  6584. }
  6585. if (upBtnImg) {
  6586. upSvg = /https?:|data/.test(upBtnImg) ? `<img class="pagetual" src="${upBtnImg}"/>` : `<span>${upBtnImg}</span>`;
  6587. }
  6588. if (downBtnImg) {
  6589. downSvg = /https?:|data/.test(downBtnImg) ? `<img class="pagetual" src="${downBtnImg}"/>` : `<span>${downBtnImg}</span>`;
  6590. }
  6591. if (_sideControllerIcon) {
  6592. sideControllerIcon = /https?:|data/.test(_sideControllerIcon) ? `<img class="pagetual" src="${_sideControllerIcon}"/>` : `<span>${_sideControllerIcon}</span>`;
  6593. }
  6594. setLoadingDiv(rulesData.loadingText || i18n("loadingText"));
  6595. if (typeof(rulesData.opacity) == "undefined") {
  6596. rulesData.opacity = 1;
  6597. }
  6598. if (typeof(rulesData.hideBar) == "undefined") {
  6599. rulesData.hideBar = false;
  6600. }
  6601. if (typeof(rulesData.dbClick2Stop) == "undefined") {
  6602. rulesData.dbClick2Stop = true;
  6603. }
  6604. if (typeof(rulesData.enableWhiteList) == "undefined") {
  6605. rulesData.enableWhiteList = false;
  6606. }
  6607. if (typeof(rulesData.enableHistory) == "undefined") {
  6608. rulesData.enableHistory = false;
  6609. }
  6610. if (typeof(rulesData.openInNewTab) == "undefined") {
  6611. rulesData.openInNewTab = false;
  6612. }
  6613. if (typeof(rulesData.enableDebug) == "undefined") {
  6614. rulesData.enableDebug = true;
  6615. }
  6616. if (typeof(rulesData.updateNotification) == "undefined") {
  6617. rulesData.updateNotification = true;
  6618. }
  6619. if (typeof(rulesData.initRun) == "undefined") {
  6620. rulesData.initRun = true;
  6621. }
  6622. if (typeof(rulesData.preload) == "undefined") {
  6623. rulesData.preload = true;
  6624. }
  6625. if (typeof(rulesData.customFirst) == "undefined") {
  6626. rulesData.customFirst = false;
  6627. }
  6628. if (typeof(rulesData.manualMode) == "undefined") {
  6629. rulesData.manualMode = false;
  6630. }
  6631. if (typeof(rulesData.clickMode) == "undefined") {
  6632. rulesData.clickMode = false;
  6633. }
  6634. if (typeof(rulesData.pageBarMenu) == "undefined") {
  6635. rulesData.pageBarMenu = true;
  6636. }
  6637. if (typeof(rulesData.arrowToScroll) == "undefined") {
  6638. rulesData.arrowToScroll = false;
  6639. }
  6640. if (typeof(rulesData.hideLoadingIcon) == "undefined") {
  6641. rulesData.hideLoadingIcon = false;
  6642. }
  6643. if (typeof(rulesData.hideBarArrow) == "undefined") {
  6644. rulesData.hideBarArrow = false;
  6645. }
  6646. if (typeof(rulesData.lastPageTips) == "undefined") {
  6647. rulesData.lastPageTips = true;
  6648. }
  6649. if (typeof(rulesData.rate) == "undefined") {
  6650. rulesData.rate = 1;
  6651. }
  6652. rate = rulesData.rate;
  6653. if (rulesData.autoLoadNum && rulesData.initRun) {
  6654. autoLoadNum = parseInt(rulesData.autoLoadNum);
  6655. }
  6656. openInNewTab = rulesData.openInNewTab ? 1 : 0;
  6657. enableDebug = rulesData.enableDebug;
  6658.  
  6659. let _nextSwitch = await getListData("nextSwitch", location.host);
  6660. if (typeof(_nextSwitch) !== "undefined") {
  6661. nextIndex = _nextSwitch || 0;
  6662. }
  6663.  
  6664. let _forceState = await getListData("forceState", location.host);
  6665. if (typeof(_forceState) == "undefined") {
  6666. _forceState = await getData("forceState_" + location.host);
  6667. }
  6668. if (typeof(_forceState) == "undefined") {
  6669. _forceState = (rulesData.enableWhiteList ? 1 : 0);
  6670. }
  6671. forceState = _forceState;
  6672.  
  6673. autoScroll = await getListData("autoScroll", location.host + location.pathname) || 0;
  6674.  
  6675. updateDate = await getData("ruleLastUpdate");
  6676.  
  6677. let _loadNowNum = await getData("loadNowNum");
  6678. if (typeof(_loadNowNum) != "undefined") {
  6679. loadNowNum = _loadNowNum;
  6680. }
  6681. let _autoScrollRate = await getData("autoScrollRate");
  6682. if (_autoScrollRate) {
  6683. autoScrollRate = _autoScrollRate;
  6684. }
  6685.  
  6686. author = await getData("author") || "";
  6687.  
  6688. manualPause = !!await getListData("pauseState", location.host);
  6689.  
  6690. let href = location.href.slice(0, 100);
  6691. try {
  6692. if (_unsafeWindow.initedPagetual) {
  6693. if (ruleImportUrlReg.test(href)) {
  6694. showTips(i18n('duplicate'));
  6695. }
  6696. return;
  6697. }
  6698. _unsafeWindow.initedPagetual = true;
  6699. } catch(e) {showTips(e)}
  6700. listenUrl();
  6701. _GM_registerMenuCommand(i18n("update"), () => {
  6702. showTips(i18n("beginUpdate"), "", 60000);
  6703. updateRules(() => {
  6704. showTips(i18n("updateSucc"));
  6705. location.reload();
  6706. },(rule, err) => {
  6707. showTips(`Failed to update ${rule.url} rules!`);
  6708. debug(err);
  6709. });
  6710. });
  6711. _GM_registerMenuCommand(i18n(forceState == 1 ? "enable" : "disableSite"), () => {
  6712. if (forceState == 1) {
  6713. forceState = 0;
  6714. showTips(i18n("enableSiteTips"));
  6715. changeStop(false);
  6716. } else {
  6717. forceState = 1;
  6718. showTips(i18n("disableSiteTips"));
  6719. changeStop(true);
  6720. sideController.remove();
  6721. }
  6722. setListData("forceState", location.host, forceState);
  6723. if (!ruleParser.curSiteRule.url) {
  6724. setTimeout(() => {
  6725. location.reload();
  6726. }, 500);
  6727. }
  6728. });
  6729. _GM_registerMenuCommand(i18n("toggleAutoScroll"), () => {
  6730. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  6731. autoScroll = parseInt(autoScroll) || 0;
  6732. if (autoScroll < 0) autoScroll = 0;
  6733. if (autoScroll && autoScroll != autoScrollRate) {
  6734. autoScrollRate = autoScroll;
  6735. storage.setItem("autoScrollRate", autoScrollRate);
  6736. }
  6737. setListData("autoScroll", location.host + location.pathname, autoScroll);
  6738. startAutoScroll();
  6739. });
  6740. startAutoScroll();
  6741.  
  6742.  
  6743. if (initConfig(href)) return;
  6744. pageReady = true;
  6745. if (forceState == 1) return;
  6746. let now = new Date().getTime();
  6747. if (!updateDate || now - updateDate > 2 * 24 * 60 * 60 * 1000) {
  6748. updateRules(() => {
  6749. }, (rule, err) => {}, true);
  6750. storage.setItem("ruleLastUpdate", now);
  6751. }
  6752. callback();
  6753. });
  6754. });
  6755. }
  6756.  
  6757. function requestDoc(url, callback) {
  6758. let postParams = url.match(/#p{(.*)}$/);
  6759. if (postParams) {
  6760. postParams = postParams[1];
  6761. url = url.replace(/#p{.*/, "");
  6762. }
  6763. let ruleHeaders = ruleParser.curSiteRule.headers;
  6764. let headers = {
  6765. 'Referer': location.href,
  6766. 'User-Agent': navigator.userAgent,
  6767. 'accept': 'text/html,application/xhtml+xml,application/xml',
  6768. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + charset,
  6769. };
  6770. if (ruleHeaders) {
  6771. if (ruleHeaders.referer) {
  6772. headers.referer = ruleHeaders.referer;
  6773. }
  6774. if (ruleHeaders.userAgent) {
  6775. headers.userAgent = ruleHeaders.userAgent;
  6776. }
  6777. if (ruleHeaders.accept) {
  6778. headers.accept = ruleHeaders.accept;
  6779. }
  6780. if (ruleHeaders.contentType) {
  6781. headers.contentType = ruleHeaders.contentType;
  6782. let ruleCharset = ruleHeaders.contentType.match(/charset\=([^;]+)/);
  6783. if (ruleCharset) charset = ruleCharset[1];
  6784. }
  6785. if (ruleHeaders.cookie) {
  6786. headers.cookie = ruleHeaders.cookie;
  6787. }
  6788. }
  6789. _GM_xmlhttpRequest({
  6790. url: url,
  6791. method: postParams ? 'POST' : 'GET',
  6792. data: postParams,
  6793. overrideMimeType: 'text/html;charset=' + charset,
  6794. headers: headers,
  6795. timeout: 50000,
  6796. onload: async function(res) {
  6797. if (isPause) return callback(false);
  6798. var doc = null, response = res.response;
  6799. let preCode = ruleParser.curSiteRule.pageElementPre || ruleParser.curSiteRule.pagePre;
  6800. if (preCode) {
  6801. try {
  6802. if (typeof preCode == 'function') {
  6803. response = preCode(response);
  6804. } else if (preCode.length == 2) {
  6805. response = response.replace(new RegExp(preCode[0], "gi"), preCode[1]);
  6806. } else {
  6807. response = Function("response",'"use strict";' + preCode)(response);
  6808. }
  6809. } catch(e) {
  6810. debug(e);
  6811. }
  6812. }
  6813. try {
  6814. doc = document.implementation.createHTMLDocument('');
  6815. doc.documentElement.innerHTML = response;
  6816. let base = doc.querySelector("base");
  6817. ruleParser.basePath = base ? base.href : url;
  6818. } catch (e) {
  6819. debug('parse error:' + e.toString());
  6820. }
  6821. if (charsetValid && !ruleHeaders) {
  6822. let equiv = doc.querySelector('[http-equiv="Content-Type"]');
  6823. if (equiv && equiv.content) {
  6824. let innerCharSet = equiv.content.match(/charset\=([^;]+)/);
  6825. if (innerCharSet && innerCharSet[1].replace("-", "").toLowerCase() != charset.replace("-", "").toLowerCase()) {
  6826. charset = innerCharSet[1];
  6827. return requestDoc(url, callback);
  6828. }
  6829. }
  6830. }
  6831. let pageElement = ruleParser.getPageElement(doc);
  6832. if ((!pageElement || pageElement.length == 0) && res.status >= 400) {
  6833. debug(res.status + " " + url, "Error status");
  6834. return callback(false);
  6835. }
  6836. if (inCors && (!pageElement || pageElement.length == 0) && ruleParser.curSiteRule.smart) {
  6837. let article;
  6838. for (let i = 0; i < mainSel.length; i++) {
  6839. article = doc.querySelectorAll(mainSel[i]);
  6840. if (article && article.length === 1) break;
  6841. }
  6842. if (article && article.length == 1) {
  6843. article = article[0];
  6844. ruleParser.curSiteRule.pageElement = article.nodeName.toLowerCase() + (article.id ? "#" + article.id : "") + (article.className ? "." + article.className.replace(/ /g, ".") : "") + ">*";
  6845. pageElement = article.children;
  6846. } else {
  6847. ruleParser.curSiteRule.pageElement = allOfBody;
  6848. pageElement = ruleParser.getPageElement(doc);
  6849. }
  6850. ruleParser.getInsert(true);
  6851. }
  6852. //只有1的話怕不是圖片哦
  6853. if (pageElement && (pageElement.length > 1 || (pageElement.length == 1 && !compareNodeName(pageElement[0], ["img"])))) {
  6854. await ruleParser.insertPage(doc, pageElement, url, callback, false);
  6855. if (ruleParser.curSiteRule.action == 1) {
  6856. isLoading = true;
  6857. requestFromIframe(url, async (doc, eles) => {
  6858. if (eles) {
  6859. await ruleParser.insertPage(doc, eles, url, callback, true);
  6860. } else isLoading = false;
  6861. });
  6862. } else ruleParser.curSiteRule.action = 0;
  6863. } else if ((ruleParser.curSiteRule.smart || curPage == 1) && !inCors) {
  6864. ruleParser.curSiteRule.action = 1;
  6865. requestFromIframe(url, async (doc, eles) => {
  6866. if (eles) {
  6867. await ruleParser.insertPage(doc, eles, url, callback, true);
  6868. } else isLoading = false;
  6869. });
  6870. } else {
  6871. debug("Stop as no page element");
  6872. ruleParser.noValidContent(url);
  6873. changeStop(true);
  6874. callback(false);
  6875. }
  6876. },
  6877. onerror: function(e) {
  6878. debug(e, "NetError");
  6879. callback(false);
  6880. },
  6881. ontimeout: function(e) {
  6882. debug(e, "NetTimeout");
  6883. callback(false);
  6884. }
  6885. });
  6886. }
  6887.  
  6888. function initPage() {
  6889. ruleParser.initPage(() => {
  6890. if (ruleParser.curSiteRule.autoLoadNum) {
  6891. autoLoadNum = ruleParser.curSiteRule.autoLoadNum;
  6892. }
  6893. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  6894. _GM_registerMenuCommand(i18n("nextSwitch"), () => {
  6895. nextSwitch.start();
  6896. });
  6897. }
  6898. if (ruleParser.nextLinkHref) {
  6899. let isJs = ruleParser.hrefIsJs(ruleParser.nextLinkHref);
  6900. if (!isJs) {
  6901. let inForce = (forceState == 2 || forceState == 3);
  6902. _GM_registerMenuCommand(i18n(inForce ? "cancelForceIframe" : "forceIframe"), () => {
  6903. if (inForce) {
  6904. setListData("forceState", location.host, "");
  6905. } else {
  6906. let _state = ruleParser.curSiteRule.action > 0 || confirm(i18n("forceAllBody")) ? 2 : 3;
  6907. setListData("forceState", location.host, _state);
  6908. }
  6909. setTimeout(() => {
  6910. location.reload();
  6911. }, 500);
  6912. });
  6913. }
  6914. _GM_registerMenuCommand(i18n("loadNow"), () => {
  6915. if (autoLoadNum != -1) {
  6916. autoLoadNum = -1;
  6917. return;
  6918. }
  6919. let loadNum = window.prompt(i18n("loadConfirm"), loadNowNum);
  6920. if (loadNum === "" || loadNum === null) return;
  6921. loadNum = Math.abs(parseInt(loadNum)) || 0;
  6922. if (loadNowNum != loadNum) {
  6923. loadNowNum = loadNum;
  6924. storage.setItem("loadNowNum", loadNowNum);
  6925. }
  6926. autoLoadNum = loadNum;
  6927. nextPage();
  6928. });
  6929. }
  6930. initListener();
  6931. });
  6932. }
  6933.  
  6934. var pageBarStyle, mainStyleEle, mainStyleStyle;
  6935. function initView() {
  6936. if (!mainStyleStyle) {
  6937. mainStyleStyle = `
  6938. .pagetual_pageBar{
  6939. -moz-transition:all 0.3s ease-in-out 0s;
  6940. -webkit-transition:all 0.3s ease-in-out 0s;
  6941. transition:all 0.3s ease-in-out 0s;
  6942. font-family: Arial,sans-serif !important;
  6943. text-align: center !important;
  6944. }
  6945. .pagetual_pageBar.stop {
  6946. -webkit-filter: invert(100%);
  6947. filter: invert(100%);
  6948. opacity: 1!important;
  6949. }
  6950. .pagetual_pageBar.hide {
  6951. display: none!important;
  6952. }
  6953. .pagetual-hide {
  6954. display: none!important;
  6955. }
  6956. .pagetual_pageBar:hover {
  6957. opacity: 1!important;
  6958. box-shadow: 0px 0px 10px 0px #000000aa;
  6959. border-radius: 20px;
  6960. background-color: rgb(240 240 240 / 80%);
  6961. border-color: transparent!important;
  6962. }
  6963. .pagetual_pageBar span {
  6964. vertical-align: super;
  6965. }
  6966. .pagetual_pageBar a::before,
  6967. .pagetual_pageBar a::after {
  6968. content: none;
  6969. }
  6970. .pagetual_pageBar a>span {
  6971. margin-top: 0!important;
  6972. pointer-events: none;
  6973. padding: unset;
  6974. opacity: 0;
  6975. -moz-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  6976. -webkit-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  6977. transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  6978. transform: none;
  6979. left: 0;
  6980. margin-left: calc(50% - 20px);
  6981. }
  6982. .pagetual_pageBar a>span:hover {
  6983. color: red;
  6984. }
  6985. .pagetual_pageBar a:hover>span {
  6986. opacity: 1!important;
  6987. }
  6988. .pagetual_pageBar span.prevScreen,
  6989. .pagetual_pageBar span.nextScreen {
  6990. display: block!important;
  6991. top: unset !important;
  6992. padding: unset !important;
  6993. opacity: 0!important;
  6994. }
  6995. .pagetual_pageBar a:hover>span.prevScreen {
  6996. margin-top: -${rulesData.opacity == 1 ? 31 : 30}px!important;
  6997. pointer-events: all;
  6998. }
  6999. .pagetual_pageBar span.refreshRing {
  7000. position: absolute;
  7001. top: 0;
  7002. opacity: 0;
  7003. height: 30px;
  7004. margin-left: calc(50% - 23px);
  7005. display: block!important;
  7006. }
  7007. .pagetual_pageBar span.refreshRing>svg {
  7008. background: white;
  7009. border-radius: 50%;
  7010. }
  7011. .pagetual_pageBar a:hover>span.refreshRing {
  7012. opacity: 0.3;
  7013. -webkit-animation: pagetual_ring 2.0s infinite linear;
  7014. animation: pagetual_ring 2.0s infinite linear;
  7015. }
  7016. @-webkit-keyframes pagetual_ring {
  7017. 0% { -webkit-transform: rotate(0deg) }
  7018. 100% {
  7019. -webkit-transform: rotate(360deg);
  7020. }
  7021. }
  7022. @keyframes pagetual_ring {
  7023. 0% {
  7024. transform: rotate(0deg);
  7025. -webkit-transform: rotate(0deg);
  7026. } 100% {
  7027. transform: rotate(360deg);
  7028. -webkit-transform: rotate(360deg);
  7029. }
  7030. }
  7031. .pagetual_pageBar a:hover>span.nextScreen {
  7032. margin-top: 30px!important;
  7033. pointer-events: all;
  7034. }
  7035. .pagetual_pageBar span>svg {
  7036. -moz-transition:transform 0.5s ease, opacity 0.3s ease;
  7037. -webkit-transition:transform 0.5s ease, opacity 0.3s ease;
  7038. transition:transform 0.5 ease, opacity 0.3s ease;
  7039. opacity: 0;
  7040. }
  7041. .pagetual_pageBar.stop span>svg{
  7042. opacity: 1;
  7043. }
  7044. .pagetual_pageBar.stop span>svg>path{
  7045. transform: scale(.8);
  7046. transform-origin: center;
  7047. -moz-transition:transform 0.3s ease;
  7048. -webkit-transition:transform 0.3s ease;
  7049. transition:transform 0.3 ease;
  7050. }
  7051. .pagetual_pageBar.stop:hover span>svg>path{
  7052. transform: unset;
  7053. }
  7054. .pagetual_pageBar:hover span>svg {
  7055. opacity: 1;
  7056. }
  7057. .pagetual_pageBar span>svg.upSvg:hover {
  7058. transform: rotate(360deg) scale3d(1.2, 1.2, 1.2);
  7059. }
  7060. .pagetual_pageBar span>svg.downSvg:hover {
  7061. transform: rotate(540deg) scale3d(1.2, 1.2, 1.2)!important;
  7062. }
  7063. .pagetual_pageBar .pagetual_pageNum{
  7064. color: #55555f;
  7065. }
  7066. .pagetual_pageBar .pagetual_pageNum:hover{
  7067. color: #ff6464;
  7068. }
  7069. .pagetual_tipsWords {
  7070. font-size: 50px;
  7071. font-weight: bold;
  7072. font-family: "黑体", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
  7073. "Oxygen", "Ubuntu", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
  7074. "Segoe UI Emoji", "Segoe UI Symbol";
  7075. color: #ffffff;
  7076. min-height: 70px;
  7077. max-width: 80%;
  7078. line-height: 1.5;
  7079. position: fixed;
  7080. left: 50%;
  7081. top: 10%;
  7082. margin-left: -99999px;
  7083. padding: 0 15px;
  7084. z-index: 2147483647;
  7085. background-color: #000;
  7086. border: 1px solid #303030;
  7087. border-radius: 10px;
  7088. opacity: 0;
  7089. filter: alpha(opacity=65);
  7090. box-shadow: 5px 5px 20px 0px #000;
  7091. -moz-transition:opacity 0.3s ease-in-out 0s;
  7092. -webkit-transition:opacity 0.3s ease-in-out 0s;
  7093. transition:opacity 0.3s ease-in-out 0s;
  7094. pointer-events: none;
  7095. word-break: break-all;
  7096. }
  7097. .pagetual_tipsWords>a {
  7098. color: #ffffff;
  7099. }
  7100. .pagetual_loading {
  7101. width: 50px;
  7102. height: 50px;
  7103. margin: 10px auto;
  7104. border-radius: 100%;
  7105. display: flex;
  7106. -webkit-animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  7107. animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  7108. }
  7109. @-webkit-keyframes pagetual_loading_scaleout {
  7110. 0% { -webkit-transform: scale(0.0) }
  7111. 100% {
  7112. -webkit-transform: scale(1.0);
  7113. opacity: 0;
  7114. }
  7115. }
  7116. @keyframes pagetual_loading_scaleout {
  7117. 0% {
  7118. transform: scale(0.0);
  7119. -webkit-transform: scale(0.0);
  7120. } 100% {
  7121. transform: scale(1.0);
  7122. -webkit-transform: scale(1.0);
  7123. opacity: 0;
  7124. }
  7125. }
  7126. .pagetual_loading_text {
  7127. white-space: nowrap;
  7128. -webkit-animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  7129. animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  7130. }
  7131. @-webkit-keyframes pagetual_loading_opacity {
  7132. 0% { opacity: 1 }
  7133. 50% { opacity: 0.2 }
  7134. 100% { opacity: 1 }
  7135. }
  7136. @keyframes pagetual_loading_opacity {
  7137. 0% { opacity: 1 }
  7138. 50% { opacity: 0.2 }
  7139. 100% { opacity: 1 }
  7140. }
  7141. `;
  7142. 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%);"}`;
  7143. }
  7144. if (!mainStyleEle || !mainStyleEle.parentNode) {
  7145. mainStyleEle = _GM_addStyle(mainStyleStyle);
  7146. }
  7147. }
  7148. var loadingDiv = document.createElement("div");
  7149. 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;";
  7150.  
  7151. 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;`;
  7152. function setLoadingDiv(loadingText) {
  7153. 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>`}`);
  7154. }
  7155.  
  7156. 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>`;
  7157. 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;`;
  7158. 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>`;
  7159. 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);`;
  7160.  
  7161. 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;`;
  7162. 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;`;
  7163. var sideControllerIcon = '';
  7164.  
  7165. var tipsWords = document.createElement("div");
  7166. tipsWords.className = "pagetual_tipsWords";
  7167.  
  7168. function changeStop(stop) {
  7169. isPause = stop;
  7170. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar,#pagetual-sideController"), bar => {
  7171. if (isPause) {
  7172. bar.classList.add("stop");
  7173. } else {
  7174. bar.classList.remove("stop");
  7175. }
  7176. });
  7177. if (!isPause) ruleParser.showAddedElements();
  7178. manualPause = isPause;
  7179. if (sideController.inited) setListData("pauseState", location.host, isPause ? true : "");
  7180. }
  7181.  
  7182. function changeHideBar(hide) {
  7183. isHideBar = hide;
  7184. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar"), bar => {
  7185. if (isHideBar) {
  7186. bar.classList.add("hide");
  7187. } else {
  7188. bar.classList.remove("hide");
  7189. }
  7190. });
  7191. }
  7192.  
  7193. function isInViewPort(element) {
  7194. if (!getBody(document).contains(element)) return false;
  7195. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  7196. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  7197. const {
  7198. top,
  7199. right,
  7200. bottom,
  7201. left,
  7202. } = element.getBoundingClientRect();
  7203.  
  7204. return (
  7205. top >= 0 &&
  7206. left >= 0 &&
  7207. right <= viewWidth + 1 &&
  7208. top <= viewHeight * rate &&
  7209. isVisible(element, _unsafeWindow)
  7210. );
  7211. }
  7212.  
  7213. function getPageBar() {
  7214. let preBar = null, nextBar = null;
  7215. let pageBars = [].slice.call(document.querySelectorAll(".pagetual_pageBar"));
  7216. for (let i = 0; i < pageBars.length; i++) {
  7217. let pageBar = pageBars[i];
  7218. if (!pageBar || !getBody(document).contains(pageBar)) continue;
  7219. let {
  7220. top,
  7221. right,
  7222. bottom,
  7223. left,
  7224. } = pageBar.getBoundingClientRect();
  7225. if (top > 500) {
  7226. nextBar = pageBar;
  7227. preBar = (i - 1 >= 0 ? pageBars[i - 1] : null);
  7228. if (pageBar && getBody(document).contains(pageBar)) {
  7229. let {
  7230. top,
  7231. right,
  7232. bottom,
  7233. left,
  7234. } = pageBar.getBoundingClientRect();
  7235. if (top < -500) {
  7236. preBar = pageBar;
  7237. } else preBar = (i - 2 >= 0 ? pageBars[i - 2] : null);
  7238. }
  7239. break;
  7240. }
  7241. }
  7242. if (!nextBar) preBar = pageBars[pageBars.length - 2];
  7243. return {preBar: preBar, nextBar: nextBar};
  7244. }
  7245.  
  7246. var urlChanged = false;
  7247. var urlChanging = false;
  7248. var urlchangeHandler = e => {
  7249. if (ruleParser && ruleParser.curSiteRule && ruleParser.curSiteRule.listenUrlChange == false) return;
  7250. isPause = true;
  7251. setTimeout(() => {
  7252. lastActiveUrl = location.href;
  7253. if (urlChanging) return;
  7254. urlChanging = true;
  7255. let href = location.href.slice(0, 60);
  7256. if (href == configPage[1]) {
  7257. setTimeout(() => {
  7258. initConfig(href);
  7259. urlChanging = false;
  7260. }, 1000);
  7261. } else {
  7262. setTimeout(() => {
  7263. if (guidePage.test(href)) {
  7264. setTimeout(() => {
  7265. initConfig(href);
  7266. urlChanging = false;
  7267. }, 1000);
  7268. } else {
  7269. ruleParser.urlChanged();
  7270. if (!ruleParser.nextLinkHref) {
  7271. isLoading = false;
  7272. }
  7273. urlChanging = false;
  7274. //if (!pageReady && !ruleImportUrlReg.test(href)) location.reload();
  7275. }
  7276. }, 500);
  7277. }
  7278. }, 1);
  7279. };
  7280. window.addEventListener('pagetual_pushState', urlchangeHandler);
  7281. /*var _wr = function(type) {
  7282. var orig = history[type];
  7283. return function() {
  7284. var rv = orig.apply(this, arguments);
  7285. var e = new Event('pagetual_' + type);
  7286. e.arguments = arguments;
  7287. window.dispatchEvent(e);
  7288. return rv;
  7289. };
  7290. };
  7291. history.pushState = _wr('pushState');*/
  7292.  
  7293. function listenUrl() {
  7294. var prevPathname = window.location.pathname;
  7295. var prevSearch = window.location.search;
  7296. var checkUrlTime = 100;
  7297. var checkUrlTimer;
  7298. var checkClickedEle = null;
  7299. var checkFunc = () => {
  7300. if (forceState == 1) return;
  7301. if (checkClickedEle) {
  7302. if (!clickedSth && checkClickedEle && checkClickedEle.nodeName) {
  7303. if (compareNodeName(checkClickedEle, ["a", "button"])) {
  7304. clickedSth = true;
  7305. } else {
  7306. let targetStyle = _unsafeWindow.getComputedStyle(checkClickedEle);
  7307. if (targetStyle.cursor == "pointer") clickedSth = true;
  7308. }
  7309. }
  7310. checkClickedEle = null;
  7311. }
  7312. if (checkUrlTime < 5000) {
  7313. checkUrlTime += checkUrlTime>>1;
  7314. }
  7315. clearTimeout(checkUrlTimer);
  7316. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7317. if (document.hidden) return;
  7318. if (!ruleParser.canListenUrlChange()) {
  7319. return;
  7320. }
  7321. if ((prevPathname !== window.location.pathname || prevSearch !== window.location.search) && window.location.href != ruleParser.historyUrl) {
  7322. checkUrlTime = 2000;
  7323. urlWillChange = true;
  7324. var e = new Event('pagetual_pushState');
  7325. e.arguments = arguments;
  7326. window.dispatchEvent(e);
  7327. clickedSth = false;
  7328. }
  7329. prevPathname = window.location.pathname;
  7330. prevSearch = window.location.search;
  7331. };
  7332. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7333.  
  7334. document.addEventListener("click", e => {
  7335. if (!checkClickedEle) {
  7336. checkClickedEle = e.target;
  7337. checkUrlTime = 300;
  7338. clearTimeout(checkUrlTimer);
  7339. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7340. }
  7341. });
  7342. }
  7343.  
  7344. let scrollContainer;
  7345. function distToBottom () {
  7346. let scrolly = window.scrollY;
  7347. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  7348. if (!scrollContainer || !document.documentElement.contains(scrollContainer)) {
  7349. if (curPage > 1 || ruleParser.nextLinkHref) {
  7350. let pageEle = ruleParser.getPageElement(document);
  7351. if (pageEle && pageEle.length) {
  7352. let parent = pageEle[0].parentNode, pageScrollY = parent.scrollTop;
  7353. while (parent && pageScrollY == 0) {
  7354. parent = parent.parentNode;
  7355. pageScrollY = parent.scrollTop;
  7356. }
  7357. if (pageScrollY) {
  7358. scrollContainer = parent;
  7359. return scrollContainer.scrollHeight - pageScrollY - windowHeight;
  7360. }
  7361. }
  7362. }
  7363. }
  7364. if (scrollContainer) {
  7365. return scrollContainer.scrollHeight - scrollContainer.scrollTop - windowHeight;
  7366. }
  7367.  
  7368. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7369. return scrollH - scrolly - windowHeight;
  7370. }
  7371.  
  7372. let scrollHandler, clickToResetHandler, dblclickHandler, keydownHandler, hashchangeHandler, manualModeKeyHandler, pagetualNextHandler, keyupHandler;
  7373. function initListener () {
  7374. document.removeEventListener('scroll', scrollHandler, true);
  7375. document.removeEventListener('wheel', scrollHandler, true);
  7376. document.removeEventListener('dblclick', dblclickHandler);
  7377. document.removeEventListener('keydown', keydownHandler);
  7378. window.removeEventListener('hashchange', hashchangeHandler, false);
  7379. document.removeEventListener('keydown', manualModeKeyHandler);
  7380. document.removeEventListener('pagetual.next', pagetualNextHandler, false);
  7381. document.removeEventListener('keyup', keyupHandler);
  7382. let loadmoreBtn, loadingMore = true, lastScroll = 0, checkLoadMoreTimes = 0;
  7383. if (ruleParser.curSiteRule.smart) {
  7384. loadingMore = false;
  7385. } else if (ruleParser.curSiteRule.loadMore) {
  7386. loadingMore = false;
  7387. }
  7388. clickMode = typeof ruleParser.curSiteRule.clickMode == 'undefined' ? rulesData.clickMode : ruleParser.curSiteRule.clickMode;
  7389. let clickingNext = false;
  7390. let clickNext = async () => {
  7391. if (clickingNext) return;
  7392. clickingNext = true;
  7393. setTimeout(() => {
  7394. clickingNext = false;
  7395. }, 1500);
  7396. let nextLink = ruleParser.nextLinkHref;
  7397. if (!nextLink) return;
  7398. let isJs = ruleParser.hrefIsJs(nextLink);
  7399. if (isJs) {
  7400. let nextBtn = ruleParser.nextLinkEle;
  7401. if (!nextBtn || !nextBtn.offsetParent) nextBtn = await ruleParser.getNextLink(document, true);
  7402. if (nextBtn) emuClick(nextBtn);
  7403. } else {
  7404. window.location.href = nextLink;
  7405. }
  7406. };
  7407. let checkScrollReach = () => {
  7408. let dist = distToBottom();
  7409. if (clickMode) {
  7410. if (dist < 10) {
  7411. clickNext();
  7412. }
  7413. } else if (dist < bottomGap) {
  7414. nextPage();
  7415. }
  7416. };
  7417. scrollHandler = e => {
  7418. if (urlChanged && !isLoading) {
  7419. ruleParser.initPage(() => {});
  7420. urlChanged = false;
  7421. loadingMore = false;
  7422. return;
  7423. }
  7424. if (isPause) return;
  7425. if (!loadingMore) {
  7426. loadmoreBtn = getLoadMore(document, loadmoreBtn);
  7427. if (loadmoreBtn) {
  7428. if (isInViewPort(loadmoreBtn)) {
  7429. emuClick(loadmoreBtn);
  7430. loadingMore = true;
  7431. setTimeout(() => {loadingMore = false}, 200);
  7432. }
  7433. } else {
  7434. loadingMore = true;
  7435. if (!ruleParser.curSiteRule.smart || checkLoadMoreTimes++ < 3) {
  7436. setTimeout(() => {loadingMore = false}, 200);
  7437. }
  7438. }
  7439. }
  7440. if (!isLoading && !stopScroll) {
  7441. checkScrollReach();
  7442. }
  7443. ruleParser.changeVisibility();
  7444. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  7445. if (ruleParser.curSiteRule.lockScroll) {
  7446. if (isLoading && Math.abs(lastScroll - curScroll) > 350) {
  7447. getBody(document).scrollTop = lastScroll;
  7448. document.documentElement.scrollTop = lastScroll;
  7449. } else {
  7450. lastScroll = curScroll;
  7451. }
  7452. }
  7453. if (targetY >= 0) {
  7454. if (Math.abs(targetY - curScroll) < 100) {
  7455. targetY = -1;
  7456. }
  7457. }
  7458. };
  7459. dblclickHandler = e => {
  7460. if (forceState == 1 || compareNodeName(e.target, ["input", "textarea", "select", "a", "button", "svg", "use", "img", "path"])) return;
  7461. if (!rulesData.dbClick2StopKey) {
  7462. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  7463. (rulesData.dbClick2StopAlt && !e.altKey) ||
  7464. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  7465. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  7466. return;
  7467. }
  7468. }
  7469. if (!compareNodeName(e.target, ["body"]) && !e.target.classList.contains('pagetual_pageBar')) {
  7470. try {
  7471. let selection = window.getSelection();
  7472. let selStr = selection.toString().trim();
  7473. if (!selStr) {
  7474. selection = selection.getRangeAt(0);
  7475. selStr = selection && selection.cloneContents().children[0];
  7476. if (selStr && !compareNodeName(selStr, ["img"])) selStr = false;
  7477. }
  7478. if (selStr) {
  7479. return;
  7480. }
  7481. } catch (e) {}
  7482. }
  7483. if (rulesData.dbClick2Stop && (ruleParser.nextLinkHref || loadmoreBtn)) {
  7484. setTimeout(() => {
  7485. if (rulesData.hideBarButNoStop || rulesData.hideBar) {
  7486. changeHideBar(!isHideBar);
  7487. }
  7488. if (!rulesData.hideBarButNoStop) {
  7489. changeStop(!isPause);
  7490. showTips(i18n(isPause ? "disable" : "enable"));
  7491. }
  7492. if (!isPause) {
  7493. checkScrollReach();
  7494. }
  7495. }, 10);
  7496. }
  7497. };
  7498. document.addEventListener('dblclick', dblclickHandler);
  7499. clickToResetHandler = e => {
  7500. if (!ruleParser.nextLinkHref) isLoading = false;
  7501. };
  7502. document.addEventListener('click', clickToResetHandler);
  7503. if (rulesData.dbClick2StopKey) {
  7504. keydownHandler = e => {
  7505. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  7506. (rulesData.dbClick2StopAlt && !e.altKey) ||
  7507. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  7508. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  7509. return;
  7510. }
  7511. if (document.activeElement &&
  7512. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  7513. document.activeElement.contentEditable == 'true')) {
  7514. return;
  7515. }
  7516. var key = e.key.toLowerCase();
  7517. if (rulesData.dbClick2StopKey.toLowerCase() == key) {
  7518. if (forceState == 1) {
  7519. forceState = 0;
  7520. showTips(i18n("enableSiteTips"));
  7521. changeStop(false);
  7522. } else {
  7523. forceState = 1;
  7524. showTips(i18n("disableSiteTips"));
  7525. changeStop(true);
  7526. sideController.remove();
  7527. }
  7528. if (!ruleParser.curSiteRule.url) {
  7529. setListData("forceState", location.host, forceState);
  7530. setTimeout(() => {
  7531. location.reload();
  7532. }, 500);
  7533. }
  7534. }
  7535. };
  7536. document.addEventListener('keydown', keydownHandler);
  7537. }
  7538. if (ruleParser.curSiteRule.listenHashChange) {
  7539. hashchangeHandler = () => {
  7540. isPause = true;
  7541. ruleParser.urlChanged();
  7542. if (!ruleParser.nextLinkHref) isLoading = false;
  7543. };
  7544. window.addEventListener('hashchange', hashchangeHandler, false);
  7545. }
  7546. let manualMode = typeof ruleParser.curSiteRule.manualMode == 'undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode;
  7547. if (manualMode) {
  7548. manualModeKeyHandler = 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. clickNext();
  7556. } else if (e.keyCode == 37) {
  7557. history.back();
  7558. }
  7559. };
  7560. document.addEventListener('keydown', manualModeKeyHandler);
  7561. pagetualNextHandler = () => {
  7562. clickNext();
  7563. };
  7564. document.addEventListener('pagetual.next', pagetualNextHandler, false);
  7565. return;
  7566. }
  7567. if (rulesData.arrowToScroll) {
  7568. keyupHandler = e => {
  7569. if (document.activeElement &&
  7570. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  7571. document.activeElement.contentEditable == 'true')) {
  7572. return;
  7573. }
  7574. if (e.keyCode == 39) {
  7575. let nextPageBar=getPageBar().nextBar;
  7576. if (nextPageBar) {
  7577. scrollToPageBar(nextPageBar);
  7578. } else {
  7579. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  7580. window.scrollTo({ top: scrollTop + (window.innerHeight || document.documentElement.clientHeight), behavior: 'instant'});
  7581. }
  7582. } else if (e.keyCode == 37) {
  7583. let prePageBar = getPageBar().preBar;
  7584. if (prePageBar) {
  7585. scrollToPageBar(prePageBar);
  7586. } else {
  7587. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  7588. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'instant'});
  7589. }
  7590. }
  7591. };
  7592. document.addEventListener('keyup', keyupHandler);
  7593. }
  7594. if (!ruleParser.curSiteRule.wheel) {
  7595. document.addEventListener('scroll', scrollHandler, true);
  7596. }
  7597. document.addEventListener('wheel', scrollHandler, true);
  7598. }
  7599.  
  7600. let hideTipsTimeout;
  7601. function showTips(content, href, time, wordColor, backColor) {
  7602. initView();
  7603. document.documentElement.appendChild(tipsWords);
  7604. tipsWords.style.color = wordColor || 0xFFFFFF;
  7605. tipsWords.style.backgroundColor = backColor || 0x000;
  7606. let _time = 1500;
  7607. if (href) {
  7608. _time = 3500;
  7609. tipsWords.innerHTML = createHTML(`<a href='${href}' target='_blank'>${content}</a>`);
  7610. tipsWords.style.pointerEvents = 'all';
  7611. } else {
  7612. tipsWords.innerHTML = createHTML(content);
  7613. }
  7614. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  7615. setTimeout(() => {
  7616. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  7617. }, 0);
  7618. setTimeout(() => {
  7619. tipsWords.style.opacity = 0.8;
  7620. clearTimeout(hideTipsTimeout);
  7621. hideTipsTimeout = setTimeout(() => {
  7622. tipsWords.style.opacity = 0;
  7623. tipsWords.style.pointerEvents = '';
  7624. }, time || _time);
  7625. }, 1);
  7626. }
  7627.  
  7628. const loadmoreReg = /^\s*((点击)?加载更多|(點擊)?加載更多|load\s*more|もっと読み込む)[.…]*\s*$/i;
  7629. 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";
  7630. function getLoadMore(doc, loadmoreBtn) {
  7631. if (!loadmoreBtn || !getBody(doc).contains(loadmoreBtn) || /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  7632. if (!ruleParser.curSiteRule.smart && !ruleParser.curSiteRule.loadMore) return null;
  7633. if (loadmoreBtn) return loadmoreBtn;
  7634. let btnSel = ruleParser.curSiteRule.loadMore || defaultLoadmoreSel;
  7635. if (btnSel) {
  7636. loadmoreBtn = getElement(btnSel, doc, null, true);
  7637. }
  7638. if (!loadmoreBtn) {
  7639. let buttons = doc.querySelectorAll("input,button,a,div[onclick]");
  7640. for (let i = 0; i < buttons.length; i++) {
  7641. let button = buttons[i];
  7642. if (!button.innerText || button.innerText.length > 20) continue;
  7643. if (button && loadmoreReg.test(button.innerText)) {
  7644. loadmoreBtn = button;
  7645. break;
  7646. }
  7647. }
  7648. }
  7649. if (loadmoreBtn && !ruleParser.curSiteRule.loadMore && loadmoreBtn.dataset.ajax !== "true") {
  7650. let href = loadmoreBtn.getAttribute("href");
  7651. if (href && href != "/" && !ruleParser.hrefIsJs(href)) {
  7652. loadmoreBtn = null;
  7653. }
  7654. }
  7655. if (loadmoreBtn && /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  7656. if (loadmoreBtn) debug(loadmoreBtn, 'Load more button');
  7657. return loadmoreBtn;
  7658. }
  7659.  
  7660. var targetY = -1;
  7661. function scrollToPageBar(bar) {
  7662. if (window.pageYOffset == 0) {
  7663. bar.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" });
  7664. } else {
  7665. let yOffset = -20;
  7666. if (typeof ruleParser.curSiteRule.pageBarTop !== 'undefined') {
  7667. yOffset = -ruleParser.curSiteRule.pageBarTop;
  7668. }
  7669. targetY = bar.getBoundingClientRect().top + window.pageYOffset + yOffset;
  7670. window.scrollTo({ top: targetY, behavior: 'smooth'});
  7671. }
  7672. }
  7673.  
  7674. const pageNumReg=/[&\/\?](p=|page[=\/_-]?)\d+|[_-]\d+\./;
  7675. function createPageBar(url) {
  7676. curPage++;
  7677. sideController.setup();
  7678. let posEle = null;
  7679. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7680. let insert = ruleParser.getInsert();
  7681. if (!insert || !insert.parentNode) return;
  7682. if (forceState == 2) {
  7683. posEle = getBody(document);
  7684. posEle = posEle.children[posEle.children.length - 1];
  7685. } else {
  7686. posEle = insert;
  7687. }
  7688. while (posEle && !posEle.offsetParent) {
  7689. posEle = posEle.previousElementSibling || posEle.parentNode;
  7690. }
  7691. if (posEle) {
  7692. let actualBottom = getElementBottom(posEle);
  7693. bottomGap = scrollH - actualBottom + (window.innerHeight || document.documentElement.clientHeight) * rate;
  7694. if (bottomGap < 100) bottomGap = 100;
  7695. } else {
  7696. bottomGap = 1000;
  7697. }
  7698. if (rulesData.opacity == 0 || ruleParser.curSiteRule.pageBar === 0) return null;
  7699. url = url.replace(/#p{.*/, "");
  7700. let example = (ruleParser.curSiteRule.insertPos == 2 || ruleParser.curSiteRule.insertPos == "in") ? insert.children[0] : (insert.parentNode.children[0] || insert);
  7701. while (example && (compareNodeName(example, ["script", "style"]) || example.className == "pagetual_pageBar")) {
  7702. example = example.nextElementSibling;
  7703. }
  7704. if (!example || !example.parentNode) example = insert;
  7705. if (example.nodeType != 1) {
  7706. example = example.previousElementSibling || example.parentNode;
  7707. if (!example || example.nodeType != 1) return;
  7708. }
  7709. let exampleStyle = _unsafeWindow.getComputedStyle(example);
  7710. let inTable, inLi;
  7711. if (forceState == 2) {
  7712. inTable = inLi = false;
  7713. } else {
  7714. inTable = compareNodeName(example.parentNode, ["table", "tbody"]) ||
  7715. compareNodeName(example, ["tr", "tbody"]) ||
  7716. exampleStyle.display == "table-row" ||
  7717. (example.nextElementSibling && compareNodeName(example.nextElementSibling, ["tr", "tbody"]));
  7718. inLi = compareNodeName(example, ["li"]) || (example.nextElementSibling && compareNodeName(example.nextElementSibling, ["li"]));
  7719. }
  7720. let pageBar = document.createElement(inTable ? "tr" : (inLi ? "li" : "div"));
  7721. let upSpan = document.createElement("span");
  7722. let downSpan = document.createElement("span");
  7723. let pageText = document.createElement("a");
  7724. let pageNum;
  7725. pageBar.className = isHideBar ? "pagetual_pageBar hide" : "pagetual_pageBar";
  7726. pageBar.id = "pagetual_pageBar" + curPage;
  7727. pageBar.setAttribute("translate", "no");
  7728. if (isPause) {
  7729. pageBar.classList.add("stop");
  7730. }
  7731. pageBar.style.cssText = pageBarStyle;
  7732. pageBar.title = i18n(isPause ? "enable" : "disable");
  7733. upSpan.innerHTML = createHTML(upSvg);
  7734. upSpan.children[0].style.cssText = upSvgCSS;
  7735. upSpan.title = i18n("toTop");
  7736. downSpan.innerHTML = createHTML(downSvg);
  7737. downSpan.children[0].style.cssText = downSvgCSS;
  7738. downSpan.title = i18n("toBottom");
  7739. upSpan.style.cssText = initStyle;
  7740. downSpan.style.cssText = initStyle;
  7741. pageText.href = url;
  7742. pageText.style.cssText = pageTextStyle;
  7743. pageText.title = i18n("current");
  7744. if (openInNewTab == 1) pageText.target = "_blank";
  7745. pageBar.appendChild(upSpan);
  7746. pageBar.appendChild(pageText);
  7747. let touched = false;
  7748. let touchBodyHandler = e => {
  7749. touched = false;
  7750. getBody(document).removeEventListener('touchstart', touchBodyHandler, { passive: false, capture: false });
  7751. };
  7752. pageText.addEventListener("touchstart", e => {
  7753. if (touched) return;
  7754. touched = true;
  7755. pageText.style.pointerEvents = 'none';
  7756. setTimeout(() => {
  7757. pageText.style.pointerEvents = 'all';
  7758. }, 250);
  7759. getBody(document).addEventListener("touchstart", touchBodyHandler, { passive: false, capture: false });
  7760. }, { passive: false, capture: false });
  7761. if (ruleParser.nextTitle) {
  7762. pageText.innerHTML = createHTML(ruleParser.nextTitle + " ");
  7763. pageText.title = ruleParser.nextTitle;
  7764. }
  7765. if (ruleParser.curSiteRule.pageNum || pageNumReg.test(url)) {
  7766. pageText.innerHTML = createHTML(pageText.innerHTML + i18n("page"));
  7767. pageNum = document.createElement("span");
  7768. let num = ruleParser.getPageNumFromUrl(url, curPage);
  7769. pageNum.innerHTML = createHTML(num + "<i style='font-size: 0;'>&nbsp;</i>");
  7770. pageNum.className = "pagetual_pageNum";
  7771. pageNum.title = i18n("inputPageNum");
  7772. pageNum.style.cssText = pageTextStyle;
  7773. pageNum.style.cursor = "pointer";
  7774. pageNum.style.color = "";
  7775. pageNum.style.marginLeft = "5px";
  7776. pageNum.addEventListener("click", e => {
  7777. let pageInput = prompt(i18n("inputPageNum"), num || "1");
  7778. if (pageInput) {
  7779. let localPageBar = document.querySelector("#pagetual_pageBar" + pageInput);
  7780. if (localPageBar) {
  7781. scrollToPageBar(localPageBar);
  7782. } else {
  7783. let pageLink = ruleParser.getLinkByPage(url, pageInput);
  7784. if (pageLink) {
  7785. _GM_openInTab(pageLink, {active:true});
  7786. }
  7787. }
  7788. }
  7789. e.preventDefault();
  7790. e.stopPropagation();
  7791. });
  7792. pageBar.appendChild(pageNum);
  7793. } else {
  7794. pageText.innerHTML = createHTML(pageText.innerHTML + i18n("page") + curPage + "<i style='font-size: 0;'>&nbsp;</i>");
  7795. }
  7796. let preBtn = document.createElement("span");
  7797. preBtn.innerHTML = createHTML("∧");
  7798. preBtn.title = i18n("prevPage");
  7799. preBtn.className = "prevScreen";
  7800. 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; ";
  7801. let nextBtn = document.createElement("span");
  7802. nextBtn.innerHTML = createHTML("∨");
  7803. nextBtn.title = i18n("nextPage");
  7804. nextBtn.className = "nextScreen";
  7805. 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; ";
  7806. let localPage = curPage;
  7807. preBtn.addEventListener("click", e => {
  7808. e.stopPropagation();
  7809. e.preventDefault();
  7810. let prePageBar = document.querySelector("#pagetual_pageBar" + (localPage - 1));
  7811. if (prePageBar) {
  7812. scrollToPageBar(prePageBar);
  7813. } else {
  7814. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  7815. targetY = scrollTop - (window.innerHeight || document.documentElement.clientHeight);
  7816. window.scrollTo({ top: targetY, behavior: 'smooth'});
  7817. }
  7818. });
  7819. nextBtn.addEventListener("click", e => {
  7820. e.stopPropagation();
  7821. e.preventDefault();
  7822. let nextPageBar = document.querySelector("#pagetual_pageBar" + (localPage + 1));
  7823. if (nextPageBar) {
  7824. scrollToPageBar(nextPageBar);
  7825. } else {
  7826. scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7827. targetY = scrollH || 9999999;
  7828. window.scrollTo({ top: targetY, behavior: 'smooth'});
  7829. }
  7830. });
  7831. if (!rulesData.hideBarArrow) {
  7832. pageText.insertBefore(preBtn, pageText.firstChild);
  7833. pageText.insertBefore(nextBtn, pageText.firstChild);
  7834. }
  7835. if (curForceIframe) {
  7836. let bgRing = document.createElement("span");
  7837. bgRing.className = "refreshRing";
  7838. bgRing.style.display = "none";
  7839. bgRing.innerHTML = createHTML(upSvg);
  7840. pageText.title = "Refresh";
  7841. pageText.appendChild(bgRing);
  7842. pageText.addEventListener("click", e => {
  7843. e.stopPropagation();
  7844. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  7845. e.preventDefault();
  7846. let nextEle = pageBar && pageBar.nextElementSibling;
  7847. if (nextEle && nextEle.name == 'pagetual-iframe') {
  7848. if (curForceIframe == nextEle) {
  7849. nextEle.setAttribute("loaded", "refresh");
  7850. }
  7851. nextEle.src = nextEle.src;
  7852. }
  7853. });
  7854. } else if (rulesData.pageBarMenu) {
  7855. pageText.addEventListener("click", e => {
  7856. e.stopPropagation();
  7857. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  7858. e.preventDefault();
  7859. picker.start();
  7860. });
  7861. }
  7862. pageBar.appendChild(downSpan);
  7863. if (forceState == 2) {
  7864. pageBar.style.width = "99%";
  7865. } else {
  7866. let parentStyle = _unsafeWindow.getComputedStyle(example.parentNode);
  7867. let parentWidth = example.parentNode.offsetWidth || parseInt(parentStyle.width);
  7868. pageBar.style.width = parentWidth - parseInt(parentStyle.paddingLeft) - parseInt(parentStyle.paddingRight) - 10 + "px";
  7869. pageBar.style.margin = '10px 5px';
  7870. if (parentStyle.display == "grid" || parentStyle.display == "inline-grid") {
  7871. pageBar.style.gridColumn = "1/-1";
  7872. }
  7873. if (inTable) {
  7874. example = compareNodeName(example, ["tr", "tbody"]) ? example : example.nextElementSibling || example;
  7875. if (compareNodeName(example, ["tbody"])) example = example.querySelector("tr");
  7876. let nextTr = example;
  7877. while (nextTr && nextTr.children.length == 0) nextTr = nextTr.nextElementSibling;
  7878. if (nextTr) example = nextTr;
  7879. let tdNum = 0;
  7880. if (exampleStyle.display == "table-row") {
  7881. [].forEach.call(example.children, el => {
  7882. tdNum += el.colSpan || 1;
  7883. });
  7884. } else {
  7885. [].forEach.call(example.children, el => {
  7886. if (compareNodeName(el, ["td", "th"])) {
  7887. tdNum += el.colSpan || 1;
  7888. }
  7889. });
  7890. }
  7891. pageBar.style.cssText = "";
  7892. pageBar.style.display = "table-row";
  7893. pageBar.style.backgroundColor = "unset";
  7894. pageBar.style.lineHeight = "20px";
  7895. pageBar.style.boxShadow = "";
  7896. let td = document.createElement("td");
  7897. td.colSpan = tdNum || 1;
  7898. let inTd = document.createElement("div");
  7899. inTd.style.cssText = pageBarStyle;
  7900. inTd.style.display = "";
  7901. inTd.className = pageBar.className;
  7902. pageBar.className = "";
  7903. inTd.appendChild(upSpan);
  7904. inTd.appendChild(pageText);
  7905. if (pageNum) inTd.appendChild(pageNum);
  7906. inTd.appendChild(downSpan);
  7907. td.appendChild(inTd);
  7908. pageBar.appendChild(td);
  7909. } else if (inLi) {
  7910. example = compareNodeName(example, ["li"]) ? example : example.nextElementSibling || example;
  7911. pageBar.style.opacity = 1;
  7912. pageBar.style.display = getComputedStyle(example).display;
  7913. pageBar.style.backgroundColor = "unset";
  7914. pageBar.style.lineHeight = "20px";
  7915. pageBar.style.boxShadow = "";
  7916. pageBar.style.border = "";
  7917. pageBar.style.width = "";
  7918. pageBar.style.maxWidth = "unset";
  7919. pageBar.style.flex = "auto";
  7920. let inTd = document.createElement("div");
  7921. inTd.style.cssText = pageBarStyle;
  7922. inTd.style.display = "";
  7923. inTd.style.margin = "0"
  7924. inTd.style.padding = "0 0";
  7925. inTd.style.textAlign = "center";
  7926. inTd.style.minWidth = "150px";
  7927. inTd.style.width = 'calc(100% - 20px)';
  7928. inTd.className = pageBar.className;
  7929. pageBar.className = "";
  7930. inTd.appendChild(upSpan);
  7931. inTd.appendChild(pageText);
  7932. if (pageNum) inTd.appendChild(pageNum);
  7933. inTd.appendChild(downSpan);
  7934. if (pageBar.style.display === 'table-row') {
  7935. let td = document.createElement("td");
  7936. td.colSpan = example.children.length;
  7937. td.style.width = '100%';
  7938. td.appendChild(inTd);
  7939. pageBar.appendChild(td);
  7940. } else {
  7941. inTd.style.width = '100%';
  7942. pageBar.appendChild(inTd);
  7943. }
  7944. }
  7945. }
  7946.  
  7947. upSpan.addEventListener("click", e => {
  7948. getBody(document).scrollTop = 0;
  7949. document.documentElement.scrollTop = 0;
  7950. e.preventDefault();
  7951. e.stopPropagation();
  7952. });
  7953. downSpan.addEventListener("click", e => {
  7954. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  7955. changeStop(true);
  7956. }
  7957. pageBar.title = i18n(isPause ? "enable" : "disable");
  7958. scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7959. getBody(document).scrollTop = scrollH || 9999999;
  7960. document.documentElement.scrollTop = scrollH || 9999999;
  7961. e.preventDefault();
  7962. e.stopPropagation();
  7963. });
  7964. pageBar.addEventListener("click", e => {
  7965. changeStop(!isPause);
  7966. pageBar.title = i18n(isPause ? "enable" : "disable");
  7967. });
  7968. ruleParser.insertElement(pageBar);
  7969. ruleParser.runPageBar(pageBar);
  7970.  
  7971. return pageBar;
  7972. }
  7973.  
  7974. async function waitForElement(sel, doc) {
  7975. if (!sel) return null;
  7976. return new Promise((resolve) => {
  7977. let checkInv = setInterval(() => {
  7978. let result = getElement(sel, doc, null, true);
  7979. if (result) {
  7980. clearInterval(checkInv);
  7981. resolve(result);
  7982. }
  7983. }, 100);
  7984. });
  7985. }
  7986.  
  7987. async function clickAction(sel, doc) {
  7988. let btn = await waitForElement(sel, doc);
  7989. emuClick(btn, doc);
  7990. }
  7991.  
  7992. async function enterAction(sel, doc) {
  7993. let btn = await waitForElement(sel, doc);
  7994. let eventParam = { key: "Enter", keyCode: 13, bubbles: true };
  7995. let event = new KeyboardEvent('keydown', eventParam);
  7996. btn.dispatchEvent(event);
  7997. event = new KeyboardEvent('keyup', eventParam);
  7998. btn.dispatchEvent(event);
  7999. event = new KeyboardEvent('keypress', eventParam);
  8000. btn.dispatchEvent(event);
  8001. }
  8002.  
  8003. async function inputAction(sel, v, doc) {
  8004. let input = await waitForElement(sel, doc);
  8005. let event = new Event('focus', { bubbles: true });
  8006. input.dispatchEvent(event);
  8007. let lastValue = input.value;
  8008. if (input.nodeName.toUpperCase() == "INPUT") {
  8009. var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
  8010. nativeInputValueSetter.call(input, v);
  8011. } else if (input.nodeName.toUpperCase() == "TEXTAREA") {
  8012. var nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
  8013. nativeTextareaValueSetter.call(input, v);
  8014. } else {
  8015. input.innerHTML = createHTML(v);
  8016. }
  8017. event = new Event('input', { bubbles: true });
  8018. let tracker = input._valueTracker;
  8019. if (tracker) {
  8020. tracker.setValue(lastValue);
  8021. }
  8022. input.dispatchEvent(event);
  8023. event = new Event('change', { bubbles: true });
  8024. input.dispatchEvent(event);
  8025. debug(input, `input ${sel}`);
  8026. }
  8027.  
  8028. function emuClick(btn, doc) {
  8029. if (!doc) doc = document;
  8030. let curScroll = getBody(doc).scrollTop || doc.documentElement.scrollTop;
  8031. let orgHref = btn.getAttribute('href');
  8032. if (orgHref && orgHref.replace(location.origin + location.pathname, "").indexOf("#") === 0) {
  8033. let hashAction = e => {
  8034. e.preventDefault();
  8035. getBody(doc).scrollTop = curScroll;
  8036. doc.documentElement.scrollTop = curScroll;
  8037. btn.removeEventListener('click', hashAction, false);
  8038. };
  8039. btn.addEventListener('click', hashAction, false);
  8040. }
  8041. if (!PointerEvent) return btn.click();
  8042. let eventParam = {
  8043. isTrusted: true,
  8044. altKey: false,
  8045. azimuthAngle: 0,
  8046. bubbles: true,
  8047. button: 0,
  8048. buttons: 0,
  8049. clientX: 1,
  8050. clientY: 1,
  8051. cancelBubble: false,
  8052. cancelable: true,
  8053. composed: true,
  8054. ctrlKey: false,
  8055. defaultPrevented: false,
  8056. detail: 1,
  8057. eventPhase: 2,
  8058. fromElement: null,
  8059. height: 1,
  8060. isPrimary: false,
  8061. metaKey: false,
  8062. pointerId: 1,
  8063. pointerType: "mouse",
  8064. pressure: 0,
  8065. relatedTarget: null,
  8066. returnValue: true,
  8067. shiftKey: false,
  8068. toElement: null,
  8069. twist: 0,
  8070. which: 1
  8071. };
  8072. let mouseEvent = new PointerEvent("mousedown", eventParam);
  8073. btn.dispatchEvent(mouseEvent);
  8074. mouseEvent = new PointerEvent("mouseup", eventParam);
  8075. btn.dispatchEvent(mouseEvent);
  8076. let dispatchTouchEvent = (ele, type) => {
  8077. let touchEvent;
  8078. try {
  8079. touchEvent = document.createEvent('TouchEvent')
  8080. touchEvent.initTouchEvent(type, true, true)
  8081. } catch (err) {
  8082. try {
  8083. touchEvent = document.createEvent('UIEvent')
  8084. touchEvent.initUIEvent(type, true, true)
  8085. } catch (err) {
  8086. touchEvent = document.createEvent('Event')
  8087. touchEvent.initEvent(type, true, true)
  8088. }
  8089. }
  8090. if (touchEvent) {
  8091. try {
  8092. touchEvent.targetTouches = [{
  8093. pageX: 1,
  8094. pageY: 1,
  8095. clientX: 1,
  8096. clientY: 1,
  8097. target: btn
  8098. }];
  8099. touchEvent.touches = [{
  8100. pageX: 1,
  8101. pageY: 1,
  8102. clientX: 1,
  8103. clientY: 1,
  8104. target: btn
  8105. }];
  8106. touchEvent.changedTouches = [{
  8107. pageX: 1,
  8108. pageY: 1,
  8109. clientX: 1,
  8110. clientY: 1,
  8111. target: btn
  8112. }];
  8113. } catch (err) {}
  8114. ele.dispatchEvent(touchEvent);
  8115. }
  8116. }
  8117. dispatchTouchEvent(btn, "touchstart");
  8118. dispatchTouchEvent(btn, "touchend");
  8119.  
  8120. btn.click();
  8121. }
  8122.  
  8123. function emuInput(input, v) {
  8124. let result = false;
  8125. if (!input) return true;
  8126. let event = new Event('focus', { bubbles: true });
  8127. input.dispatchEvent(event);
  8128. let lastValue = input.value;
  8129. if (input.type == 'file') {
  8130. let file = v;
  8131. let blob = new Blob([file], {
  8132. type: 'text/plain'
  8133. });
  8134. file = new File([blob], 'noname.txt', { type: blob.type });
  8135. let dataTransfer = new DataTransfer();
  8136. dataTransfer.items.add(file);
  8137. input.files = dataTransfer.files;
  8138. v = "c:/fakepath/fakefile";
  8139. } else if (/INPUT/i.test(input.nodeName)) {
  8140. var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
  8141. nativeInputValueSetter.call(input, v);
  8142. } else if (/SELECT/i.test(input.nodeName)) {
  8143. var nativeSelectValueSetter = Object.getOwnPropertyDescriptor(window.HTMLSelectElement.prototype, "value").set;
  8144. nativeSelectValueSetter.call(input, v);
  8145. } else if (input.nodeName.toUpperCase() == "TEXTAREA") {
  8146. var nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
  8147. nativeTextareaValueSetter.call(input, v);
  8148. } else {
  8149. input.innerHTML = createHTML(v);
  8150. }
  8151. event = new Event('input', { bubbles: true });
  8152. let tracker = input._valueTracker;
  8153. if (tracker) {
  8154. tracker.setValue(lastValue);
  8155. }
  8156. input.dispatchEvent(event);
  8157. event = new Event('change', { bubbles: true });
  8158. input.dispatchEvent(event);
  8159. return result;
  8160. }
  8161.  
  8162. var failFromIframe = 0;
  8163. var inCors = false;
  8164. var checkRemoveIntv;
  8165. function requestFromIframe(url, callback){
  8166. if (location.protocol === 'https:' && !/^https:/.test(url)) {
  8167. ruleParser.noValidContent(url);
  8168. }
  8169. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  8170. let iframe = document.createElement('iframe');
  8171. iframe.name = 'pagetual-iframe';
  8172. iframe.width = '100%';
  8173. iframe.height = '1000';
  8174. iframe.frameBorder = '0';
  8175. if (ruleParser.curSiteRule.sandbox != false) {
  8176. iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  8177. }
  8178. 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;';
  8179. let waitTime = 100, checkEval;
  8180. ruleParser.runWait((_checkEval, _waitTime) => {
  8181. if (_checkEval) {
  8182. checkEval = _checkEval;
  8183. }
  8184. if (_waitTime) {
  8185. waitTime = _waitTime;
  8186. }
  8187. });
  8188. if (checkRemoveIntv) clearInterval(checkRemoveIntv);
  8189. checkRemoveIntv = setInterval(() => {
  8190. if (!iframe || !getBody(document).contains(iframe)) {
  8191. clearInterval(checkRemoveIntv);
  8192. loadPageOver();
  8193. }
  8194. }, 500);
  8195. let loadedHandler = async e => {
  8196. if (e.data != 'pagetual-iframe:DOMLoaded' && e.type != 'load') return;
  8197. clearInterval(checkRemoveIntv);
  8198. window.removeEventListener('message', loadedHandler, false);
  8199. iframe.removeEventListener('load', loadedHandler, false);
  8200. let pageEleTryTimes = 0;
  8201. async function checkIframe() {
  8202. if (urlChanged || isPause) {
  8203. return callback(false, false);
  8204. }
  8205. try {
  8206. let doc = iframe.contentDocument || iframe.contentWindow.document;
  8207. if (checkEval && !await checkEval(doc)) {
  8208. setTimeout(() => {
  8209. checkIframe();
  8210. }, waitTime);
  8211. return;
  8212. } else {
  8213. let base = doc.querySelector("base");
  8214. ruleParser.basePath = base ? base.href : url;
  8215. let eles = ruleParser.getPageElement(doc, iframe.contentWindow, pageEleTryTimes < 25);
  8216. if (eles && eles.length > 0) {
  8217. await ruleParser.hookUrl(doc);
  8218. await callback(doc, eles);
  8219. } else if (pageEleTryTimes++ < 100) {
  8220. getBody(doc).scrollTop = 9999999;
  8221. doc.documentElement.scrollTop = 9999999;
  8222. setTimeout(() => {
  8223. checkIframe();
  8224. }, waitTime);
  8225. return;
  8226. } else {
  8227. if (failFromIframe++ > 2) {
  8228. failFromIframe = 0;
  8229. debug("Stop as failFromIframe");
  8230. changeStop(true);
  8231. callback(false, false);
  8232. } else {
  8233. ruleParser.noValidContent(url);
  8234. callback(false, false);
  8235. }
  8236. }
  8237. }
  8238. } catch(e) {
  8239. inCors = true;
  8240. if (forceState === 3) {
  8241. debug("Stop as cors");
  8242. isPause = true;
  8243. }
  8244. if (!ruleParser.curSiteRule.pageElement) {
  8245. ruleParser.curSiteRule.pageElement = allOfBody;
  8246. ruleParser.getInsert(true);
  8247. }
  8248. ruleParser.curSiteRule.action = 0;
  8249. ruleParser.nextLinkHref = url;
  8250. callback(false, false);
  8251. nextPage();
  8252. }
  8253. if (iframe && iframe.parentNode) iframe.parentNode.removeChild(iframe);
  8254. }
  8255. setTimeout(() => {
  8256. checkIframe();
  8257. }, waitTime);
  8258. };
  8259. let code = ruleParser.curSiteRule.iframeInit;
  8260. if (code) {
  8261. let checkReady = setInterval(() => {
  8262. let doc;
  8263. try {
  8264. doc = iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document);
  8265. } catch(e) {
  8266. clearInterval(checkReady);
  8267. return;
  8268. }
  8269. if (doc) {
  8270. clearInterval(checkReady);
  8271. try {
  8272. Function('win', 'iframe', '"use strict";' + code)(iframe.contentWindow, iframe);
  8273. } catch(e) {
  8274. debug(e);
  8275. }
  8276. }
  8277. }, 50);
  8278. }
  8279. window.addEventListener('message', loadedHandler, false);
  8280. iframe.addEventListener('load', loadedHandler, false);
  8281. iframe.src = url;
  8282. try {
  8283. getBody(document).appendChild(iframe);
  8284. } catch (e) {
  8285. return callback(false, false);
  8286. }
  8287. }
  8288.  
  8289. var emuIframe, lastActiveUrl, orgContent, meetCors = false;
  8290. function emuPage(callback) {
  8291. let orgPage = null, preContent = null, iframeDoc, checkTimes = 0, loadmoreBtn, pageEle, nextLink, loadmoreEnd = false, waitTimes = 80, changed = false;
  8292. function returnFalse(log) {
  8293. if (curPage > 1) {
  8294. if (rulesData.lastPageTips) showTips(i18n("lastPage"), "", 800);
  8295. } else {
  8296. sideController.remove();
  8297. }
  8298. debug(log);
  8299. isPause = true;
  8300. callback(false, false);
  8301. if (emuIframe && emuIframe.parentNode) {
  8302. emuIframe.parentNode.removeChild(emuIframe);
  8303. emuIframe = null;
  8304. }
  8305. }
  8306. function cloneStatus() {
  8307. if (!iframeDoc) return;
  8308. let inputs = document.querySelectorAll("input:not([type=button],[type=image],[type=reset],[type=submit])");
  8309. let selectOptions = document.querySelectorAll("select>option");
  8310. [...inputs].forEach(input => {
  8311. let sel = geneSelector(input, true, true);
  8312. let mirrorEle = iframeDoc.querySelector(sel);
  8313. if (!mirrorEle) return;
  8314. emuInput(mirrorEle, input.value);
  8315. });
  8316. [...selectOptions].forEach(option => {
  8317. let sel = geneSelector(option, true, true);
  8318. let mirrorEle = iframeDoc.querySelector(sel);
  8319. if (!mirrorEle) return;
  8320. let selected = option.selected;
  8321. mirrorEle.selected = !!selected;
  8322. mirrorEle.parentNode.dispatchEvent(new Event('change'));
  8323. });
  8324. }
  8325. async function checkPage() {
  8326. if (isPause) return loadPageOver();
  8327. try {
  8328. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  8329. } catch(e) {
  8330. returnFalse("Stop as cors");
  8331. return;
  8332. }
  8333.  
  8334. let waitTime = 200, checkEval;
  8335. ruleParser.runWait((_checkEval, _waitTime) => {
  8336. if (_checkEval) {
  8337. checkEval = _checkEval;
  8338. }
  8339. if (_waitTime) {
  8340. waitTime = _waitTime;
  8341. }
  8342. });
  8343.  
  8344. if (!orgPage) {
  8345. if (!loadmoreEnd) {
  8346. loadmoreBtn = getLoadMore(iframeDoc);
  8347. if (loadmoreBtn && isVisible(loadmoreBtn, emuIframe.contentWindow)) {
  8348. emuClick(loadmoreBtn, iframeDoc);
  8349. let intv = setInterval(() => {
  8350. loadmoreBtn = getLoadMore(iframeDoc);
  8351. if (!loadmoreBtn || !getBody(document).contains(loadmoreBtn) || !isVisible(loadmoreBtn, emuIframe.contentWindow)) {
  8352. clearInterval(intv);
  8353. loadmoreEnd = true;
  8354. setTimeout(() => {
  8355. checkPage();
  8356. }, 500);
  8357. } else if (isInViewPort(loadmoreBtn)) {
  8358. emuClick(loadmoreBtn, iframeDoc);
  8359. }
  8360. }, 200);
  8361. return;
  8362. } else {
  8363. loadmoreEnd = true;
  8364. }
  8365. }
  8366. if (checkEval && !await checkEval(iframeDoc)) {
  8367. waitTimes = 50;
  8368. setTimeout(() => {
  8369. checkPage();
  8370. }, waitTime);
  8371. return;
  8372. } else {
  8373. if (!nextLink || !nextLink.offsetParent) nextLink = await ruleParser.getNextLink(iframeDoc, true);
  8374. if (nextLink) pageEle = ruleParser.getPageElement(iframeDoc, emuIframe.contentWindow, true);
  8375. if (!pageEle || pageEle.length == 0 || !nextLink) {
  8376. getBody(iframeDoc).scrollTop = 9999999;
  8377. iframeDoc.documentElement.scrollTop = 9999999;
  8378. if (waitTimes-- > 0) {
  8379. setTimeout(() => {
  8380. checkPage();
  8381. }, waitTime);
  8382. return;
  8383. }
  8384. }
  8385. }
  8386. if (!pageEle || pageEle.length == 0) {
  8387. returnFalse("Stop as no page when emu");
  8388. return;
  8389. }
  8390. pageEle = [].filter.call(pageEle, ele => {return ele && !compareNodeName(ele, ["style", "script", "meta"])});
  8391. if (compareNodeName(pageEle[0], ["ul"]) || pageEle.length == 1) pageEle = pageEle[0];
  8392. else if (pageEle[0].parentNode == pageEle[1].parentNode) {
  8393. pageEle = pageEle[0].parentNode;
  8394. } else {
  8395. pageEle = pageEle[0];
  8396. }
  8397. if (ruleParser.curSiteRule.smart && orgContent != pageEle.innerHTML) {
  8398. orgContent = pageEle.innerHTML;
  8399. if (waitTimes-- > 0) {
  8400. setTimeout(() => {
  8401. checkPage();
  8402. }, 500);
  8403. return;
  8404. }
  8405. }
  8406. orgPage = pageEle;
  8407. if (nextLink) {
  8408. if (compareNodeName(orgPage, ["img"])) {
  8409. if (!ruleParser.curSiteRule.lazyImgSrc) ruleParser.curSiteRule.lazyImgSrc = "0";
  8410. if (orgPage.src) {
  8411. orgContent = orgPage.src;
  8412. } else {
  8413. setTimeout(() => {
  8414. checkPage();
  8415. }, 500);
  8416. return;
  8417. }
  8418. } else {
  8419. orgContent = orgPage.innerHTML;
  8420. }
  8421. preContent = orgContent;
  8422. if (!isVisible(nextLink, emuIframe.contentWindow)) {
  8423. returnFalse("Stop as next hide when emu");
  8424. } else {
  8425. emuClick(nextLink, iframeDoc);
  8426. setTimeout(() => {
  8427. checkPage();
  8428. }, 500);
  8429. }
  8430. } else {
  8431. returnFalse("Stop as no next when emu");
  8432. }
  8433. return;
  8434. }
  8435. if (!ruleParser.checkStopSign(nextLink, iframeDoc)) {
  8436. return returnFalse("Stop as stopSign");
  8437. }
  8438. if (checkTimes++ > 200) {
  8439. returnFalse("Stop as timeout when emu");
  8440. return;
  8441. }
  8442. if (checkEval && !await checkEval(iframeDoc)) {
  8443. checkTimes = 0;
  8444. setTimeout(() => {
  8445. checkPage();
  8446. }, waitTime);
  8447. return;
  8448. }
  8449. let eles = ruleParser.getPageElement(iframeDoc, emuIframe.contentWindow, true), checkItem;
  8450. if (eles && eles.length > 0) {
  8451. eles = [].filter.call(eles, ele => {return ele && !compareNodeName(ele, ["style", "script", "meta"])});
  8452. if (compareNodeName(eles[0], ["ul"]) || eles.length == 1) checkItem = eles[0];
  8453. else if (eles[0].parentNode == eles[1].parentNode) {
  8454. checkItem = eles[0].parentNode;
  8455. } else {
  8456. checkItem = eles[0];
  8457. }
  8458. }
  8459. if (!checkItem) {
  8460. setTimeout(() => {
  8461. checkPage();
  8462. }, waitTime);
  8463. } else {
  8464. let checkInner;
  8465. if (compareNodeName(checkItem, ["img"])) {
  8466. if (checkItem.src) {
  8467. checkInner = checkItem.src;
  8468. } else {
  8469. setTimeout(() => {
  8470. checkPage();
  8471. }, waitTime);
  8472. return;
  8473. }
  8474. } else {
  8475. checkInner = checkItem.innerHTML;
  8476. }
  8477. if (orgPage != checkItem || checkInner != preContent) {
  8478. changed = true;
  8479. orgPage = checkItem;
  8480. preContent = checkInner;
  8481. setTimeout(() => {
  8482. checkPage();
  8483. }, 500);
  8484. } else if (changed) {
  8485. checkTimes = 0;
  8486. if (orgContent == preContent && (ruleParser.curSiteRule.smart || ruleParser.curSiteRule.stopSame)) {
  8487. returnFalse("Stop as same content");
  8488. } else {
  8489. orgContent = preContent;
  8490. await ruleParser.hookUrl(iframeDoc);
  8491. callback(iframeDoc, eles);
  8492. }
  8493. } else {
  8494. if (checkTimes % 10 === 5) {
  8495. if (!nextLink || !nextLink.offsetParent) {
  8496. nextLink = await ruleParser.getNextLink(iframeDoc, true);
  8497. }
  8498. if (nextLink) {
  8499. emuClick(nextLink, iframeDoc);
  8500. }
  8501. }
  8502. setTimeout(() => {
  8503. checkPage();
  8504. }, waitTime);
  8505. }
  8506. }
  8507. }
  8508. if (!emuIframe) {
  8509. let loaded = false;
  8510. emuIframe = document.createElement('iframe');
  8511. emuIframe.name = 'pagetual-iframe';
  8512. let notSetSandbox = typeof ruleParser.curSiteRule.sandbox == 'undefined';
  8513. if (notSetSandbox || ruleParser.curSiteRule.sandbox == true) {
  8514. emuIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  8515. } else if (ruleParser.curSiteRule.sandbox) {
  8516. emuIframe.sandbox = ruleParser.curSiteRule.sandbox;
  8517. }
  8518. emuIframe.width = '100%';
  8519. emuIframe.height = '100%';
  8520. emuIframe.frameBorder = '0';
  8521. 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;';
  8522. emuIframe.addEventListener("load", e => {
  8523. try {
  8524. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  8525. } catch(e) {
  8526. if (e.message && e.message.indexOf("cross-origin") != -1 && notSetSandbox && emuIframe.hasAttribute("sandbox")) {
  8527. emuIframe.removeAttribute("sandbox");
  8528. meetCors = true;
  8529. callback(false, false);
  8530. if (ruleParser.curSiteRule.smart) {
  8531. ruleParser.findNoNext();
  8532. }
  8533. } else {
  8534. returnFalse("Stop as cors");
  8535. }
  8536. return;
  8537. }
  8538. setTimeout(async () => {
  8539. if (meetCors && ruleParser.curSiteRule.smart) {
  8540. ruleParser.smartRules = ruleParser.smartRules.filter(item => {return item && item.url !== ruleParser.curSiteRule.url;});
  8541. storage.setItem("smartRules", ruleParser.smartRules);
  8542. }
  8543. meetCors = false;
  8544. let code = ruleParser.curSiteRule.init;
  8545. if (code) {
  8546. try {
  8547. 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)});
  8548. } catch(e) {
  8549. debug(e);
  8550. }
  8551. } else {
  8552. let refreshByClickSel = ruleParser.curSiteRule.refreshByClick;
  8553. if (iframeDoc && refreshByClickSel) {
  8554. let clickBtn = await waitForElement(refreshByClickSel, iframeDoc);
  8555. await sleep(500);
  8556. cloneStatus();
  8557. emuClick(clickBtn, iframeDoc);
  8558. await sleep(500);
  8559. }
  8560. }
  8561. if (loaded) return;
  8562. loaded = true;
  8563. checkPage();
  8564. }, 500);
  8565. });
  8566. let code = ruleParser.curSiteRule.iframeInit;
  8567. if (code) {
  8568. let checkReady = setInterval(() => {
  8569. try {
  8570. iframeDoc = emuIframe.contentDocument || (emuIframe.contentWindow && emuIframe.contentWindow.document);
  8571. } catch(e) {
  8572. clearInterval(checkReady);
  8573. return;
  8574. }
  8575. if (iframeDoc) {
  8576. clearInterval(checkReady);
  8577. try {
  8578. Function('win', 'iframe', '"use strict";' + code)(emuIframe.contentWindow, emuIframe);
  8579. } catch(e) {
  8580. debug(e);
  8581. }
  8582. }
  8583. }, 50);
  8584. }
  8585. if (!lastActiveUrl) lastActiveUrl = location.href;
  8586. emuIframe.src = lastActiveUrl;
  8587. getBody(document).appendChild(emuIframe);
  8588. } else {
  8589. if (emuIframe.src != lastActiveUrl || meetCors) {
  8590. emuIframe.src = lastActiveUrl;
  8591. return;
  8592. }
  8593. checkPage();
  8594. }
  8595. }
  8596.  
  8597. var scrollToResizeInited = false;
  8598. var resizePool = [];
  8599. var scrollingToResize = false;
  8600.  
  8601. function isTouchViewPort(element) {
  8602. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  8603. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  8604. const {
  8605. top,
  8606. right,
  8607. bottom,
  8608. left,
  8609. } = element.getBoundingClientRect();
  8610.  
  8611. return (
  8612. top < viewHeight &&
  8613. left < viewWidth &&
  8614. right > 0 &&
  8615. bottom > 0
  8616. );
  8617. }
  8618.  
  8619. function resizeIframe(iframe, frameDoc, pageEle) {
  8620. if (targetY >= 0) {
  8621. window.scrollTo({ top: targetY, behavior: 'instant'});
  8622. targetY = -1;
  8623. }
  8624. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  8625. if (ruleParser.curSiteRule.smart || forceState === 2) {
  8626. let height = (getBody(frameDoc).scrollHeight || getBody(frameDoc).offsetHeight || 500);
  8627. if (!iframe.style.height || parseInt(iframe.style.height) === 0 || height - parseInt(iframe.style.height) > window.innerHeight) {
  8628. iframe.style.height = height + "px";
  8629. iframe.style.minHeight = iframe.style.height;
  8630. }
  8631. iframe.style.width = "100%";
  8632. frameDoc.documentElement.scrollTop = 0;
  8633. frameDoc.documentElement.scrollLeft = 0;
  8634. } else {
  8635. if (pageEle) {
  8636. if (document.body.scrollWidth) frameDoc.documentElement.style.width = document.body.scrollWidth + "px";
  8637. let fitWidth = ruleParser.curSiteRule.fitWidth !== false;
  8638. let targetElement = pageEle[0];
  8639. if (!targetElement) return;
  8640. if (pageEle.length > 1) {
  8641. targetElement = targetElement.parentNode;
  8642. }
  8643. let scrollHeight = targetElement.scrollHeight || targetElement.offsetHeight || 500;
  8644. iframe.style.height = scrollHeight + "px";
  8645. let scrollTop = 0, scrollLeft = 0;
  8646. getBody(frameDoc).scrollTop = 0;
  8647. getBody(frameDoc).scrollLeft = 0;
  8648. while (targetElement && targetElement.offsetParent) {
  8649. targetElement.offsetParent.scrollTop = targetElement.offsetTop;
  8650. if (targetElement.offsetParent.scrollTop == 0) {
  8651. scrollTop += targetElement.offsetTop;
  8652. }
  8653. if (fitWidth) {
  8654. targetElement.offsetParent.scrollLeft = targetElement.offsetLeft;
  8655. if (targetElement.offsetParent.scrollLeft == 0) {
  8656. scrollLeft += targetElement.offsetLeft;
  8657. }
  8658. }
  8659. targetElement = targetElement.offsetParent;
  8660. }
  8661. frameDoc.documentElement.scrollTop = scrollTop;
  8662. frameDoc.documentElement.scrollLeft = scrollLeft;
  8663. if (frameDoc.documentElement.scrollTop == 0 && frameDoc.documentElement.scrollLeft == 0) {
  8664. getBody(frameDoc).scrollTop += scrollTop;
  8665. getBody(frameDoc).scrollLeft += scrollLeft;
  8666. }
  8667. if (!fitWidth && iframe.style.marginLeft == '0px') {
  8668. iframe.style.width = "100vw";
  8669. iframe.style.maxWidth = "100vw";
  8670. iframe.style.minWidth = "100vw";
  8671. var cWidth = document.body.clientWidth || document.documentElement.clientWidth;
  8672. var iWidth = window.innerWidth;
  8673. iframe.style.marginLeft = -iframe.getBoundingClientRect().left - (iWidth - cWidth) / 2 + "px";
  8674. }
  8675. }
  8676. }
  8677. let newScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  8678. if (newScroll != curScroll) {
  8679. getBody(document).scrollTop = curScroll;
  8680. document.documentElement.scrollTop = curScroll;
  8681. }
  8682. }
  8683.  
  8684. function scrollToResize(e) {
  8685. if (scrollingToResize) return;
  8686. else {
  8687. scrollingToResize = true;
  8688. let resizeHandler = () => {
  8689. let touched = 0;
  8690. for (let i = 0; i < resizePool.length; i++) {
  8691. let resizeArr = resizePool[i];
  8692. let iframe = resizeArr[1]();
  8693. if (isTouchViewPort(iframe)) {
  8694. touched++;
  8695. let pageEle = resizeArr[0]();
  8696. let frameDoc = resizeArr[2]();
  8697. resizeIframe(iframe, frameDoc, pageEle);
  8698. } else if (touched) {
  8699. if (touched == 1) {
  8700. let pageEle = resizeArr[0]();
  8701. let frameDoc = resizeArr[2]();
  8702. resizeIframe(iframe, frameDoc, pageEle);
  8703. }
  8704. break;
  8705. } else if (!iframe.parentNode) {
  8706. resizePool.splice(i, 1);
  8707. break;
  8708. }
  8709. }
  8710. };
  8711. setTimeout(() => {
  8712. scrollingToResize = false;
  8713. }, 300);
  8714. resizeHandler();
  8715. }
  8716. }
  8717.  
  8718. var curForceIframe;
  8719. function forceIframe(url, callback) {
  8720. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  8721. let curIframe = document.createElement('iframe'), iframeDoc, pageElement = null, inAction = true;
  8722. let loadedHandler = () => {
  8723. let getPageEle = () => {
  8724. if (ruleParser.curSiteRule.smart) {
  8725. return null;
  8726. } else {
  8727. if (!pageElement || pageElement.length === 0 || !pageElement[0].offsetParent) {
  8728. pageElement = ruleParser.getPageElement(iframeDoc, curIframe.contentWindow);
  8729. }
  8730. return pageElement;
  8731. }
  8732. };
  8733. resizeIframe(curIframe, iframeDoc, getPageEle());
  8734. let loaded = curIframe.getAttribute("loaded");
  8735. if (loaded == "true") {
  8736. return;
  8737. }
  8738. curIframe.setAttribute("loaded", "true");
  8739. let getIframe = () => {
  8740. return curIframe;
  8741. };
  8742. let getFrameDoc = () => {
  8743. return iframeDoc;
  8744. };
  8745. ruleParser.insertPage(iframeDoc, [], url, ele => {
  8746. callback(curIframe, loaded == "refresh");
  8747. inAction = false;
  8748. }, true);
  8749. if (!loaded) {
  8750. resizePool.push([getPageEle, getIframe, getFrameDoc]);
  8751. }
  8752. };
  8753. let checkIframeTimer = setInterval(() => {
  8754. if (!curIframe.parentNode) {
  8755. clearInterval(checkIframeTimer);
  8756. return curIframe.getAttribute("loaded") == "true" || callback(false);
  8757. }
  8758. }, 500);
  8759. let code = ruleParser.curSiteRule.iframeInit;
  8760. if (code) {
  8761. let checkReady = setInterval(() => {
  8762. try {
  8763. iframeDoc = curIframe.contentDocument || (curIframe.contentWindow && curIframe.contentWindow.document);
  8764. } catch(e) {
  8765. clearInterval(checkReady);
  8766. return;
  8767. }
  8768. if (iframeDoc) {
  8769. clearInterval(checkReady);
  8770. try {
  8771. Function('win', 'iframe', '"use strict";' + code)(curIframe.contentWindow, curIframe);
  8772. } catch(e) {
  8773. debug(e);
  8774. }
  8775. }
  8776. }, 50);
  8777. }
  8778. let waitTime = 300, checkEval;
  8779. ruleParser.runWait((_checkEval, _waitTime) => {
  8780. if (_checkEval) {
  8781. checkEval = _checkEval;
  8782. }
  8783. if (_waitTime) {
  8784. waitTime = _waitTime;
  8785. }
  8786. });
  8787. async function checkIframe() {
  8788. if (checkEval && !await checkEval(iframeDoc)) {
  8789. setTimeout(() => {
  8790. checkIframe();
  8791. }, waitTime);
  8792. return;
  8793. }
  8794. loadedHandler();
  8795. }
  8796. curIframe.name = 'pagetual-iframe';
  8797. curIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  8798. curIframe.frameBorder = '0';
  8799. curIframe.scrolling = "no";
  8800. 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;';
  8801. curIframe.addEventListener("load", async e => {
  8802. clearInterval(checkIframeTimer);
  8803. if (isPause) return callback(false);
  8804. try {
  8805. iframeDoc = curIframe.contentDocument || curIframe.contentWindow.document;
  8806. } catch(e) {
  8807. debug("Stop as cors");
  8808. isPause = true;
  8809. callback(false);
  8810. return;
  8811. }
  8812. let css = ruleParser.curSiteRule.css || rulesData.customCss;
  8813. if (css) {
  8814. let cssArr = css.split("inIframe:");
  8815. if (cssArr && cssArr.length > 1) {
  8816. let styleEle = iframeDoc.createElement("style");
  8817. styleEle.innerHTML = cssArr[1];
  8818. iframeDoc.head.appendChild(styleEle);
  8819. }
  8820. }
  8821. checkIframe();
  8822. iframeDoc.addEventListener('wheel', e => {
  8823. document.dispatchEvent(new Event('wheel'));
  8824. }, true);
  8825. });
  8826. let checkTimes = 0, findPageEle = false;
  8827. let forceRefresh = e => {
  8828. if (inAction || !iframeDoc) return;
  8829. inAction = true;
  8830. let foundNext = () => {
  8831. document.removeEventListener("scroll", forceRefresh);
  8832. }
  8833. setTimeout(async () => {
  8834. inAction = false;
  8835. if (!ruleParser.nextLinkHref && !isPause) {
  8836. checkTimes++;
  8837. await ruleParser.getNextLink(iframeDoc, true);
  8838. if (ruleParser.nextLinkHref) {
  8839. foundNext();
  8840. if (isLoading) isLoading = false;
  8841. } else if (checkTimes >= 10) {
  8842. foundNext();
  8843. } else if (checkTimes >= 3 && !findPageEle) {
  8844. if (!pageElement) pageElement = ruleParser.getPageElement(iframeDoc, curIframe.contentWindow);
  8845. if (!pageElement) {
  8846. inAction = true;
  8847. curIframe.contentWindow.location.reload();
  8848. } else {
  8849. findPageEle = true;
  8850. }
  8851. }
  8852. } else {
  8853. foundNext();
  8854. }
  8855. }, 100);
  8856. };
  8857. document.addEventListener("scroll", forceRefresh);
  8858. curIframe.src = url;
  8859. curForceIframe = curIframe;
  8860. let insert = ruleParser.getInsert();
  8861. let body = getBody(document);
  8862. let curScroll = body.scrollTop || document.documentElement.scrollTop;
  8863. if (forceState == 2) {
  8864. document.documentElement.appendChild(loadingDiv);
  8865. body.appendChild(curIframe);
  8866. let bodyStyle = getComputedStyle(body);
  8867. if (bodyStyle.display == "flex" || bodyStyle.display == "inline-flex") {
  8868. body.style.flexDirection = "column";
  8869. }
  8870. } else {
  8871. ruleParser.insertElement(curIframe);
  8872. }
  8873. body.scrollTop = curScroll;
  8874. document.documentElement.scrollTop = curScroll;
  8875.  
  8876. if (!scrollToResizeInited) {
  8877. scrollToResizeInited = true;
  8878. document.addEventListener("scroll", scrollToResize);
  8879. }
  8880. return curIframe;
  8881. }
  8882.  
  8883. function loadPageOver() {
  8884. isLoading = false;
  8885. stopScroll = true;
  8886. setTimeout(() => {stopScroll = false;}, 300);
  8887. if (loadingDiv.parentNode) {
  8888. loadingDiv.parentNode.removeChild(loadingDiv);
  8889. }
  8890. if (rate !== 1 && !clickMode) {
  8891. setTimeout(() => {
  8892. if (distToBottom() < bottomGap) {
  8893. nextPage();
  8894. }
  8895. }, 1);
  8896. }
  8897. }
  8898.  
  8899. function checkAutoLoadNum() {
  8900. if (autoLoadNum >= 0) {
  8901. if (autoLoadNum !== 0 && --autoLoadNum === 0) {
  8902. autoLoadNum = -1;
  8903. } else {
  8904. setTimeout(() => nextPage(), 1);
  8905. }
  8906. }
  8907. }
  8908.  
  8909. async function nextPage() {
  8910. if (isPause || isLoading || forceState === 1) return;
  8911. if (ruleParser.curSiteRule.delay) {
  8912. try {
  8913. let checkDelay = ((typeof ruleParser.curSiteRule.delay === 'function') ? ruleParser.curSiteRule.delay : Function('"use strict";' + ruleParser.curSiteRule.delay))();
  8914. if (!checkDelay) return;
  8915. } catch(e) {
  8916. debug(e);
  8917. }
  8918. }
  8919. let nextLink = ruleParser.nextLinkHref;
  8920. if (!nextLink) {
  8921. isLoading = true;
  8922. if (curPage === 1) {
  8923. await ruleParser.getNextLink(document, true);
  8924. nextLink = ruleParser.nextLinkHref;
  8925. }
  8926. if (!nextLink) {
  8927. if (curPage === 1) {
  8928. if (ruleParser.curSiteRule.pinUrl) {
  8929. setTimeout(() => {isLoading = false;}, 500);
  8930. } else if (tryTimes++ < 5) {
  8931. setTimeout(() => {isLoading = false;}, 1000);
  8932. } else {
  8933. ruleParser.findNoNext();
  8934. }
  8935. } else if (rulesData.lastPageTips && !showedLastPageTips) {
  8936. showTips(i18n("lastPage"), "", 800);
  8937. showedLastPageTips = true;
  8938. }
  8939. return;
  8940. }
  8941. isLoading = false;
  8942. }
  8943. showedLastPageTips = false;
  8944. let pvGallery = document.querySelector("span.pv-gallery-container");
  8945. if (pvGallery && pvGallery.style.display !== "none") return;
  8946. let insert = ruleParser.getInsert();
  8947. if (insert) {
  8948. if (curPage === 1) initView();
  8949. /*if (curPage == 1) {
  8950. window.postMessage({
  8951. command: 'pagetual.insert'
  8952. }, '*');
  8953. }*/
  8954. let isJs = ruleParser.curSiteRule.action == 3 || ruleParser.hrefIsJs(nextLink);
  8955. if (!isJs) {
  8956. emuIframe = null;
  8957. lastActiveUrl = nextLink;
  8958. if (location.protocol === "https:" && /^http:/.test(nextLink)) {
  8959. nextLink = nextLink.replace(/^http/, "https");
  8960. }
  8961. }
  8962. isLoading = true;
  8963. if (curPage !== 1 || !isJs || !ruleParser.curSiteRule.smart) {
  8964. ruleParser.beginLoading(loadingDiv);
  8965. }
  8966. let sleep = ruleParser.curSiteRule.sleep || 0;
  8967. setTimeout(() => {
  8968. if (ruleParser.curSiteRule.pageElementByJs) {
  8969. var over = eles => {
  8970. if (urlChanged || isPause) {
  8971. loadPageOver();
  8972. return;
  8973. }
  8974. if (eles) {
  8975. ruleParser.insertPage(document, eles, nextLink, () => {
  8976. createPageBar(nextLink);
  8977. checkAutoLoadNum();
  8978. }, true);
  8979. } else {
  8980. debug("Stop as no page when get by js");
  8981. isPause = true;
  8982. loadPageOver();
  8983. }
  8984. };
  8985. try {
  8986. ((typeof ruleParser.curSiteRule.pageElementByJs === 'function') ? ruleParser.curSiteRule.pageElementByJs : Function("over", "pageNum",'"use strict";' + ruleParser.curSiteRule.pageElementByJs))(over, curPage);
  8987. } catch(e) {
  8988. debug(e);
  8989. }
  8990. } else if ((forceState === 2 || ruleParser.curSiteRule.action == 2) && !isJs) {
  8991. forceIframe(nextLink, (iframe, refresh) => {
  8992. if (urlChanged || isPause) {
  8993. loadPageOver();
  8994. return;
  8995. }
  8996. if (!refresh) {
  8997. let pageBar = createPageBar(nextLink);
  8998. if (pageBar && iframe && iframe.parentNode) iframe.parentNode.insertBefore(pageBar, iframe);
  8999. }
  9000. loadPageOver();
  9001. checkAutoLoadNum();
  9002. });
  9003. } else if ((forceState === 3 || ruleParser.curSiteRule.action == 1) && !isJs) {
  9004. requestFromIframe(nextLink, async (doc, eles) => {
  9005. if (urlChanged || isPause) {
  9006. loadPageOver();
  9007. return;
  9008. }
  9009. if (eles) {
  9010. await ruleParser.insertPage(doc, eles, nextLink, () => {
  9011. createPageBar(nextLink);
  9012. checkAutoLoadNum();
  9013. }, true);
  9014. } else loadPageOver();
  9015. });
  9016. } else {
  9017. if (!isJs) {
  9018. requestDoc(nextLink, (eles) => {
  9019. if (urlChanged || isPause) {
  9020. loadPageOver();
  9021. return;
  9022. }
  9023. if (eles) {
  9024. createPageBar(nextLink);
  9025. checkAutoLoadNum();
  9026. } else loadPageOver();
  9027. });
  9028. } else {
  9029. emuPage((doc, eles) => {
  9030. if (urlChanged || isPause) {
  9031. loadPageOver();
  9032. return;
  9033. }
  9034. if (eles) {
  9035. ruleParser.insertPage(doc, eles, "", () => {
  9036. createPageBar(nextLink);
  9037. checkAutoLoadNum();
  9038. }, true);
  9039. } else loadPageOver();
  9040. });
  9041. }
  9042. }
  9043. }, sleep);
  9044. }
  9045. }
  9046.  
  9047. function init() {
  9048. if (document.readyState === 'loading' || document.readyState === 'uninitialized') {
  9049. let domReady = e => {
  9050. initRules(() => {
  9051. initPage();
  9052. });
  9053. document.removeEventListener("DOMContentLoaded", domReady, false);
  9054. };
  9055. document.addEventListener("DOMContentLoaded", domReady, false);
  9056. } else {
  9057. initRules(() => {
  9058. initPage();
  9059. });
  9060. }
  9061. }
  9062.  
  9063. function visibilitychangeHandler() {
  9064. document.removeEventListener('visibilitychange', visibilitychangeHandler);
  9065. init();
  9066. }
  9067.  
  9068. setTimeout(() => {
  9069. if (document.hidden) {
  9070. document.addEventListener('visibilitychange', visibilitychangeHandler);
  9071. } else {
  9072. init();
  9073. }
  9074. }, 300);
  9075. })();

QingJ © 2025

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