东方永页机

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

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

QingJ © 2025

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