东方永页机

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

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

  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.57
  14. // @description Perpetual pages - powerful auto-pager script. Auto fetching next paginated web pages and inserting into current page for infinite scroll. Support thousands of web sites without any rule.
  15. // @description:zh-CN 终极自动翻页 - 加载并拼接下一分页内容至当前页尾,智能适配任意网页
  16. // @description:zh-TW 終極自動翻頁 - 加載並拼接下一分頁內容至當前頁尾,智能適配任意網頁
  17. // @description:ja Webページを自動で読み込み継ぎ足し表示を行うブラウザ拡張です、次のページ付けされた Web ページの自動読み込みと現在のページへの挿入 ルールなしで何千もの Web サイトをサポートします。
  18. // @description:ko 페이지가 매겨진 다음 웹 페이지를 자동으로 로드하고 현재 페이지에 삽입합니다. 규칙 없이 수천 개의 웹 사이트를 지원합니다.
  19. // @description:ru Автоматическая подгрузка следующих страниц и вставка их содержимого в текущую страницу. Поддерживает тысячи сайтов даже с настройками по умолчанию.
  20. // @description:de Automatisches Laden der nächsten paginierten Webseiten und Einfügen in die aktuelle Seite. Unterstützen Sie Tausende von Websites ohne Regeln.
  21. // @description:es Carga automática de las siguientes páginas web paginadas e inserción en la página actual. Admite miles de sitios web sin ninguna regla.
  22. // @description:fr Chargement automatique des pages Web paginées suivantes et insertion dans la page en cours. Prend en charge des milliers de sites Web sans aucune règle.
  23. // @description:it Caricamento automatico delle pagine Web impaginate successive e inserimento nella pagina corrente. Supporta migliaia di siti web senza alcuna regola.
  24. // @author hoothin
  25. // @license MPL-2.0
  26. // @match *://*/*
  27. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAdVBMVEUAAAD3VU33VU32VEz8U073VU32VU33VU32VUz0Uk/3VE32VU32VUz2VU32VU32VU32VU33VU33U0z2VU34Wkv3VE32VUz/mpj/nJj2VUz2VU32VE33VEz2VU32VU32VUz3VE32VEz3VE3/mZf2Vkz2VU3/mpilFFolAAAAJXRSTlMA3Lp/GvTBT5YQLuawZ/DOyZwlPQeKc21N04+FX1bqpm9DNoB4T68ePwAAAitJREFUWMPt1tuasiAUBuCFCG5Rs3QybTPV1/1f4v/3PDkyIojn8x5qBrI+ltAfh32/yysmBKvyXb+njb6bDL9kzTd5SzjDAsYT8nFoGSxYe6BVqoNDp2jFDit25BRgVUAODB4YWcETWVTwVNGiGN5iWtBgg4YMCpsoI38dNunmmWyxUTvbPwwbsYR0fIzZLQ0pTG8eieRmBLMmpdH9uimQEf6TNRnXXKLZHixpJtywLzOgMHtFCqdM64DahHRnOE1dsrekm9wr2WtLcAlpdHwcp1pAJySXYnERclzp4+v19jXdmcTvQUJtz+ZaI4i05/V/UGYrCxbaAsOYoNfIKEQxpqQuzCgJJJ/3f42O8ywEZuMVWi/8hODxGj3GW2b0udkbGULLDOjimAG0S3fLGlBnXQM9irG1CiQdVQi0dqQsOSDlyEEz7Vy9OxxfR71VCXsSB23jMrKJYZXSjw57sqgLn5Z0wolsOCz0RyJkyeYjgz7pwwVq20eboZwtVUl2EnN5gJ50dQZFdryATvABRTr/tJXkUMdaAK5pwtCapwtFLskguwuyMh/Sd9WChQ4sIvIUYSk3PYqQvCQlOC04IfN7PkdjOyRKWhdKXMmiAFt9i3sJ5jxoRuR0vqAghxxwHuqfQE5OHGDKOrwEnqs1DgAZ2e4Eev1d45TN7JfhrQLKgfwMFYAsvp33dXII073aVQLI2gN5S58lfmGnKKFtah7nkgnBZB7zlP7Y/QNiTM6sYNzawwAAAABJRU5ErkJggg==
  28. // @grant GM_xmlhttpRequest
  29. // @grant GM_registerMenuCommand
  30. // @grant GM_notification
  31. // @grant GM_getValue
  32. // @grant GM_setValue
  33. // @grant GM_addStyle
  34. // @grant GM_openInTab
  35. // @grant GM_deleteValue
  36. // @grant GM_info
  37. // @grant GM_setClipboard
  38. // @grant GM.xmlHttpRequest
  39. // @grant GM.registerMenuCommand
  40. // @grant GM.notification
  41. // @grant GM.getValue
  42. // @grant GM.setValue
  43. // @grant GM.addStyle
  44. // @grant GM.openInTab
  45. // @grant GM.deleteValue
  46. // @grant GM.info
  47. // @grant GM.setClipboard
  48. // @supportURL https://github.com/hoothin/UserScripts/issues
  49. // @connect wedata.net
  50. // @connect githubusercontent.com
  51. // @connect ghproxy.com
  52. // @connect hoothin.github.io
  53. // @run-at document-idle
  54. // @connect *
  55. // @contributionURL https://ko-fi.com/hoothin
  56. // @contributionAmount 1
  57. // ==/UserScript==
  58.  
  59. (function() {
  60. 'use strict';
  61.  
  62. const pauseVideo = () => {
  63. setTimeout(() => {
  64. [].forEach.call(document.querySelectorAll("video"), video => {
  65. video.removeAttribute && video.removeAttribute("autoplay");
  66. video.pause && video.pause();
  67. });
  68. }, 1000);
  69. };
  70. if (window.name === 'pagetual-iframe' || (window.frameElement && window.frameElement.name === 'pagetual-iframe')) {
  71. [].forEach.call(document.querySelectorAll("iframe"), iframe => {
  72. iframe.name = 'pagetual-iframe';
  73. });
  74. var domloaded = function() {
  75. window.parent.postMessage('pagetual-iframe:DOMLoaded', '*');
  76. };
  77. if (window.opera) {
  78. document.addEventListener('DOMContentLoaded', domloaded, false);
  79. pauseVideo();
  80. } else {
  81. domloaded();
  82. if (document.readystate === 'complete') {
  83. pauseVideo();
  84. } else {
  85. window.addEventListener('load', () => {
  86. pauseVideo();
  87. }, false);
  88. }
  89. }
  90. if (getComputedStyle(document.documentElement).display === 'none') {
  91. document.documentElement.style.display = 'block';
  92. }
  93. if (document.body && getComputedStyle(document.body).display === 'none') {
  94. document.body.style.display = 'block';
  95. }
  96. return;
  97. }
  98.  
  99. if (window.top !== window.self) {
  100. try {
  101. if (window.self.innerWidth < 300 || window.self.innerHeight < 300) {
  102. return;
  103. }
  104. } catch(e) {
  105. return;
  106. }
  107. }
  108.  
  109. const noRuleTest = false;
  110. const lang = navigator.appName === "Netscape" ? navigator.language : navigator.userLanguage;
  111. const langData = [
  112. {
  113. name: "English",
  114. match: ["en"],
  115. lang: {
  116. enableDebug: "Enable debug output",
  117. updateNotification: "Notification after rules updated",
  118. disable: "Disable",
  119. disableSite: "Toggle disabled state",
  120. disableSiteTips: "Disabled on this site",
  121. enableSiteTips: "Enabled on this site",
  122. enable: "Enable",
  123. toTop: "To Top",
  124. toBottom: "To Bottom",
  125. current: "Current Page",
  126. forceIframe: "Force to join next page",
  127. cancelForceIframe: "Cancel Force join",
  128. configure: "Configure",
  129. firstUpdate: "Click here to initialize the rules",
  130. update: "Update online rules",
  131. click2update: "Click to update rules from url now",
  132. loadNow: "Load next automatically",
  133. loadConfirm: "How much pages do you want to load? (0 means infinite)",
  134. noNext: "No next link found, please create a new rule",
  135. passSec: "Updated #t# seconds ago",
  136. passMin: "Updated #t# minutes ago",
  137. passHour: "Updated #t# hours ago",
  138. passDay: "Updated #t# days ago",
  139. cantDel: "Can't delete buildin rules",
  140. confirmDel: "Are you sure you want to delete this rule?",
  141. updateSucc: "Update succeeded",
  142. beginUpdate: "Begin update, wait a minute please",
  143. customUrls: "Import Pagetual or AutoPagerize rule url, One url per line",
  144. customRules: "Input custom rules. <a href='#t#'>✍️Contribute rules</a>",
  145. save: "Save",
  146. loadingText: "Shojo Now Loading...",
  147. opacity: "Opacity",
  148. opacityPlaceholder: "0: hide spacer",
  149. hideBar: "Hide the paging spacer",
  150. hideBarButNoStop: "Hide but not stop",
  151. dbClick2Stop: "Double-click on the blank space to pause",
  152. sortTitle: "Sorting takes effect after the next rule update",
  153. autoRun: "Auto enable (blacklist mode)",
  154. autoLoadNum: "Amount for preload pages",
  155. turnRate: "Turn the next page when it's less than 【X】 times page height from the footer",
  156. inputPageNum: "Enter page number to jump",
  157. enableHistory: "Write browsing history after page turning",
  158. enableHistoryAfterInsert: "Write browsing history immediately after splicing, otherwise write after browsing",
  159. contentVisibility: "Automatically switch contentVisibility to improve rendering performance",
  160. initRun: "Turn pages immediately after opening",
  161. preload: "Preload next page for speeding up",
  162. click2ImportRule: "Click to import base rules link, then wait until the update is complete: ",
  163. forceAllBody: "Join full body of page?",
  164. openInNewTab: "Open urls of additions in new tab",
  165. importSucc: "Import completed",
  166. import: "Import",
  167. editCurrent: "Edit rule for current",
  168. editBlacklist: "Edit the blacklist urls, line by line, Support ? * for wildcard",
  169. upBtnImg: "Icon of back to top",
  170. downBtnImg: "Icon of go to footer",
  171. sideControllerIcon: "Icon of sidebar",
  172. loadingTextTitle: "Loading text",
  173. dbClick2StopCtrl: "Ctrl key",
  174. dbClick2StopAlt: "Alt key",
  175. dbClick2StopShift: "Shift key",
  176. dbClick2StopMeta: "Meta key",
  177. dbClick2StopKey: "Shortcut key",
  178. pageElementCss: "Custom style for main page elements",
  179. customCss: "Custom complete css",
  180. firstAlert: "You have not imported the base rule, please select the appropriate rule to import",
  181. picker: "Pagetual page element picker",
  182. closePicker: "Close Pagetual picker",
  183. pickerPlaceholder: "Element selector, Leave empty if you have no idea",
  184. pickerCheck: "Check selector and copy",
  185. switchSelector: "Click to switch element",
  186. gotoEdit: "Go to edit rule with current selector",
  187. manualMode: "Disable splicing, manually turn pages with the right arrow keys (or dispatch event 'pagetual.next')",
  188. clickMode: "Disable splicing, automatically click the next page when scrolling to the end of the page",
  189. pageBarMenu: "Click the center of the page bar to open the picker menu",
  190. nextSwitch: "Switch next link",
  191. arrowToScroll: "Press left arrow key to scroll prev and right arrow key to scroll next",
  192. sideController: "Display the paging control bar in the sidebar",
  193. sideControllerScroll: "Scroll toggle",
  194. sideControllerAlways: "Always show",
  195. hideLoadingIcon: "Hide loading animation",
  196. hideBarArrow: "Hide arrow for page bar",
  197. duplicate: "Duplicate Pagetual have been installed, check your script manager!",
  198. forceStateIframe: "Embed full page as iframe",
  199. forceStateDynamic: "Load dynamic content via iframe",
  200. forceStateDisable: "Disable page turning on this site",
  201. autoScrollRate: "Scroll speed (1~1000)",
  202. disableAutoScroll: "Stop Auto Scroll",
  203. enableAutoScroll: "Enable Auto Scroll",
  204. toggleAutoScroll: "Toggle Auto Scroll",
  205. ruleRequest: "Rule Request",
  206. page: "Page ",
  207. prevPage: "Prev page",
  208. nextPage: "Next page",
  209. errorRulesMustBeArray: "Rules must be a Array!",
  210. errorJson: "JSON error, check again!",
  211. editSuccess: "Edit successfully",
  212. errorWrongUrl: "Wrong url, check again!",
  213. errorAlreadyExists: "Already exists!",
  214. settingsSaved: "The settings are saved, refresh to view",
  215. iframe: "Iframe",
  216. dynamic: "Dynamic",
  217. reloadPage: "Edit completed, reload page now?",
  218. copied: "Copied",
  219. noValidContent: "No valid content detected, Captcha action may be required, click to view",
  220. outOfDate: "The script is outdated, update to the latest version in time!",
  221. hideBarTips: "Hide the pagination bar, toggle immersive experience",
  222. setConfigPage: "Set current page as the default configuration page",
  223. wedata2github: "Change the wedata address to the mirror address in the github repository",
  224. addOtherProp: "Add rule property",
  225. addNextSelector: "Add selector content as nextLink",
  226. addPageSelector: "Add selector content as pageElement",
  227. propName: "Enter rule property name",
  228. propValue: "Enter rule property value",
  229. customFirst: "Ignore cache for local custom rules",
  230. rulesExample: "Rules Example",
  231. lastPage: "Reached the last page",
  232. lastPageTips: "Show tips when reaching the last page"
  233. }
  234. },
  235. {
  236. //Translated by Prankster 199 (vfggf95565).
  237. name: "Arabic",
  238. match: ["ar", "ar-AE", "ar-BH", "ar-DZ", "ar-EG", "ar-IQ", "ar-JO", "ar-KW", "ar-LB", "ar-LY", "ar-MA", "ar-OM", "ar-QA", "ar-SA", "ar-SY", "ar-TN", "ar-YE"],
  239. lang: {
  240. enableDebug: "تمكين تصحيح الأخطاء",
  241. updateNotification: "إشعار بعد تحديث القواعد",
  242. disable: "معطل",
  243. disableSite: "تبديل حالة التعطيل/التفعيل للموقع",
  244. disableSiteTips: "معطل على هذا الموقع",
  245. enableSiteTips: "مفعل على هذا الموقع",
  246. enable: "مفعل",
  247. toTop: "إلى الأعلى",
  248. toBottom: "إلى الأسفل",
  249. current: "الصفحة الحالية",
  250. forceIframe: "إجبار على الانضمام للصفحة التالية",
  251. cancelForceIframe: "إلغاء الانضمام القسري",
  252. configure: "إعداد",
  253. firstUpdate: "انقر هنا لتفعيل القواعد لأول مرة",
  254. update: "تحديث القواعد عبر الإنترنت",
  255. click2update: "انقر لتحديث القواعد من الرابط الآن",
  256. loadNow: "تحميل التالي تلقائيًا",
  257. loadConfirm: "كم عدد الصفحات التي ترغب تحميلها؟ (0 يعني لانهائي)",
  258. noNext: "لم يتم العثور على رابط الصفحة التالية، يرجى إنشاء قاعدة جديدة",
  259. passSec: "تم التحديث منذ #t# ثانية",
  260. passMin: "تم التحديث منذ #t# دقيقة",
  261. passHour: "تم التحديث منذ #t# ساعة",
  262. passDay: "تم التحديث منذ #t# يوم",
  263. cantDel: "لا يمكن حذف القواعد المدمجة",
  264. confirmDel: "هل أنت متأكد من حذف هذه القاعدة؟",
  265. updateSucc: "تم التحديث بنجاح",
  266. beginUpdate: "بدأ التحديث، يرجى الانتظار لحظة",
  267. customUrls: "استيراد رابط قاعدة Pagetual أو AutoPagerize، رابط واحد لكل سطر",
  268. customRules: "إدخال القواعد المخصصة. <a href='#t#'>✍️ساهم بالقواعد</a>",
  269. save: "حفظ",
  270. /* From the creator hoothin :
  271. "Shojo Now Loading..." is a meme that refers to the game loading text in the Japanese Touhou (東方) game series. */
  272. loadingText: "جارٍ التحميل...",
  273. opacity: "الشفافية",
  274. opacityPlaceholder: "0: إخفاء الفاصل",
  275. hideBar: "إخفاء الفاصل التصفحي",
  276. hideBarButNoStop: "إخفاء، لكن لا تتوقف",
  277. dbClick2Stop: "انقر مزدوج على المساحة الفارغة للإيقاف",
  278. sortTitle: "يتم تفعيل الفرز بعد التحديث التالي للقواعد",
  279. autoRun: "تمكين تلقائي (وضع القائمة السوداء)",
  280. autoLoadNum: "عدد صفحات التحميل المسبق",
  281. turnRate: "الانتقال للصفحة التالية عندما تكون المسافة أقل من 【X】 مرات ارتفاع الصفحة من التذييل",
  282. inputPageNum: "أدخل رقم الصفحة للانتقال",
  283. enableHistory: "كتابة سجل التصفح بعد تحويل الصفحة",
  284. enableHistoryAfterInsert: "كتابة سجل التصفح فورًا بعد الدمج، أو بعد التصفح",
  285. contentVisibility: "التنقل التلقائي لرؤية المحتوى, لتحسين أداء العرض",
  286. initRun: "الانتقال بين الصفحات فور الفتح",
  287. preload: "تحميل الصفحة التالية مسبقًا لتسريع الأداء",
  288. click2ImportRule: "انقر لاستيراد رابط القواعد الأساسية، ثم انتظر حتى يكتمل التحديث",
  289. forceAllBody: "دمج كامل الصفحة كإطار؟",
  290. openInNewTab: "فتح الروابط الإضافية في علامة تبويب جديدة",
  291. importSucc: "تم الاستيراد بنجاح",
  292. import: "استيراد",
  293. editCurrent: "تحرير القاعدة للحالية",
  294. editBlacklist: "تحرير عناوين القائمة السوداء، سطر بسطر، دعم؟ * للرموز المتحركة",
  295. upBtnImg: "أيقونة العودة إلى الأعلى",
  296. downBtnImg: "أيقونة الانتقال إلى الأسفل",
  297. sideControllerIcon: "أيقونة الشريط الجانبي",
  298. loadingTextTitle: "تحميل النص",
  299. dbClick2StopCtrl: "مفتاح Ctrl",
  300. dbClick2StopAlt: "مفتاح Alt",
  301. dbClick2StopShift: "مفتاح Shift",
  302. dbClick2StopMeta: "مفتاح Meta",
  303. dbClick2StopKey: "مفاتيح الاختصار",
  304. pageElementCss: "نمط مخصص لعناصر الصفحة الرئيسية",
  305. customCss: "مخصص بالكامل CSS نمط",
  306. firstAlert: "لم تستورد القاعدة الأساسية بعد، يرجى اختيار القاعدة المناسبة للاستيراد",
  307. picker: "محدد عناصر الصفحة Pagetual",
  308. closePicker: "إغلاق محدد Pagetual",
  309. pickerPlaceholder: "محدد العناصر، اتركه فارغًا إذا كنت لا تعرف",
  310. pickerCheck: "تحقق من المحدد ونسخ",
  311. switchSelector: "انقر للتبديل بين العناصر",
  312. gotoEdit: "اذهب لتحرير القاعدة بالمحدد الحالي",
  313. manualMode: "تعطيل الدمج/الربط، واستخدام مفتاح الاتجاه الأيمن يدويًا للتمرير، واستخدام مفتاح السهم الأيسر للرجوع",
  314. clickMode: "تعطيل الدمج/الربط، عند التمرير إلى نهاية الصفحة، سيتم النقر تلقائيًا على الصفحة التالية",
  315. pageBarMenu: "انقر على مركز شريط الصفحة لفتح قائمة التحديد",
  316. nextSwitch: "تبديل الرابط التالي",
  317. arrowToScroll: "انقر على مفتاح السهم الأيمن للتمرير التالي ومفتاح السهم الأيسر للتمرير السابق",
  318. sideController: "عرض شريط التحكم في التصفح الترقيم في الشريط الجانبي",
  319. sideControllerScroll: "تبديل التمرير",
  320. sideControllerAlways: "عرض دائمًا",
  321. hideLoadingIcon: "إخفاء رمز التحميل",
  322. hideBarArrow: "إخفاء سهم شريط الصفحة",
  323. duplicate: "تم تثبيت Pagetual مكرر، تحقق من مدير النصوص البرمجية الخاص بك!",
  324. forceStateIframe: "تضمين الصفحة بالكامل كإطار",
  325. forceStateDynamic: "تحميل المحتوى الديناميكي عبر الإطار",
  326. forceStateDisable: "تعطيل تحويل الصفحات على هذا الموقع",
  327. autoScrollRate: "سرعة التمرير (1~1000)",
  328. disableAutoScroll: "إيقاف التمرير التلقائي",
  329. enableAutoScroll: "تمكين التمرير التلقائي",
  330. toggleAutoScroll: "تبديل التمرير التلقائي",
  331. ruleRequest: "طلب قاعدة",
  332. page: "صفحة ",
  333. prevPage: "الصفحة السابقة",
  334. nextPage: "الصفحة التالية",
  335. errorRulesMustBeArray: "يجب أن تكون القواعد مصفوفة!",
  336. errorJson: "خطأ في JSON، تحقق مرة أخرى!",
  337. editSuccess: "تم التحرير بنجاح",
  338. errorWrongUrl: "عنوان URL خاطئ، تحقق مرة أخرى!",
  339. errorAlreadyExists: "موجود بالفعل!",
  340. settingsSaved: "تم حفظ الإعدادات، قم بالتحديث لعرض",
  341. iframe: "إطار",
  342. dynamic: "ديناميكي",
  343. reloadPage: "اكتمل التحرير، إعادة تحميل الصفحة الآن؟",
  344. copied: "تم النسخ",
  345. noValidContent: "لم يتم الكشف عن محتوى صالح، قد يكون الإجراء Captcha مطلوبًا، انقر لعرض",
  346. outOfDate: "النص البرمجي قديم، قم بالتحديث إلى الإصدار الأحدث في الوقت المناسب!",
  347. hideBarTips: "إخفاء شريط التحكم في التصفح الترقيم ، والتبديل لوضع كامل الصفحة",
  348. setConfigPage: "تعيين الصفحة الحالية كصفحة الإعداد الافتراضية",
  349. wedata2github: "تغيير عنوان الويب داتا إلى العنوان البديل المرآة, في مستودع جيت هاب",
  350. addOtherProp: "إضافة خاصية قاعدة",
  351. addNextSelector: "إضافة محتوى المحدد كـ nextLink",
  352. addPageSelector: "إضافة محتوى المحدد كـ pageElement",
  353. propName: "أدخل اسم خاصية القاعدة",
  354. propValue: "أدخل قيمة خاصية القاعدة",
  355. customFirst: "تجاهل ذاكرة التخزين المؤقت للقواعد المخصصة المحلية",
  356. rulesExample: "مثال على القواعد",
  357. lastPage: "تم الوصول إلى الصفحة الأخيرة",
  358. lastPageTips: "عرض تلميحات عند الوصول إلى الصفحة الأخيرة"
  359. }
  360. },
  361. {
  362. name: "简体中文",
  363. match: ["zh-CN", "zh-SG"],
  364. lang: {
  365. enableDebug: "调试模式,输出信息至控制台",
  366. updateNotification: "规则更新后提示",
  367. disable: "暂时禁用",
  368. disableSite: "站点禁用开关",
  369. disableSiteTips: "已在此站禁用",
  370. enableSiteTips: "已在此站启用",
  371. enable: "启用自动翻页",
  372. toTop: "回到顶部",
  373. toBottom: "前往页尾",
  374. current: "当前页",
  375. forceIframe: "强制拼接",
  376. cancelForceIframe: "取消强制拼接",
  377. configure: "打开配置页面",
  378. firstUpdate: "点击此处初始化规则",
  379. update: "更新在线规则",
  380. click2update: "点击立即更新规则",
  381. loadNow: "立即翻页",
  382. loadConfirm: "要翻几页?(0为不间断)",
  383. noNext: "没有找到下一页,请新建规则",
  384. passSec: "更新于 #t# 秒前",
  385. passMin: "更新于 #t# 分钟前",
  386. passHour: "更新于 #t# 小时前",
  387. passDay: "更新于 #t# 天前",
  388. cantDel: "无法删除内置规则",
  389. confirmDel: "是否确认要删除此规则?",
  390. updateSucc: "更新成功",
  391. beginUpdate: "正在更新,请耐心等待,不要关闭页面",
  392. customUrls: "导入 Pagetual 或 AutoPagerize 规则 url,一行一条",
  393. customRules: "输入【东方永页机】格式的自定义规则 <a href='#t#'>✍️贡献规则</a>",
  394. save: "保存设置",
  395. loadingText: "少女祈祷中...",
  396. opacity: "不透明值",
  397. opacityPlaceholder: "0: 隐藏分隔条",
  398. hideBar: "隐藏分页隔条",
  399. hideBarButNoStop: "隐藏但不停止",
  400. dbClick2Stop: "空白处双击暂停翻页",
  401. sortTitle: "排序在下次更新规则后生效",
  402. autoRun: "自动启用,否则为白名单模式",
  403. autoLoadNum: "自动加载指定页数",
  404. turnRate: "距离页尾【X】倍页面高度时就开始翻页",
  405. inputPageNum: "输入页码跳转",
  406. enableHistory: "翻页后写入历史记录",
  407. enableHistoryAfterInsert: "拼接后立即写入历史记录,否则浏览完毕后再行写入",
  408. contentVisibility: "自动切换 contentVisibility,提升渲染性能",
  409. initRun: "打开页面后立即尝试翻页,否则滚动至页尾再翻页",
  410. preload: "翻页前预读下一页,加速浏览",
  411. click2ImportRule: "点击下方任意一条添加规则库,并静待更新成功,请预先打开链接确认能正常访问再行导入:",
  412. forceAllBody: "是否拼接整个页面?",
  413. openInNewTab: "使拼接页面的内容在新页面打开",
  414. importSucc: "导入成功",
  415. import: "导入",
  416. editCurrent: "编辑此站规则",
  417. editBlacklist: "编辑黑名单网址,一行一条,支持? *通配符与正则",
  418. upBtnImg: "回到页首图标",
  419. downBtnImg: "前往页尾图标",
  420. sideControllerIcon: "侧边栏图标",
  421. loadingTextTitle: "加载中文字",
  422. dbClick2StopCtrl: "Ctrl",
  423. dbClick2StopAlt: "Alt",
  424. dbClick2StopShift: "Shift",
  425. dbClick2StopMeta: "Meta",
  426. dbClick2StopKey: "快捷键",
  427. pageElementCss: "页面主体框架的样式",
  428. customCss: "自定义 css",
  429. firstAlert: "你还未导入规则库,请选择合适的规则库导入哦",
  430. picker: "东方永页机主体元素抓取器",
  431. closePicker: "关闭东方永页机抓取器",
  432. pickerPlaceholder: "元素选择器,没想法建议留空",
  433. pickerCheck: "检查你编辑的选择器并复制",
  434. switchSelector: "点击切换元素",
  435. gotoEdit: "使用当前的选择器前往编辑规则",
  436. manualMode: "禁用拼接,手动用右方向键翻页,可使用左方向键返回",
  437. clickMode: "禁用拼接,滚动至页尾时自动点击下一页",
  438. pageBarMenu: "点击分隔条中间弹出菜单",
  439. nextSwitch: "切换其他页码",
  440. arrowToScroll: "左方向键滚动至上一页,右方向键滚动至下一页",
  441. sideController: "在侧边显示翻页控制栏",
  442. sideControllerScroll: "滚动开关",
  443. sideControllerAlways: "始终显示",
  444. hideLoadingIcon: "隐藏加载动画",
  445. hideBarArrow: "隐藏分隔条定位箭头",
  446. duplicate: "检测到永页机重复安装,请删除其他脚本管理器中的永页机!",
  447. forceStateIframe: "以 iframe 嵌入整页",
  448. forceStateDynamic: "通过 iframe 加载动态内容后取出",
  449. forceStateDisable: "在此站禁用",
  450. autoScrollRate: "滚动速度(1~1000)",
  451. disableAutoScroll: "停止自动滚动",
  452. enableAutoScroll: "开启自动滚动",
  453. toggleAutoScroll: "自动滚动开关",
  454. ruleRequest: "适配请求",
  455. page: "Page ",
  456. prevPage: "上一页",
  457. nextPage: "下一页",
  458. errorRulesMustBeArray: "规则必须为数组形式!",
  459. errorJson: "JSON 格式有错,请重新检查!",
  460. editSuccess: "编辑成功",
  461. errorWrongUrl: "URL 错误, 请重新检查!",
  462. errorAlreadyExists: "已经存在!",
  463. settingsSaved: "设置已保存,刷新后生效",
  464. iframe: "强制拼接",
  465. dynamic: "动态加载",
  466. reloadPage: "编辑完成,是否立即刷新页面?",
  467. copied: "已复制",
  468. noValidContent: "没有检测到有效内容,可能需要人机校验,点击查看",
  469. outOfDate: "脚本已过时,请及时更新到最新版本!",
  470. hideBarTips: "隐藏分页隔条,沉浸式体验",
  471. setConfigPage: "将当前页面设为默认配置页",
  472. wedata2github: "将 wedata 地址更改为 github 仓库内的镜像地址",
  473. addOtherProp: "添加规则属性",
  474. addNextSelector: "添加选择器内容为 nextLink",
  475. addPageSelector: "添加选择器内容为 pageElement",
  476. propName: "输入规则属性名",
  477. propValue: "输入规则属性值",
  478. customFirst: "为本地自定义规则忽略缓存",
  479. rulesExample: "自定义规则详解",
  480. lastPage: "已到达最后一页",
  481. lastPageTips: "到达最后一页时进行提示"
  482. }
  483. },
  484. {
  485. name: "正體中文",
  486. match: ["zh", "zh-TW", "zh-HK"],
  487. lang: {
  488. enableDebug: "調試模式,輸出信息至控制台",
  489. updateNotification: "規則更新后提示",
  490. disable: "暫時禁用",
  491. disableSite: "站點禁用開關",
  492. disableSiteTips: "已在此站禁用",
  493. enableSiteTips: "已在此站啟用",
  494. enable: "啟用自動翻頁",
  495. toTop: "回到頂部",
  496. toBottom: "前往頁尾",
  497. current: "當前頁",
  498. forceIframe: "強制拼接",
  499. cancelForceIframe: "取消强制拼接",
  500. configure: "打開配置頁面",
  501. firstUpdate: "點擊此處初始化規則",
  502. update: "更新在綫規則",
  503. click2update: "點擊立即更新規則",
  504. loadNow: "立即翻頁",
  505. loadConfirm: "要翻几頁?(0為不間斷)",
  506. noNext: "沒有找到下一頁,請新建規則",
  507. passSec: "更新于 #t# 秒前",
  508. passMin: "更新于 #t# 分鐘前",
  509. passHour: "更新于 #t# 小時前",
  510. passDay: "更新于 #t# 天前",
  511. cantDel: "無法刪除内置規則",
  512. confirmDel: "是否確認要刪除此規則?",
  513. updateSucc: "更新成功",
  514. beginUpdate: "正在更新,請稍候",
  515. customUrls: "導入 Pagetual 或 AutoPagerize 規則 url,一行一條",
  516. customRules: "輸入【東方永頁機】格式的自定義規則 <a href='#t#'>✍️貢獻規則</a>",
  517. save: "存儲設置",
  518. loadingText: "少女祈禱中...",
  519. opacity: "不透明值",
  520. opacityPlaceholder: "0: 隱藏分隔條",
  521. hideBar: "隱藏分頁隔條",
  522. hideBarButNoStop: "隱藏但不停止",
  523. dbClick2Stop: "空白處雙擊暫停翻頁",
  524. sortTitle: "排序在下次更新規則後生效",
  525. autoRun: "自動啓用,否則為白名單模式",
  526. autoLoadNum: "自動加載指定頁數",
  527. turnRate: "距離頁尾【X】倍頁面高度時就開始翻頁",
  528. inputPageNum: "輸入頁碼跳轉",
  529. enableHistory: "翻頁后寫入歷史記錄",
  530. enableHistoryAfterInsert: "拼接後立即寫入歷史記錄,否則瀏覽完畢後再行寫入",
  531. contentVisibility: "自動切換 contentVisibility,提升渲染性能",
  532. initRun: "打開頁面后立即嘗試翻頁,否則滾動至頁尾再翻頁",
  533. preload: "翻頁前預讀下一頁,加速瀏覽",
  534. click2ImportRule: "點擊下方添加特殊規則庫,并靜待更新成功:",
  535. forceAllBody: "是否拼接整個頁面?",
  536. openInNewTab: "使拼接頁面的内容在新頁面打開",
  537. importSucc: "導入成功",
  538. import: "導入",
  539. editCurrent: "編輯此站規則",
  540. editBlacklist: "編輯黑名單網址,一行一條,支持? *通配符與正則",
  541. upBtnImg: "回到頁首圖標",
  542. downBtnImg: "前往頁尾圖標",
  543. sideControllerIcon: "側邊欄圖標",
  544. loadingTextTitle: "加載中文字",
  545. dbClick2StopCtrl: "Ctrl",
  546. dbClick2StopAlt: "Alt",
  547. dbClick2StopShift: "Shift",
  548. dbClick2StopMeta: "Meta",
  549. dbClick2StopKey: "快捷鍵",
  550. pageElementCss: "頁面主體框架的樣式",
  551. customCss: "自定義 css",
  552. firstAlert: "你還未導入規則庫,請選擇合適的規則庫導入哦",
  553. picker: "東方永頁機主體元素抓取器",
  554. closePicker: "關閉東方永頁機抓取器",
  555. pickerPlaceholder: "元素選擇器,沒想法建議留空",
  556. pickerCheck: "檢查你編輯的選擇器並複製",
  557. switchSelector: "點擊切換元素",
  558. gotoEdit: "使用當前的選擇器前往編輯規則",
  559. manualMode: "禁用拼接,手動用右方向鍵翻頁,左方向鍵返回",
  560. clickMode: "禁用拼接,滾動至頁尾時自動點擊下一頁",
  561. pageBarMenu: "點擊分隔條中間彈出菜單",
  562. nextSwitch: "切換其他頁碼",
  563. arrowToScroll: "左方向鍵滾動至上一頁,右方向鍵滾動至下一頁",
  564. sideController: "在側邊顯示翻頁控制欄",
  565. sideControllerScroll: "滾燈開關",
  566. sideControllerAlways: "始終顯示",
  567. hideLoadingIcon: "隱藏加載動畫",
  568. hideBarArrow: "隱藏分隔條定位箭頭",
  569. duplicate: "檢測到永頁機重複安裝,請刪除其他腳本管理器中的永頁機!",
  570. forceStateIframe: "以 iframe 嵌入整頁",
  571. forceStateDynamic: "通過 iframe 加載動態內容後取出",
  572. forceStateDisable: "在此站禁用",
  573. autoScrollRate: "滾動速度(1~1000)",
  574. disableAutoScroll: "停止自動滾動",
  575. enableAutoScroll: "開啟自動滾動",
  576. toggleAutoScroll: "自動滾動開關",
  577. ruleRequest: "適配請求",
  578. page: "Page ",
  579. prevPage: "上一頁",
  580. nextPage: "下一頁",
  581. errorRulesMustBeArray: "規則必須為陣列形式!",
  582. errorJson: "JSON 格式有錯,請重新檢查!",
  583. editSuccess: "編輯成功",
  584. errorWrongUrl: "URL 錯誤, 請重新檢查!",
  585. errorAlreadyExists: "已經存在!",
  586. settingsSaved: "設置已保存,刷新後生效",
  587. iframe: "強制拼接",
  588. dynamic: "動態加載",
  589. reloadPage: "編輯完成,是否立即刷新頁面?",
  590. copied: "已復制",
  591. noValidContent: "沒有檢測到有效内容,可能需要人機校驗,點擊查看",
  592. outOfDate: "脚本已過時,請及時更新到最新版本!",
  593. hideBarTips: "隱藏分頁隔條,沉浸式體驗",
  594. setConfigPage: "將當前頁面設為默認配置頁",
  595. wedata2github: "將 wedata 地址更改為 github 倉庫內的鏡像地址",
  596. addOtherProp: "添加規則屬性",
  597. addNextSelector: "添加選擇器內容為 nextLink",
  598. addPageSelector: "添加選擇器內容為 pageElement",
  599. propName: "輸入規則屬性名",
  600. propValue: "輸入規則屬性值",
  601. customFirst: "為本地自定義規則忽略緩存",
  602. rulesExample: "自定義規則詳解",
  603. lastPage: "已到達最後一頁",
  604. lastPageTips: "到達最後一頁時進行提示"
  605. }
  606. },
  607. {
  608. name: "日本語",
  609. match: ["ja"],
  610. lang: {
  611. enableDebug: "デバッグモード",
  612. updateNotification: "ルール更新後の通知",
  613. disable: "一時的に無効",
  614. disableSite: "無効状態の切り替え",
  615. disableSiteTips: "このサイトで既に無効になっています",
  616. enableSiteTips: "このサイトで既に有効になっています",
  617. enable: "ページめくりを有効にする",
  618. toTop: "トップに戻る",
  619. toBottom: "ページの下部に移動",
  620. current: "現在のページ",
  621. forceIframe: "強制ステッチ",
  622. cancelForceIframe: "強制ステッチをキャンセル",
  623. configure: "設定ページを開く",
  624. firstUpdate: "ここをクリックしてルールを初期化します",
  625. update: "更新ルール",
  626. click2update: "今すぐルールを更新してください",
  627. loadNow: "今すぐページをめくる",
  628. loadConfirm: "数ページめくりたいですか?(0は途切れない)",
  629. noNext: "次のページが見つかりません、新しいルールを作成してください",
  630. passSec: "#t#秒前に更新",
  631. passMin: "#t#分前に更新",
  632. passHour: "#t#時間前に更新",
  633. passDay: "#t#日前に更新",
  634. cantDel: "組み込みルールを削除できません",
  635. confirmDel: "このルールを削除してもよろしいですか?",
  636. updateSucc: "更新に成功しました",
  637. beginUpdate: "更新中、お待ちください",
  638. customUrls: "インポートルールのURL、1行に1つ",
  639. customRules: "【東方永頁機】の形式でカスタムルールを入力してください <a href='#t#'>✍️寄稿ルール</a>",
  640. save: "設定を保存",
  641. loadingText: "少女祈祷中...",
  642. opacity: "不透明値",
  643. opacityPlaceholder: "0: 隠す",
  644. hideBar: "ページ区切り文字を非表示にします",
  645. hideBarButNoStop: "非表示にするが停止しない",
  646. dbClick2Stop: "空白部分をダブルクリックしてページめくりを一時停止します",
  647. sortTitle: "並べ替えは、次のルールの更新後に有効になります",
  648. autoRun: "自動的に有効",
  649. autoLoadNum: "指定したページ数を自動的に読み込みます",
  650. turnRate: "ページの端からページの高さの【X】倍になったらページをめくる",
  651. inputPageNum: "ジャンプするページ番号を入力",
  652. enableHistory: "ページめくり後の履歴を書く",
  653. enableHistoryAfterInsert: "スプライシングの直後に履歴レコードを書き込みます。それ以外の場合は、閲覧後に書き込みます",
  654. contentVisibility: "contentVisibility を自動的に切り替えてレンダリング パフォーマンスを向上させる",
  655. initRun: "Webページを開いた直後にページをめくる",
  656. preload: "事前に次のページを読む",
  657. click2ImportRule: "以下をクリックして、ルールベースを追加します:",
  658. forceAllBody: "フルページ埋め込み?",
  659. openInNewTab: "スプライスされたページのコンテンツを新しいページで開きます",
  660. importSucc: "インポート完了",
  661. import: "インポート",
  662. editCurrent: "現在のルールの編集",
  663. editBlacklist: "ブラックリストのURLを編集し、1行ずつ、サポート? *ワイルドカード",
  664. upBtnImg: "トップアイコンに戻る",
  665. downBtnImg: "フッターアイコンに移動",
  666. sideControllerIcon: "サイドバー アイコン",
  667. loadingTextTitle: "テキストをロード",
  668. dbClick2StopCtrl: "Ctrlキー",
  669. dbClick2StopAlt: "Altキー",
  670. dbClick2StopShift: "Shiftキー",
  671. dbClick2StopMeta: "Metaキー",
  672. dbClick2StopKey: "Shortcutキー",
  673. pageElementCss: "ページ本文フレームの STYLE",
  674. customCss: "カスタム css",
  675. firstAlert: "ルールベースをインポートしていないため、インポートする適切なルールベースを選択してください",
  676. picker: "Pagetualページ要素ピッカー",
  677. closePicker: "Pagetualピッカーを閉じる",
  678. pickerPlaceholder: "わからない場合は空のままにしてください",
  679. pickerCheck: "セレクターをチェックしてコピー",
  680. switchSelector: "クリックして要素を切り替えます",
  681. gotoEdit: "現在のセレクターでルールを編集する",
  682. manualMode: "スプライシングを無効にします。手動で右の矢印キーを使用してページをめくります",
  683. clickMode: "スティッチングを無効にします。ページの最後までスクロールすると、次のページが自動的にクリックされます",
  684. pageBarMenu: "ページバーの中央をクリックしてメニューをポップアップ表示",
  685. nextSwitch: "次のページに切り替え",
  686. arrowToScroll: "左矢印キーで前へ、右矢印キーで次へ",
  687. sideController: "サイドバーにページング コントロール バーを表示する",
  688. sideControllerScroll: "スクロール スイッチ",
  689. sideControllerAlways: "常に表示",
  690. hideLoadingIcon: "読み込み中のアニメーションを隠す",
  691. hideBarArrow: "分割線の位置矢印を隠す",
  692. duplicate: "Pagetual の重複インストールが検出されました。他のスクリプト マネージャで永続的なページ マシンを削除してください!",
  693. forceStateIframe: "iframe にページ全体を埋め込む",
  694. forceStateDynamic: "iframe 経由で動的コンテンツを読み込む",
  695. forceStateDisable: "このステーションでのページめくりを無効にする",
  696. autoScrollRate: "スクロール速度 (1~1000)",
  697. disableAutoScroll: "自動スクロールを停止します",
  698. EnableAutoScroll: "自動スクロールを有効にする",
  699. toggleAutoScroll: "自動スクロールの切り替え",
  700. ruleRequest: "ルール要求",
  701. page: "Page ",
  702. prevPage: "Prev page",
  703. nextPage: "Next page",
  704. errorRulesMustBeArray: "Rules must be a Array!",
  705. errorJson: "JSON error, check again!",
  706. editSuccess: "Edit successfully",
  707. errorWrongUrl: "Wrong url, check again!",
  708. errorAlreadyExists: "Already exists!",
  709. settingsSaved: "The settings are saved, refresh to view",
  710. iframe: "Iframe",
  711. dynamic: "Dynamic",
  712. reloadPage: "Edit completed, reload page now?",
  713. copied: "Copied",
  714. noValidContent: "有効なコンテンツが検出されませんでした。クリックして表示",
  715. outOfDate: "スクリプトが古くなっています。最新バージョンに更新してください。",
  716. hideBarTips: "ページネーション バーを非表示にします。没入型エクスペリエンス",
  717. setConfigPage: "現在のページをデフォルト設定ページとして設定",
  718. wedata2github: "wedata アドレスを github ウェアハウスのミラー アドレスに変更",
  719. addOtherProp: "ルールプロパティを追加",
  720. addNextSelector: "セレクターのコンテンツを nextLink として追加",
  721. addPageSelector: "セレクタ コンテンツを pageElement として追加",
  722. propName: "ルールのプロパティ名を入力してください",
  723. propValue: "ルールのプロパティ値を入力してください",
  724. customFirst: "ローカルカスタムルールのキャッシュを無視する",
  725. rulesExample: "カスタムルールの詳しい説明",
  726. lastPage: "最後のページに到達しました",
  727. lastPageTips: "最後のページに到達した時にヒントを表示する"
  728. }
  729. },
  730. {
  731. name: "Русский",
  732. match: ["ru", "ru-RU"],
  733. lang: {
  734. enableDebug: "Включить отладку",
  735. updateNotification: "Уведомление после обновления правила",
  736. disable: "Выключить",
  737. disableSite: "Включить/выключить на сайте",
  738. disableSiteTips: "Выключено для этого сайта",
  739. enableSiteTips: "Включено для этого сайта",
  740. enable: "Включить",
  741. toTop: "Наверх",
  742. toBottom: "Вниз",
  743. current: "Текущая страница",
  744. forceIframe: "Подгрузить ещё страницу",
  745. cancelForceIframe: "Отменить подгрузку",
  746. configure: "Настройки",
  747. firstUpdate: "Нажмите здесь, чтобы инициализировать правила",
  748. update: "Обновить правила",
  749. click2update: "Нажмите, чтобы обновить правила",
  750. loadNow: "Загрузить следующую страницу",
  751. loadConfirm: "Сколько страниц вы хотите загрузить? (0 означает бесконечность)",
  752. noNext: "Ссылка на следующую страницу не найдена. Пожалуйста, создайте новое правило",
  753. passSec: "Обновлено #t# секунд назад",
  754. passMin: "Обновлено #t# минут назад",
  755. passHour: "Обновлено #t# часов назад",
  756. passDay: "Обновлено #t# дней назад",
  757. cantDel: "Нельзя удалить правила по умолчанию",
  758. confirmDel: "Вы уверены, что хотите удалить эту ссылку?",
  759. updateSucc: "Правила обновлены",
  760. beginUpdate: "Обновление. Пожалуйста, немного подождите",
  761. customUrls: "Ссылки с правилами для импорта. Одна ссылка на строку",
  762. customRules: "Введите пользовательские правила в формате Pagetual. <a href='#t#'>✍️Улучшить встроенные правила</a>",
  763. save: "Сохранить настройки",
  764. loadingText: "Следующая страница подгружается…",
  765. opacity: "Прозрачность",
  766. opacityPlaceholder: "0 - скрыть",
  767. hideBar: "Скрыть разделитель страниц",
  768. hideBarButNoStop: "Скрыть, но не останавливать",
  769. dbClick2Stop: "Двойной клик на странице для выключения",
  770. sortTitle: "Правило сортировки применится после следующего обновления правил",
  771. autoRun: "Автозапуск (режим черного списка)",
  772. autoLoadNum: "Количество страниц для предзагрузки",
  773. turnRate: "Подгрузить страницу, когда она будет в 【X】 раз больше высоты страницы от конца страницы",
  774. inputPageNum: "Введите номер страницы для перехода",
  775. enableHistory: "Записать историю после переключения страниц",
  776. enableHistoryAfterInsert: "Записать запись истории сразу после вставки, иначе записать после просмотра",
  777. contentVisibility: "Автоматически переключать contentVisibility для повышения производительности рендеринга",
  778. initRun: "Подгружать страницы сразу после открытия",
  779. preload: "Предзагрузка следующей страницы",
  780. click2ImportRule: "Нажмите, чтобы импортировать базовые правила: ",
  781. forceAllBody: "Присоединить страницу целиком?",
  782. openInNewTab: "Открыть дополнительные ссылки в новой вкладке",
  783. importSucc: "Импорт завершен",
  784. import: "Импорт",
  785. editCurrent: "Изменить правило для текущего сайта",
  786. editBlacklist: "Изменить черный список. Одна ссылка на строку. Поддерживаются метасимволы: ? и *",
  787. upBtnImg: "Иконка перехода к началу",
  788. downBtnImg: "Иконка перехода к концу",
  789. sideControllerIcon: "Значок боковой панели",
  790. loadingTextTitle: "Текст во время загрузки",
  791. dbClick2StopCtrl: "Ctrl",
  792. dbClick2StopAlt: "Alt",
  793. dbClick2StopShift: "Shift",
  794. dbClick2StopMeta: "Meta",
  795. dbClick2StopKey: "Клавиша",
  796. pageElementCss: "Пользовательский стиль для основных элементов страницы",
  797. customCss: "Полный пользовательский CSS",
  798. firstAlert: "Вы не импортировали базовое правило. Пожалуйста, выберите соответствующее правило для импорта",
  799. picker: "Pagetual: выбор элемента страницы",
  800. closePicker: "Закрыть окно Pagetual",
  801. pickerPlaceholder: "Если не знаете, что тут писать — оставьте поле пустым",
  802. pickerCheck: "Проверить и скопировать селектор",
  803. switchSelector: "Нажмите для выбора элемента",
  804. gotoEdit: "Перейти к редактированию правила с текущим селектором",
  805. manualMode: "Отключить автоматическую загрузку страниц. Загружать вручную с помощью стрелки вправо (или вызова события 'pagetual.next')",
  806. clickMode: "Отключить \"сшивание\" страниц. При прокрутке до конца автоматически переходить на следующую страницу",
  807. pageBarMenu: "Открывать меню кликом на середину панели страниц",
  808. nextSwitch: "Переключить ссылку на следующую страницу",
  809. arrowToScroll: "Листать страницы клавишами со стрелками влево и вправо",
  810. sideController: "Показать справа панель перемещения по вкладке",
  811. sideControllerScroll: "Переключатель прокрутки",
  812. sideControllerAlways: "Всегда показывать",
  813. hideLoadingIcon: "Скрыть анимацию загрузки",
  814. hideBarArrow: "Скрыть кнопки перемещения на разделителе",
  815. duplicate: "Похоже, Pagetual установлен несколько раз. Пожалуйста, удалите Pagetual из других менеджеров скриптов!",
  816. forceStateIframe: "Вставить полную страницу как iframe",
  817. forceStateDynamic: "Загружать динамический контент через iframe",
  818. forceStateDisable: "Отключить перелистывание страниц на этой станции",
  819. autoScrollRate: "Скорость прокрутки (1~1000)",
  820. disableAutoScroll: "Остановить автоматическую прокрутку",
  821. enableAutoScroll: "Включить автопрокрутку",
  822. toggleAutoScroll: "Переключить автопрокрутку",
  823. ruleRequest: "Запрос правил",
  824. page: "Страница ",
  825. prevPage: "Предыдущая страница",
  826. nextPage: "Следующая страница",
  827. errorRulesMustBeArray: "Правила должны быть массивом!",
  828. errorJson: "Ошибка разбора JSON. Пожалуйста, исправьте его",
  829. editSuccess: "Редактирование успешно",
  830. errorWrongUrl: "Ссылка некорректна. Пожалуйста, исправьте её",
  831. errorAlreadyExists: "Уже существует!",
  832. settingsSaved: "Настройки сохранены. Обновите страницы",
  833. iframe: "iframe",
  834. dynamic: "Динамически",
  835. reloadPage: "Редактирование завершено. Обновить страницу?",
  836. copied: "Скопировано",
  837. noValidContent: "Действительный контент не обнаружен, нажмите для просмотра",
  838. outOfDate: "Скрипт устарел, своевременно обновляйте до последней версии!",
  839. hideBarTips: "Скрыть панель разбиения на страницы, иммерсивный опыт",
  840. setConfigPage: "Установить текущую страницу в качестве страницы конфигурации по умолчанию",
  841. wedata2github: "Изменить адрес wedata на зеркальный адрес на складе github",
  842. addOtherProp: "Добавить свойство правила",
  843. addNextSelector: "Добавить содержимое селектора как nextLink",
  844. addPageSelector: "Добавить содержимое селектора как pageElement",
  845. propName: "Введите имя свойства правила",
  846. propValue: "Введите значение свойства правила",
  847. customFirst: "Игнорировать кеш для локальных пользовательских правил",
  848. rulesExample: "Подробное объяснение настраиваемых правил",
  849. lastPage: "Достигнута последняя страница",
  850. lastPageTips: "Показывать подсказки при достижении последней страницы"
  851. }
  852. }
  853. ];
  854. var langList = {};
  855. langData.forEach(lang => {
  856. langList[lang.match[0]] = lang.name;
  857. });
  858. var i18nData = langData[0].lang;
  859. function setLang(la) {
  860. for (let i = 0; i < langData.length; i++) {
  861. let lang = langData[i];
  862. if (lang && lang.match.indexOf(la) !== -1) {
  863. i18nData = lang.lang;
  864. break;
  865. }
  866. }
  867. }
  868. setLang(lang);
  869. var enableDebug = true;
  870. var _GM_xmlhttpRequest, _GM_registerMenuCommand, _GM_notification, _GM_addStyle, _GM_openInTab, _GM_info, _GM_setClipboard;
  871. function i18n(name, param) {
  872. return i18nData[name] ? i18nData[name].replace("#t#", param) : name;
  873. }
  874.  
  875. function debug(str, title) {
  876. if (enableDebug) {
  877. console.log(
  878. `%cPagetual v.${_GM_info.script.version}】 ${title ? title : 'debug'}:`,
  879. 'color: yellow;font-size: large;font-weight: bold;background-color: darkblue;',
  880. str
  881. );
  882. }
  883. }
  884.  
  885. if (typeof GM_xmlhttpRequest !== 'undefined') {
  886. _GM_xmlhttpRequest = GM_xmlhttpRequest;
  887. } else if (typeof GM !== 'undefined' && typeof GM.xmlHttpRequest !== 'undefined') {
  888. _GM_xmlhttpRequest = GM.xmlHttpRequest;
  889. } else {
  890. _GM_xmlhttpRequest = (f) => {fetch(f.url, {method: f.method || 'GET', body: f.data, headers: f.headers}).then(response => response.text()).then(data => {f.onload && f.onload({response: data})}).catch(f.onerror && f.onerror())};
  891. }
  892. if (typeof GM_registerMenuCommand !== 'undefined') {
  893. _GM_registerMenuCommand = GM_registerMenuCommand;
  894. } else if (typeof GM !== 'undefined' && typeof GM.registerMenuCommand !== 'undefined') {
  895. _GM_registerMenuCommand = GM.registerMenuCommand;
  896. } else {
  897. _GM_registerMenuCommand = (s, f) => {debug(s); debug(f);};
  898. }
  899. if (typeof GM_info !== 'undefined') {
  900. _GM_info = GM_info;
  901. } else if (typeof GM !== 'undefined' && typeof GM.info !== 'undefined') {
  902. _GM_info = GM.info;
  903. } else {
  904. _GM_info = {script: {}};
  905. }
  906. if (typeof GM_notification !== 'undefined') {
  907. _GM_notification = GM_notification;
  908. } else if (typeof GM !== 'undefined' && typeof GM.notification !== 'undefined') {
  909. _GM_notification = GM.notification;
  910. } else {
  911. _GM_notification = (s) => {showTips(String(s.text || s));};
  912. }
  913. if (typeof GM_openInTab !== 'undefined') {
  914. _GM_openInTab = GM_openInTab;
  915. } else if (typeof GM !== 'undefined' && typeof GM.openInTab !== 'undefined') {
  916. _GM_openInTab = GM.openInTab;
  917. } else {
  918. _GM_openInTab = (s,t) => {window.open(s); debug(t);};
  919. }
  920. if (typeof GM_addStyle !== 'undefined') {
  921. _GM_addStyle = GM_addStyle;
  922. } else if (typeof GM !== 'undefined' && typeof GM.addStyle !== 'undefined') {
  923. _GM_addStyle = GM.addStyle;
  924. } else {
  925. _GM_addStyle = cssStr => {
  926. let styleEle = document.createElement("style");
  927. styleEle.innerHTML = cssStr;
  928. document.head.appendChild(styleEle);
  929. return styleEle;
  930. };
  931. }
  932. if (typeof GM_setClipboard !== 'undefined') {
  933. _GM_setClipboard = GM_setClipboard;
  934. } else if (typeof GM !== 'undefined' && typeof GM.setClipboard !== 'undefined') {
  935. _GM_setClipboard = GM.setClipboard;
  936. } else {
  937. _GM_setClipboard = (s, i) => {debug(s); debug(i);};
  938. }
  939. const _unsafeWindow = (typeof unsafeWindow === 'undefined') ? window : unsafeWindow;//兼容 ios userscripts 的寫法
  940. const storage = {
  941. supportGM: typeof GM_getValue === 'function' && typeof GM_getValue('a', 'b') !== 'undefined',
  942. supportGMPromise: typeof GM !== 'undefined' && typeof GM.getValue === 'function' && typeof GM.getValue('a', 'b') !== 'undefined' && typeof GM.getValue('a', 'b').then === 'function',
  943. supportCrossSave: function() {
  944. return this.supportGM || this.supportGMPromise;
  945. },
  946. mxAppStorage: (function() {
  947. try {
  948. return window.external.mxGetRuntime().storage;
  949. } catch(e) {
  950. }
  951. })(),
  952. operaUJSStorage: (function() {
  953. try {
  954. return window.opera.scriptStorage;
  955. } catch(e) {
  956. }
  957. })(),
  958. setItem: function(key, value) {
  959. if (this.supportGMPromise) {
  960. GM.setValue(key, value);
  961. if (value === "" && typeof GM !== 'undefined' && typeof GM.deleteValue !== 'undefined') {
  962. GM.deleteValue(key);
  963. }
  964. } else if (this.supportGM) {
  965. GM_setValue(key, value);
  966. if (value === "" && typeof GM_deleteValue !== 'undefined') {
  967. GM_deleteValue(key);
  968. }
  969. } else if (this.operaUJSStorage) {
  970. this.operaUJSStorage.setItem(key, value);
  971. } else if (this.mxAppStorage) {
  972. this.mxAppStorage.setConfig(key, value);
  973. } else if (window.localStorage) {
  974. window.localStorage.setItem(key, value);
  975. }
  976. },
  977. getItem: function(key, cb) {
  978. var value;
  979. if (this.supportGMPromise) {
  980. value = GM.getValue(key).then(v => {cb(v);});
  981. return;
  982. } else if (this.supportGM) {
  983. value = GM_getValue(key);
  984. } else if (this.operaUJSStorage) {
  985. value = this.operaUJSStorage.getItem(key);
  986. } else if (this.mxAppStorage) {
  987. value = this.mxAppStorage.getConfig(key);
  988. } else if (window.localStorage) {
  989. value = window.localStorage.getItem(key);
  990. }
  991. cb(value);
  992. }
  993. };
  994. async function getData(key) {
  995. return new Promise((resolve) => {
  996. storage.getItem(key, value => {
  997. resolve(value);
  998. });
  999. });
  1000. }
  1001. async function getListData(list, key) {
  1002. return new Promise((resolve) => {
  1003. storage.getItem(list, listData => {
  1004. let value;
  1005. if (listData) {
  1006. for(var i = 0; i < listData.length; i++) {
  1007. let data = listData[i];
  1008. if (data.k === key) {
  1009. value = data.v;
  1010. break;
  1011. }
  1012. }
  1013. }
  1014. resolve(value);
  1015. });
  1016. });
  1017. }
  1018. function setListData(list, key, value, length) {
  1019. storage.getItem(list, listData => {
  1020. if (!listData) {
  1021. listData = [];
  1022. }
  1023. listData = listData.filter(data => data && data.k !== key);
  1024. if (value !== "") {
  1025. listData.unshift({k: key, v: value});
  1026. if (listData.length > (length || 100)) {
  1027. listData.pop();
  1028. }
  1029. }
  1030. storage.setItem(list, listData);
  1031. });
  1032. }
  1033. const isMobile = ('ontouchstart' in document.documentElement);
  1034. const configPage = [`https://pagetual.hoothin.com/${lang === 'zh-CN' ? 'cn/' : ''}rule.html`,
  1035. "https://github.com/hoothin/UserScripts/tree/master/Pagetual",
  1036. "https://hoothin.github.io/UserScripts/Pagetual/"];
  1037. const firstRunPage = "https://pagetual.hoothin.com/firstRun";
  1038. const guidePage = /^https?:\/\/.*pagetual.*rule\.html/i;
  1039. const ruleImportUrlReg = /greasyfork\.org\/.*scripts\/438684(\-[^\/]*)?(\/discussions|\/?$|\/feedback)|github\.com\/hoothin\/UserScripts\/(tree\/master\/Pagetual|issues)/i;
  1040. const allOfBody = "body>*";
  1041. const mainSel = ["article,.article","[role=main],main,.main,#main","#results"];
  1042. const nextTextReg1 = new RegExp("\u005e\u7ffb\u003f\u005b\u4e0b\u540e\u5f8c\u6b21\u005d\u005b\u4e00\u30fc\u0031\u005d\u003f\u005b\u9875\u9801\u5f20\u5f35\u005d\u007c\u005e\u006e\u0065\u0078\u0074\u005b\u005c\u0073\u005f\u002d\u005d\u003f\u0070\u0061\u0067\u0065\u005c\u0073\u002a\u005b\u203a\u003e\u2192\u00bb\u005d\u003f\u0024\u007c\u6b21\u306e\u30da\u30fc\u30b8\u007c\u005e\u6b21\u3078\u003f\u0024\u007c\u0412\u043f\u0435\u0440\u0435\u0434", "i");
  1043. const nextTextReg2 = new RegExp("\u005e\u0028\u005b\u4e0b\u540e\u5f8c\u6b21\u005d\u005b\u4e00\u30fc\u0031\u005d\u003f\u005b\u7ae0\u8bdd\u8a71\u8282\u7bc0\u5e45\u005d\u007c\u006e\u0065\u0078\u0074\u002e\u003f\u0063\u0068\u0061\u0070\u0074\u0065\u0072\u007c\u00bb\u007c\u003e\u003e\u0029\u0028\u005b\u003a\uff1a\u005c\u002d\u005f\u2014\u005c\u0073\u005c\u002e\u3002\u003e\u0023\u00b7\u005c\u005b\u3010\u3001\uff08\u005c\u0028\u002f\u002c\uff0c\uff1b\u003b\u2192\u005d\u007c\u0024\u0029", "i");
  1044. const lazyImgAttr = ["data-lazy-src", "data-lazy", "data-isrc", "data-url", "data-orig-file", "zoomfile", "file", "original", "load-src", "imgsrc", "real_src", "src2", "origin-src", "data-lazyload", "data-lazyload-src", "data-lazy-load-src", "data-ks-lazyload", "data-ks-lazyload-custom", "data-src", "data-defer-src", "data-actualsrc", "data-cover", "data-original", "data-thumb", "data-imageurl", "data-placeholder", "lazysrc"];
  1045. var rulesData = {uninited: true, firstRun: true, sideController: !isMobile}, ruleUrls, updateDate, clickedSth = false, loadNowNum = 5, autoScrollRate = 50;
  1046. var isPause = false, manualPause = false, isHideBar = false, isLoading = false, curPage = 1, forceState = 0, autoScroll = 0, autoScrollInterval, bottomGap = 1000, autoLoadNum = -1, nextIndex = 0, stopScroll = false, clickMode = false, openInNewTab = 0, charset = "UTF-8", charsetValid = true, urlWillChange = false;
  1047. var tryTimes = 0, showedLastPageTips = false, rate = 1, author = '';
  1048.  
  1049. function getBody(doc) {
  1050. return doc.body || doc.querySelector('body') || doc;
  1051. }
  1052.  
  1053. function getElementByXpath(xpath, doc, contextNode) {
  1054. if (doc && doc.ownerDocument) doc = doc.ownerDocument;
  1055. doc = (doc && doc.evaluate) ? doc : document;
  1056. contextNode = contextNode || doc;
  1057. try {
  1058. let result = doc.evaluate(xpath, contextNode, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  1059. return result.singleNodeValue && result.singleNodeValue.nodeType === 1 && result.singleNodeValue;
  1060. } catch (err) {
  1061. debug(`Invalid xpath: ${xpath}`);
  1062. }
  1063. return null;
  1064. }
  1065.  
  1066. function getAllElementsByXpath(xpath, contextNode, doc) {
  1067. if (doc && doc.ownerDocument) doc = doc.ownerDocument;
  1068. doc = (doc && doc.evaluate) ? doc : document;
  1069. contextNode = contextNode || doc;
  1070. var result = [];
  1071. try {
  1072. var query = doc.evaluate(xpath, contextNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  1073. for (var i = 0; i < query.snapshotLength; i++) {
  1074. var node = query.snapshotItem(i);
  1075. if (node.nodeType === 1) {
  1076. result.push(node);
  1077. }
  1078. }
  1079. } catch (err) {
  1080. debug(`Invalid xpath: ${xpath}`);
  1081. }
  1082. return result;
  1083. }
  1084.  
  1085. function isXPath(xpath) {
  1086. if (!xpath) {
  1087. return false;
  1088. }
  1089. return /^\(*(descendant::|\.\/|\/|id\()/.test(xpath);
  1090. }
  1091.  
  1092. function getAllElements(sel, doc, contextNode) {
  1093. try {
  1094. if (!isXPath(sel)) {
  1095. return doc.querySelectorAll(sel);
  1096. }
  1097. } catch(e) {
  1098. debug(e, 'Error selector');
  1099. }
  1100. return getAllElementsByXpath(sel, contextNode, doc);
  1101. }
  1102.  
  1103. function getElement(sel, doc, contextNode, bySort) {
  1104. try {
  1105. if (!isXPath(sel)) {
  1106. if (!bySort) {
  1107. return doc.querySelector(sel);
  1108. } else {
  1109. let selArr = sel.split(",");
  1110. try {
  1111. for (let i = 0; i < selArr.length; i++) {
  1112. let ele = doc.querySelector(selArr[i].trim());
  1113. if (ele) {
  1114. return ele;
  1115. }
  1116. }
  1117. } catch(e) {
  1118. return doc.querySelector(sel);
  1119. }
  1120. return null;
  1121. }
  1122. }
  1123. } catch(e) {
  1124. debug(e, 'Error selector');
  1125. }
  1126. return getElementByXpath(sel, doc, contextNode);
  1127. }
  1128.  
  1129. function compareNodeName(node, names) {
  1130. if (!node || !node.nodeName || !node.nodeName.toLowerCase) {
  1131. return false;
  1132. }
  1133. let nodeName = node.nodeName.toLowerCase();
  1134. for (let i = 0; i < names.length; i++) {
  1135. if (names[i] === nodeName) {
  1136. return true;
  1137. }
  1138. }
  1139. return false;
  1140. }
  1141.  
  1142. function geneSelector(ele, addID, exact) {
  1143. let selector = ele.nodeName.toLowerCase();
  1144. //Google id class都是隨機。百度更過分,style script順序都是隨機的
  1145. if (selector !== "html" && selector !== "body") {
  1146. let hasId = false;
  1147. if (addID && ele.id && /^[a-z_][\w\-_]*$/i.test(ele.id)) {
  1148. if (ele.ownerDocument && ele.ownerDocument.querySelectorAll("#" + ele.id).length === 1) {
  1149. hasId = true;
  1150. selector = '#' + ele.id;
  1151. }
  1152. }
  1153. if (!hasId) {
  1154. let className = "";
  1155. if (ele.className) {
  1156. let classList = ele.classList;
  1157. for (let i = 0; i < classList.length; i++) {
  1158. let c = classList[i];
  1159. if (/^[\w\-_]+$/.test(c) && !/\d{4,}/.test(c)) {
  1160. className += '.' + c;
  1161. }
  1162. }
  1163. selector += className;
  1164. }
  1165. let parent = ele.parentElement;
  1166. if (parent) {
  1167. if (exact) {
  1168. let i, nth = 0, all = 0;
  1169. for (i = 0; i < parent.children.length; i++) {
  1170. if (parent.children[i].nodeName === ele.nodeName) {
  1171. all++;
  1172. if (parent.children[i] === ele) {
  1173. nth = all;
  1174. }
  1175. if (nth > 0 && all > 1) {
  1176. break;
  1177. }
  1178. }
  1179. }
  1180. selector += (all === 1 ? "" : `:nth-of-type(${nth})`);
  1181. } else if (!className && !hasId && parent.children.length > 1 && !compareNodeName(parent, ["html"])) {
  1182. let prevE = ele.previousElementSibling;
  1183. if (prevE && prevE.className) {
  1184. let classList = prevE.classList;
  1185. for (let i = 0; i < classList.length; i++) {
  1186. let c = classList[i];
  1187. if (/^[\w\-_]+$/.test(c) && !/\d{4,}/.test(c)) {
  1188. className += '.' + c;
  1189. }
  1190. }
  1191. if (className) {
  1192. selector = prevE.nodeName.toLowerCase() + className + "+" + selector;
  1193. }
  1194. }
  1195. if (!className) {
  1196. let i, nth = 0, all = 0;
  1197. for (i = 0; i < parent.children.length; i++) {
  1198. if (parent.children[i].nodeName === ele.nodeName) {
  1199. all++;
  1200. if (parent.children[i] === ele) {
  1201. nth = all;
  1202. }
  1203. if (nth > 0 && all > 1) {
  1204. break;
  1205. }
  1206. }
  1207. }
  1208. selector += (all === 1 ? "" : `:nth-of-type(${nth})`);
  1209. }
  1210. }
  1211. selector = geneSelector(parent, addID, exact) + ' > ' + selector;
  1212. }
  1213. }
  1214. }
  1215. return selector;
  1216. }
  1217.  
  1218. function createXPathFromElement(elm) {
  1219. let allNodes = document.getElementsByTagName('*'), segs;
  1220. for (segs = []; elm && elm.nodeType === 1; elm = elm.parentNode) {
  1221. if (compareNodeName(elm, ["body", "html"])) {
  1222. segs.unshift(elm.localName.toLowerCase());
  1223. continue;
  1224. }
  1225. if (elm.hasAttribute && elm.hasAttribute('id')) {
  1226. var uniqueIdCount = 0;
  1227. for (var n = 0; n < allNodes.length; n++) {
  1228. if (allNodes[n].hasAttribute('id') && allNodes[n].id === elm.id) {
  1229. uniqueIdCount++;
  1230. }
  1231. if (uniqueIdCount > 1) {
  1232. break;
  1233. }
  1234. }
  1235. if ( uniqueIdCount === 1) {
  1236. segs.unshift('id("' + elm.getAttribute('id') + '")');
  1237. return segs.join('/');
  1238. } else {
  1239. segs.unshift(elm.localName.toLowerCase() + '[@id="' + elm.getAttribute('id') + '"]');
  1240. }
  1241. } else if (elm.hasAttribute && elm.hasAttribute('class')) {
  1242. segs.unshift(elm.localName.toLowerCase() + '[@class="' + elm.getAttribute('class') + '"]');
  1243. } else {
  1244. let i, sib;
  1245. for (i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling) {
  1246. if (sib.localName === elm.localName) {
  1247. i++;
  1248. }
  1249. }
  1250. segs.unshift(elm.localName.toLowerCase() + '[' + i + ']');
  1251. }
  1252. }
  1253. return segs.length ? '/' + segs.join('/') : null;
  1254. }
  1255.  
  1256. const escapeHTMLPolicy = (_unsafeWindow.trustedTypes && _unsafeWindow.trustedTypes.createPolicy) ? _unsafeWindow.trustedTypes.createPolicy('pagetual_default', {
  1257. createHTML: (string, sink) => string
  1258. }) : null;
  1259.  
  1260. function createHTML(html) {
  1261. return escapeHTMLPolicy ? escapeHTMLPolicy.createHTML(html) : html;
  1262. }
  1263.  
  1264. const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
  1265.  
  1266. async function sleep(time) {
  1267. await new Promise((resolve) => {
  1268. setTimeout(() => {
  1269. resolve();
  1270. }, time);
  1271. });
  1272. }
  1273.  
  1274. class RuleParser {
  1275. constructor() {
  1276. this.hpRules = [];
  1277. this.smartRules = [];
  1278. this.customRules = [];
  1279. this.rules = [];
  1280. this.pageDoc = document;
  1281. this.nextLinkHref = null;
  1282. this.nextTitle = "";
  1283. this.oldUrl = "";
  1284. this.curUrl = location.href;
  1285. this.curSiteRule = {};
  1286. }
  1287.  
  1288. async initSavedRules(callback) {
  1289. var self = this;
  1290. let smartRules = await getData("smartRules");
  1291. if (smartRules) self.smartRules = smartRules;
  1292. let hpRules = await getData("hpRules");
  1293. if (hpRules) self.hpRules = hpRules;
  1294. let customRules = await getData("customRules");
  1295. if (customRules) self.customRules = customRules;
  1296. if (_unsafeWindow.pagetualRules && _unsafeWindow.pagetualRules.length) {
  1297. _unsafeWindow.pagetualRules.forEach(rule => {
  1298. rule.isScript = true;
  1299. });
  1300. self.customRules = _unsafeWindow.pagetualRules.concat(self.customRules);
  1301. }
  1302. let rules = await getData("rules");
  1303. if (rules) self.rules = rules;
  1304. callback();
  1305. }
  1306.  
  1307. saveCurSiteRule() {
  1308. /*if(!this.curSiteRule || !this.curSiteRule.url || this.curSiteRule.smart || this.curSiteRule.url.length<13)return;
  1309. this.hpRules=this.hpRules.filter(item=>{return item&&item.url!=this.curSiteRule.url});
  1310. this.hpRules.unshift(this.curSiteRule);
  1311. if(this.hpRules.length>30){
  1312. this.hpRules.pop();
  1313. }
  1314. storage.setItem("hpRules", this.hpRules);*/
  1315. }
  1316.  
  1317. requestJSON(url, callback) {
  1318. _GM_xmlhttpRequest({
  1319. url: url,
  1320. method: 'GET',
  1321. timeout: 1000000,
  1322. headers: {
  1323. 'accept': 'application/json,text/html',
  1324. 'Referer': url,
  1325. },
  1326. onload: function(res) {
  1327. let json = null;
  1328. try {
  1329. json = JSON.parse(res.response || res.responseText);
  1330. } catch(e) {
  1331. debug(e, 'Error json');
  1332. }
  1333. callback(json);
  1334. },
  1335. onerror: function(e) {
  1336. callback(null, e);
  1337. },
  1338. ontimeout: function(e) {
  1339. callback(null, e);
  1340. }
  1341. });
  1342. }
  1343.  
  1344. formatRule(item, from) {
  1345. if (item.data && item.data.url) {
  1346. let result = {
  1347. name: item.name,
  1348. from: from,
  1349. action: item.data.forceIframe === "true" ? 1 : undefined,
  1350. url: item.data.url,
  1351. pageElement: item.data.pageElement,
  1352. nextLink: item.data.nextLink,
  1353. insert: item.data.insertBefore||undefined,
  1354. updatedAt: item.updated_at
  1355. };
  1356. let _css = (item.data.Stylus || '') + (item.data.CSS || '');
  1357. if (_css) result.css = _css;
  1358. if (item.data.bookmarklet) result.pageAction = item.data.bookmarklet;
  1359. return result;
  1360. } else {
  1361. item.from = from;
  1362. return item;
  1363. }
  1364. return null;
  1365. }
  1366.  
  1367. addRuleByUrl(url, from, callback) {
  1368. if (url.indexOf("?") === -1) {
  1369. url = url + "?" + Date.now();
  1370. } else {
  1371. url = url + "&" + Date.now();
  1372. }
  1373. this.requestJSON(url, (json,err) => {
  1374. if (!json) {
  1375. debug(err, "Failed to update " + url + " rules!");
  1376. }
  1377. this.addRules(json, from);
  1378. callback(json, err);
  1379. });
  1380. }
  1381.  
  1382. addRules(rules, from) {
  1383. if (rules && rules.length > 0) {
  1384. let first = -1;
  1385. this.rules = this.rules.filter((item, i) => {
  1386. if (item.from === from) {
  1387. if (first === -1) first = i;
  1388. return false;
  1389. } else return true;
  1390. });
  1391. if (first === -1) first = 0;
  1392. rules.forEach(item => {
  1393. let rule = this.formatRule(item, from);
  1394. if (rule) {
  1395. this.rules.splice(first, 0, rule)
  1396. }
  1397. });
  1398. }
  1399. }
  1400.  
  1401. ruleMatchPre(r) {
  1402. if (r.include) {
  1403. let include;
  1404. if (Array && Array.isArray && Array.isArray(r.include)) {
  1405. include = r.include.every((sel, i) => {
  1406. let ele = getElement(sel, document);
  1407. return !!ele;
  1408. });
  1409. } else include = getElement(r.include, document);
  1410. if (!include) return false;
  1411. }
  1412. if (r.exclude) {
  1413. let exclude;
  1414. if (Array && Array.isArray && Array.isArray(r.exclude)) {
  1415. exclude = !r.exclude.every((sel, i) => {
  1416. let ele = getElement(sel, document);
  1417. return !ele;
  1418. });
  1419. } else exclude = getElement(r.exclude, document);
  1420. if (exclude) return false;
  1421. }
  1422. return true;
  1423. }
  1424.  
  1425. ruleMatchReady(r) {
  1426. let findIndex = 0;
  1427. if (r.nextLink && r.nextLink !== 0) {
  1428. let nextLinkSel = r.nextLink, nextLink;
  1429. if (Array && Array.isArray && Array.isArray(nextLinkSel)) {
  1430. nextLink = !nextLinkSel.every((sel, i) => {
  1431. let ele = getElement(sel, document);
  1432. if (ele) findIndex = i;
  1433. return !ele;
  1434. });
  1435. } else nextLink = getElement(nextLinkSel, document);
  1436. if (!nextLink) return false;
  1437. }
  1438. if (r.pageElement) {
  1439. let pageElementSel = r.pageElement, pageElement;
  1440. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  1441. pageElementSel = pageElementSel[findIndex];
  1442. }
  1443. pageElement = getElement(pageElementSel, document);
  1444. if (!pageElement) return false;
  1445. }
  1446. if (r.insert) {
  1447. let insertSel = r.insert, insert;
  1448. if (Array && Array.isArray && Array.isArray(insertSel)) {
  1449. insertSel = insertSel[findIndex];
  1450. }
  1451. insert = getElement(insertSel, document);
  1452. if (!insert) return false;
  1453. }
  1454. //if (findIndex !== 0) nextIndex = findIndex;
  1455. return true;
  1456. }
  1457.  
  1458. ruleMatch(r) {
  1459. return this.ruleMatchPre(r) && this.ruleMatchReady(r);
  1460. }
  1461.  
  1462. scrollToShow(sel, doc) {
  1463. let exclude = getElement(sel, doc);
  1464. if (exclude) {
  1465. var actualTop = exclude.offsetTop;
  1466. var current = exclude.offsetParent;
  1467. while (current !== null) {
  1468. actualTop += current.offsetTop;
  1469. current = current.offsetParent;
  1470. }
  1471. getBody(doc).scrollTop = 0;
  1472. doc.documentElement.scrollTop = 0;
  1473. let maxHeight = Math.max(getBody(doc).scrollHeight, doc.documentElement.scrollHeight);
  1474. getBody(doc).scrollTop = actualTop - 10;
  1475. doc.documentElement.scrollTop = actualTop - 10;
  1476. setTimeout(() => {
  1477. while (actualTop < maxHeight) {
  1478. actualTop += 200;
  1479. getBody(doc).scrollTop = actualTop;
  1480. doc.documentElement.scrollTop = actualTop;
  1481. }
  1482. }, 0);
  1483. return false;
  1484. }
  1485. return true;
  1486. }
  1487.  
  1488. waitElement(doc, selArr) {
  1489. if (!selArr) selArr = this.curSiteRule.waitElement;
  1490. if (!Array.isArray(selArr)) {
  1491. selArr = [selArr];
  1492. }
  1493. let includeSel = selArr[0].trim(), excludeSel;
  1494. if (selArr.length === 2) {
  1495. excludeSel = selArr[1].trim().replace(/^!/, '');
  1496. } else if (includeSel.indexOf('!') === 0) {
  1497. excludeSel = includeSel.replace(/^!/, '');
  1498. includeSel = '';
  1499. }
  1500. if (includeSel) {
  1501. let include = getElement(includeSel, doc);
  1502. if (!include) {
  1503. if (doc !== document) {
  1504. getBody(doc).scrollTop = 9999999;
  1505. doc.documentElement.scrollTop = 9999999;
  1506. }
  1507. return false;
  1508. }
  1509. }
  1510. if (doc === document) return true;
  1511. if (excludeSel) {
  1512. if (!this.scrollToShow(excludeSel, doc)) {
  1513. if (!loadingDiv.offsetParent && this.insert.parentNode) {
  1514. this.insertElement(loadingDiv);
  1515. }
  1516. return false;
  1517. }
  1518. }
  1519. return true;
  1520. }
  1521.  
  1522. runPageBar(pageBar) {
  1523. if (this.curSiteRule.pageBar && this.curSiteRule.pageBar !== 0) {
  1524. try {
  1525. ((typeof this.curSiteRule.pageBar === 'function') ? this.curSiteRule.pageBar : Function("pageBar",'"use strict";' + this.curSiteRule.pageBar))(pageBar);
  1526. } catch(e) {
  1527. debug(e);
  1528. }
  1529. }
  1530. }
  1531.  
  1532. runWait(cb) {
  1533. let checkEval = null, waitTime = 0;
  1534. if (this.curSiteRule.waitElement) {
  1535. checkEval = async doc => {
  1536. return await this.waitElement(doc);
  1537. };
  1538. } else if(this.curSiteRule.wait) {
  1539. if (isNaN(this.curSiteRule.wait)) {
  1540. try {
  1541. checkEval = (typeof this.curSiteRule.wait === 'function') ? this.curSiteRule.wait : new AsyncFunction("doc", '"use strict";' + this.curSiteRule.wait);
  1542. } catch(e) {
  1543. debug(e);
  1544. }
  1545. } else {
  1546. waitTime = this.curSiteRule.wait;
  1547. }
  1548. }
  1549. cb(checkEval, waitTime);
  1550. }
  1551.  
  1552. findNoNext() {
  1553. if (!this.curSiteRule || !this.curSiteRule.smart || this.curSiteRule.nextLink === 0 || this.possibleRule) return;
  1554. let self = this;
  1555. self.curSiteRule.nextLink = 0;
  1556. self.smartRules = self.smartRules.filter(item => {return item && item.url !== self.curSiteRule.url;});
  1557. self.smartRules.unshift(self.curSiteRule);
  1558. storage.setItem("smartRules", self.smartRules);
  1559. }
  1560.  
  1561. async getRule(callback) {
  1562. var href = location.href.slice(0, 500);
  1563. if(noRuleTest) {
  1564. this.curSiteRule = {};
  1565. this.curSiteRule.url = href;
  1566. this.curSiteRule.smart = true;
  1567. callback();
  1568. return;
  1569. }
  1570. if (_unsafeWindow.pagetualRule) {
  1571. this.curSiteRule = _unsafeWindow.pagetualRule;
  1572. if (!this.curSiteRule.url) this.curSiteRule.url = ".";
  1573. this.curSiteRule.isScript = true;
  1574. }
  1575. if (this.curSiteRule && this.curSiteRule.url && !this.curSiteRule.smart) {
  1576. let urlReg = new RegExp(this.curSiteRule.url, "i");
  1577. if (urlReg.test(href) && this.ruleMatch(this.curSiteRule)) {
  1578. return callback();
  1579. }
  1580. }
  1581. if (this.possibleRule) {
  1582. let urlReg = new RegExp(this.possibleRule.url, "i");
  1583. if (urlReg.test(href) && this.ruleMatch(this.possibleRule)) {
  1584. this.curSiteRule = this.possibleRule;
  1585. debug(this.curSiteRule, 'Match');
  1586. return callback();
  1587. }
  1588. }
  1589. this.curSiteRule = {};
  1590. var self = this;
  1591.  
  1592. function setRule(r) {
  1593. if (self.preSiteRule) {
  1594. href = location.href.slice(0, 500);
  1595. let urlReg = new RegExp(self.preSiteRule.url, "i");
  1596. if (urlReg.test(href) && self.ruleMatch(self.preSiteRule)) {
  1597. self.curSiteRule = self.preSiteRule;
  1598. return callback();
  1599. }
  1600. }
  1601. if (r.from === 2) {
  1602. delete r.autoLoadNum;
  1603. delete r.history;
  1604. delete r.sideController;
  1605. if (r.pageBar === 0) delete r.pageBar;
  1606. }
  1607. if (!r.smart) {
  1608. self.insert = null;
  1609. self.curSiteRule = r;
  1610. self.preSiteRule = r;
  1611. if (r.enable !== 0) debug(r, 'Match');
  1612. } else if (!self.curSiteRule || !self.curSiteRule.smart) self.curSiteRule = r;
  1613. callback();
  1614. }
  1615.  
  1616. function checkRule(r) {
  1617. if (r.from === 1 && r.url.length <= 13) return false;
  1618. let urlReg = new RegExp(r.url, "i");
  1619. if (urlReg.test(href)) {
  1620. if (!self.ruleMatchPre(r)) return false;
  1621. if (r.url.length > 15 && r.from !== 1) {
  1622. self.possibleRule = r;
  1623. }
  1624. if (r.waitElement) {
  1625. let waitTime = 500;
  1626. let checkReady = () => {
  1627. setTimeout(() => {
  1628. if (!self.waitElement(document, r.waitElement) || !self.ruleMatchReady(r)) {
  1629. checkReady();
  1630. } else {
  1631. setRule(r);
  1632. }
  1633. }, parseInt(waitTime));
  1634. };
  1635. checkReady();
  1636. debug(r, 'Wait for');
  1637. return true;
  1638. } else if (r.wait) {
  1639. let waitTime = 500, checkEval, maxCheckTimes = 50;
  1640. if (isNaN(r.wait)) {
  1641. try {
  1642. checkEval = (typeof r.wait === 'function') ? r.wait : AsyncFunction("doc",'"use strict";' + r.wait);
  1643. } catch(e) {
  1644. debug(e, 'Error when checkeval');
  1645. }
  1646. } else {
  1647. waitTime = r.wait;
  1648. }
  1649. let checkReady = () => {
  1650. if (maxCheckTimes-- <= 0) {
  1651. debug("Wait for rule ready but failed");
  1652. setRule(r);
  1653. return;
  1654. }
  1655. setTimeout(async() => {
  1656. if (!self.ruleMatchReady(r) || (checkEval && !await checkEval(document))) {
  1657. checkReady();
  1658. } else {
  1659. setRule(r);
  1660. }
  1661. }, parseInt(waitTime));
  1662. };
  1663. checkReady();
  1664. debug(r, 'Wait for');
  1665. return true;
  1666. }
  1667. if (r.pinUrl) {
  1668. setRule(r);
  1669. return true;
  1670. }
  1671. if (!self.ruleMatchReady(r)) {
  1672. return false;
  1673. }
  1674. setRule(r);
  1675. return true;
  1676. }
  1677. return false;
  1678. }
  1679.  
  1680. function checkHpRules() {
  1681. for (let i in self.hpRules) {
  1682. let rule = self.hpRules[i];
  1683. if (!rule || !rule.url || rule.smart) continue;
  1684. if (checkRule(rule)) return true;
  1685. }
  1686. return false;
  1687. }
  1688.  
  1689. function checkCustomRules() {
  1690. for (let i in self.customRules) {
  1691. let rule = self.customRules[i];
  1692. if (!rule || !rule.url) continue;
  1693. if (checkRule(rule)) return true;
  1694. }
  1695. return false;
  1696. }
  1697.  
  1698. if (rulesData.customFirst) {
  1699. if (checkCustomRules()) return;
  1700. await sleep(1);
  1701. if (checkHpRules()) return;
  1702. } else {
  1703. if (checkHpRules()) return;
  1704. await sleep(1);
  1705. if (checkCustomRules()) return;
  1706. }
  1707. await sleep(1);
  1708.  
  1709. for (let i in this.smartRules) {
  1710. let rule = this.smartRules[i];
  1711. if (!rule || !rule.url || !rule.smart) continue;
  1712. if (href == rule.url) {
  1713. setRule(rule);
  1714. return;
  1715. }
  1716. }
  1717. let r = 0;
  1718. async function searchByTime() {
  1719. while (document.hidden) {
  1720. await sleep(1000);
  1721. }
  1722. setTimeout(() => {
  1723. let end = r + 20;
  1724. end = end > self.rules.length ? self.rules.length : end;
  1725. for (; r < end; r++) {
  1726. let rule = self.rules[r];
  1727. if (checkRule(rule)) return;
  1728. }
  1729. if (end >= self.rules.length) {
  1730. setRule({url: href, smart: true});
  1731. return;
  1732. } else {
  1733. searchByTime();
  1734. }
  1735. }, 1);
  1736. }
  1737. searchByTime();
  1738. }
  1739.  
  1740. addToHpRules(instead) {
  1741. try {
  1742. if (this.curSiteRule.isScript) return;
  1743. if (!this.hpRules) this.hpRules = [];
  1744. let url = this.curSiteRule && this.curSiteRule.url, self = this;
  1745. let href = location.href.slice(0, 500);
  1746. let matchedRules = this.hpRules.filter(rule => rule != self.curSiteRule && new RegExp(rule.url, "i").test(href) && self.ruleMatch(rule));
  1747. if (url) matchedRules.unshift(this.curSiteRule);
  1748. matchedRules.sort((a, b) => {
  1749. if ((a.include || a.exclude) && (!b.include && !b.exclude)) {
  1750. return -1;
  1751. } else if ((b.include || b.exclude) && (!a.include && !a.exclude)) {
  1752. return 1;
  1753. } else {
  1754. if ((a.nextLink || a.pageElement) && (!b.nextLink && !b.pageElement)) {
  1755. return -1;
  1756. } else if ((b.nextLink || b.pageElement) && (!a.nextLink && !a.pageElement)) {
  1757. return 1;
  1758. } else {
  1759. if (a.url.length > b.url.length) {
  1760. return -1;
  1761. } else if (a.url.length < b.url.length) {
  1762. return 1;
  1763. } else {
  1764. return 0;
  1765. }
  1766. }
  1767. }
  1768. });
  1769. this.hpRules = this.hpRules.filter(item => {
  1770. return item && !matchedRules.find(rule => item.url == rule.url && JSON.stringify(item) == JSON.stringify(rule));
  1771. });
  1772. if (instead) {
  1773. if (url) {
  1774. this.hpRules.unshift(this.curSiteRule);
  1775. matchedRules = [];
  1776. }
  1777. } else {
  1778. this.hpRules = matchedRules.concat(this.hpRules);
  1779. }
  1780. if (matchedRules && matchedRules.length) this.curSiteRule = matchedRules[0];
  1781. if (this.hpRules.length > 30) {
  1782. this.hpRules.pop();
  1783. }
  1784. if (!rulesData.sort) rulesData.sort = [1];
  1785. this.hpRules.sort((a, b) => {
  1786. let aSort = -1, bSort = -1;
  1787. for (let s = 0; s < rulesData.sort.length; s++) {
  1788. if (a.from == rulesData.sort[s]) aSort = s;
  1789. if (b.from == rulesData.sort[s]) bSort = s;
  1790. if (aSort > -1 && bSort > -1) break;
  1791. }
  1792. return aSort - bSort;
  1793. });
  1794. storage.setItem("hpRules", this.hpRules);
  1795. } catch (e) {
  1796. debug(e);
  1797. }
  1798. }
  1799.  
  1800. replaceElement(doc) {
  1801. if (!doc || doc === document) return;
  1802. let replaceElementSel = this.curSiteRule.replaceElement;
  1803. if (replaceElementSel) {
  1804. if (!Array.isArray(replaceElementSel)) {
  1805. replaceElementSel = [replaceElementSel];
  1806. }
  1807. replaceElementSel.forEach(sel => {
  1808. let pageEles = getAllElements(sel, document);
  1809. let replaceEles = getAllElements(sel, doc);
  1810. for (let i = 0; i < pageEles.length; i++) {
  1811. let replaceEle = replaceEles[i];
  1812. let pageEle = pageEles[i];
  1813. if (replaceEle) {
  1814. pageEle.parentNode.replaceChild(replaceEle.cloneNode(true), pageEle);
  1815. } else break;
  1816. }
  1817. });
  1818. }
  1819. }
  1820.  
  1821. refreshByClick() {
  1822. let refreshByClickSel = this.curSiteRule.refreshByClick;
  1823. if (refreshByClickSel) {
  1824. let self = this;
  1825. if (!this.refreshByClickHandler) {
  1826. this.refreshByClickHandler = e => {
  1827. if (!self.refreshing) {
  1828. self.refreshing = true;
  1829. setTimeout(() => {
  1830. self.refreshing = false;
  1831. let checkEles = getAllElements(refreshByClickSel, document);
  1832. for (let i = 0; i < checkEles.length; i++) {
  1833. let curEle = checkEles[i];
  1834. if (curEle === e.target || curEle.contains(e.target)) {
  1835. ruleParser.urlChanged();
  1836. isPause = true;
  1837. if (!ruleParser.nextLinkHref) isLoading = false;
  1838. break;
  1839. }
  1840. }
  1841. }, 300);
  1842. }
  1843. }
  1844. }
  1845. document.removeEventListener("click", this.refreshByClickHandler);
  1846. document.addEventListener("click", this.refreshByClickHandler);
  1847. }
  1848. }
  1849.  
  1850. getValidSize(ele, win) {
  1851. if (!win) return {h: 0, w: 0};
  1852. let eleStyle = win.getComputedStyle(ele);
  1853. if (!ele.offsetParent && (eleStyle.position !== "fixed" || eleStyle.opacity === 0)) {
  1854. return {h: 0, w: 0};
  1855. }
  1856. if (ele.children && ele.children.length === 1 && (ele.offsetWidth === 0 || ele.offsetHeight === 0)) {
  1857. ele = ele.children[0];
  1858. }
  1859. let h = ele.scrollHeight, w;
  1860. if (eleStyle.overflow === "hidden") {
  1861. h = ele.offsetHeight;
  1862. w = ele.offsetWidth;
  1863. } else w = parseInt(ele.offsetWidth || ele.scrollWidth);
  1864. if (h === 0 && ele.parentNode && ele.parentNode.children.length === 1) {
  1865. h = ele.parentNode.scrollHeight;
  1866. }
  1867. while (h === 0 && ele.children && ele.children.length === 1) {
  1868. ele = ele.children[0];
  1869. h = ele.scrollHeight;
  1870. }
  1871. if (h === 0 && ele.children && ele.children.length) {
  1872. let maxChildSize = {h: 0}, self = this;
  1873. [].forEach.call(ele.children, el => {
  1874. let childSize = self.getValidSize(el, win);
  1875. if (childSize.h > maxChildSize.h) maxChildSize = childSize;
  1876. });
  1877. if (maxChildSize.h !== 0) return maxChildSize;
  1878. }
  1879. const maxNum = 2147483647;
  1880. let moreChild = ele.children[0], minOffsetTop = maxNum;
  1881. while (moreChild) {
  1882. if ((moreChild.offsetParent === ele || moreChild.offsetParent === ele.offsetParent)) {
  1883. let curOffsetTop = moreChild.offsetParent === ele.offsetParent ? moreChild.offsetTop - ele.offsetTop : moreChild.offsetTop;
  1884. if (curOffsetTop < minOffsetTop) {
  1885. minOffsetTop = curOffsetTop;
  1886. }
  1887. }
  1888. moreChild = moreChild.nextElementSibling;
  1889. }
  1890. if (h && minOffsetTop !== maxNum && minOffsetTop > 0) {
  1891. h -= minOffsetTop;
  1892. }
  1893. return {h: h, w: w};
  1894. }
  1895.  
  1896. checkTargetChildren(ele, curWin, articleNum, curHeight) {
  1897. let pf = false;
  1898. if (ele.parentNode) {
  1899. let paStyle = curWin.getComputedStyle(ele.parentNode);
  1900. let paDisplay = paStyle.display;
  1901. let paOverflow = paStyle.overflow;
  1902. pf = (paDisplay.indexOf('flex') !== -1 && paStyle.flexDirection.indexOf("row") === 0 && paStyle.flexWrap !== "wrap") || compareNodeName(ele.parentNode, ["ul"]) || paDisplay.indexOf('grid') !== -1 || paOverflow === "hidden";
  1903. }
  1904. let curStyle = curWin.getComputedStyle(ele);
  1905. if (ele.children.length > 1) {
  1906. if (articleNum > 1) {
  1907. return ">article";
  1908. } else {
  1909. let hasText = false;
  1910. for (let i in ele.childNodes) {
  1911. let child = ele.childNodes[i];
  1912. if (child.nodeType === 3 && child.nodeValue.trim() !== '') {
  1913. hasText = true;
  1914. break;
  1915. }
  1916. }
  1917. let gridArea = curStyle.gridArea;
  1918. if (gridArea && gridArea !== "auto" && gridArea !== "auto / auto / auto / auto") {
  1919. return ">*";
  1920. } else {
  1921. let middleChild = ele.children[parseInt(ele.children.length / 2)];
  1922. if ((curStyle.display === 'flex' && curStyle.flexDirection.indexOf("row") === 0 && curStyle.flexWrap !== "wrap") || (curStyle.float === "none" && curStyle.display !== "table-cell" && (rulesData.opacity !== 0 || hasText) && !pf)) {
  1923. return "";
  1924. } else if ((middleChild.style && middleChild.style.position === "absolute" && middleChild.style.left && middleChild.style.top) || compareNodeName(ele, ["ul"]) || curHeight === 0) {
  1925. return "";
  1926. } else {
  1927. return ">*";
  1928. }
  1929. }
  1930. }
  1931. } else if (pf || curStyle.position === "absolute") {
  1932. return ">*";
  1933. }
  1934. return "";
  1935. }
  1936.  
  1937. getPageElement(doc, curWin, dontFind) {
  1938. if (doc === document && this.docElementValid()) {
  1939. return this.docPageElement;
  1940. }
  1941. let pageElement = null;
  1942. let self = this;
  1943. let body = getBody(doc);
  1944. if (this.curSiteRule.pageElement) {
  1945. let pageElementSel = this.curSiteRule.pageElement;
  1946. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  1947. pageElementSel = pageElementSel[nextIndex < pageElementSel.length ? nextIndex : 0];
  1948. }
  1949. pageElement = getAllElements(pageElementSel, doc);
  1950. if (this.curSiteRule.smart && (!pageElement || pageElement.length === 0)) {
  1951. const childSelMatch = />\s*\*$/;
  1952. const targetChild = childSelMatch.test(pageElementSel);
  1953. if (targetChild) pageElementSel = pageElementSel.replace(childSelMatch, "");
  1954. let pageElementSelSplit = pageElementSel.split(">");
  1955. while(pageElementSelSplit && pageElementSelSplit.length > 5) {
  1956. pageElementSelSplit.shift();
  1957. let tempSel = pageElementSelSplit.join(">");
  1958. pageElement = getAllElements(tempSel, doc);
  1959. if (pageElement && pageElement.length === 1) {
  1960. if (targetChild) {
  1961. pageElement = pageElement.children;
  1962. }
  1963. this.curSiteRule.pageElement = tempSel + (targetChild ? ">*" : "");
  1964. break;
  1965. }
  1966. }
  1967. if (!pageElement || pageElement.length === 0) {
  1968. pageElementSel = pageElementSel.replace(/:nth-of-type\(\d+\)/g, "");
  1969. pageElement = getAllElements(pageElementSel, doc);
  1970. if (pageElement && pageElement.length === 1) {
  1971. if (targetChild) {
  1972. pageElement = pageElement.children;
  1973. }
  1974. this.curSiteRule.pageElement = pageElementSel + (targetChild ? ">*" : "");
  1975. }
  1976. }
  1977. }
  1978. if (this.curSiteRule.smart && pageElement && pageElement.length && curWin && curWin !== _unsafeWindow) {
  1979. if (pageElement.length === 1 && !pageElement[0].src && pageElement[0].innerHTML.trim() === "") {
  1980. pageElement = null;
  1981. } else {
  1982. let parent = pageElement[0].parentNode;
  1983. let loading = parent.querySelector('[class*=loading]');
  1984. if (loading && loading.offsetParent && loading.offsetHeight > parent.offsetHeight>>2) {
  1985. pageElement = null;
  1986. }
  1987. }
  1988. }
  1989. }
  1990. if (pageElement && pageElement.length === 1 && pageElement[0].style.display === 'none') {
  1991. pageElement = [body];
  1992. }
  1993. if (this.curSiteRule.smart && pageElement && pageElement.length > 0 && compareNodeName(pageElement[0], ["tr"])) {
  1994. let mainTr = this.insert.parentNode.querySelectorAll('tr'), mainTdNum = 0, newTdNum = 0;
  1995. mainTr = mainTr[mainTr.length - 1];
  1996. [].forEach.call(mainTr.children, el => {
  1997. if (compareNodeName(el, ["td", "th"])) {
  1998. mainTdNum += el.colSpan || 1;
  1999. }
  2000. });
  2001. [].forEach.call(pageElement[0].children, el => {
  2002. if (compareNodeName(el, ["td", "th"])) {
  2003. newTdNum += el.colSpan || 1;
  2004. }
  2005. });
  2006. if (mainTdNum !== newTdNum) {
  2007. this.curSiteRule.pageElement = this.curSiteRule.pageElement.replace(/> *table.*/, ">table");
  2008. this.getInsert(true);
  2009. return this.getPageElement(doc, curWin, dontFind);
  2010. }
  2011. }
  2012. if ((this.curSiteRule.smart || !this.curSiteRule.pageElement) && (!pageElement || pageElement.length == 0) && curWin && !dontFind) {
  2013. if (!body) return null;
  2014. let bodyHeight = parseInt(body.offsetHeight || body.scrollHeight);
  2015. let curHeight = bodyHeight, curWidth = 0;
  2016. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  2017. let windowWidth = window.innerWidth || document.documentElement.clientWidth;
  2018. let needCheckNext = (doc == document && this.initNext), nextLeftPos = 0;
  2019. if (needCheckNext && this.initNext.getBoundingClientRect) {
  2020. nextLeftPos = this.initNext.getBoundingClientRect().left;
  2021. }
  2022. function checkElement(ele) {
  2023. if (compareNodeName(ele, ["pre", "code"])) {
  2024. self.curSiteRule.pageElement = geneSelector(ele.parentNode);
  2025. debug(self.curSiteRule.pageElement, 'Page element');
  2026. return [ele.parentNode];
  2027. }
  2028. if (ele.children && ele.children.length === 1) {
  2029. let hasText = false;
  2030. for (let i in ele.childNodes) {
  2031. let child = ele.childNodes[i];
  2032. if (child.nodeType === 3 && child.nodeValue.trim() !== '') {
  2033. hasText = true;
  2034. break;
  2035. }
  2036. }
  2037. if (!hasText) {
  2038. ele = ele.children[0];
  2039. let validSize = self.getValidSize(ele, curWin);
  2040. curHeight = validSize.h;
  2041. curWidth = validSize.w;
  2042. }
  2043. }
  2044. if (compareNodeName(ele, ["picture"]) || !ele.innerText || ele.innerText.trim() === '') {
  2045. self.curSiteRule.pageElement = geneSelector(ele.parentNode) + ">" + ele.nodeName.toLowerCase();
  2046. debug(self.curSiteRule.pageElement, 'Page element');
  2047. let eles = [];
  2048. for (let i = 0; i < ele.parentNode.children.length; i++) {
  2049. let curNode = ele.parentNode.children[i];
  2050. if (curNode.nodeName === ele.nodeName && curNode.id === ele.id && curNode.className === ele.className) {
  2051. eles.push(curNode);
  2052. }
  2053. }
  2054. return eles;
  2055. }
  2056. if (compareNodeName(ele, ["form"]) && ele.parentNode !== getBody(document)) {
  2057. self.curSiteRule.pageElement = geneSelector(ele) + ">*";
  2058. debug(self.curSiteRule.pageElement, 'Page element');
  2059. return ele.children;
  2060. }
  2061. if (ele.children.length === 0 && !self.curSiteRule.pageElement) {
  2062. if (compareNodeName(ele.parentNode, ["p"])) ele = ele.parentNode;
  2063. self.curSiteRule.pageElement = geneSelector(ele.parentNode) + ">" + ele.nodeName.toLowerCase();
  2064. debug(self.curSiteRule.pageElement, 'Page element');
  2065. return getAllElements(self.curSiteRule.pageElement, doc);
  2066. }
  2067. let i, minHeight = curHeight * 0.52, curMaxEle = null, curMaxArea = 0, minWidth = Math.min(curWidth * 0.38, 500);
  2068. let isHori, preOffsetTop = -1;
  2069. let articleNum = 0;
  2070. for (i = 0; i < ele.children.length; i++) {
  2071. let curNode = ele.children[i];
  2072. if (ele !== body && /^H\d$/i.test(curNode.nodeName) && curNode.offsetParent) {
  2073. curMaxEle = null;
  2074. break;
  2075. }
  2076. if (compareNodeName(curNode, ["canvas", "nav"])) continue;
  2077. let curStyle = curWin.getComputedStyle(curNode);
  2078. if (!curNode.offsetParent && (curStyle.position !== "fixed" || curStyle.opacity === 0)) {
  2079. continue;
  2080. }
  2081. if (!compareNodeName(curNode, ["img"]) && curNode.querySelector('img') === null && /^\s*$/.test(curNode.innerText)) continue;
  2082. if (needCheckNext && !curNode.contains(self.initNext) && getElementTop(curNode) > windowHeight) {
  2083. continue;
  2084. }
  2085. if (compareNodeName(curNode, ["article"])) articleNum++;
  2086. let validSize = self.getValidSize(curNode, curWin);
  2087. let h = validSize.h;
  2088. let w = validSize.w;
  2089. if (isNaN(h) || isNaN(w) || !h || !w) continue;
  2090. isHori = Math.abs(preOffsetTop - curNode.offsetTop) <= 20 ? true : (preOffsetTop === -1 && curNode.nextElementSibling && curNode.nextElementSibling.offsetTop === curNode.offsetTop);
  2091. if (isHori && h <= 50) continue;
  2092. /*if (isHori && nextLeftPos && curMaxEle && curWidth > 500 && curHeight > 500) {
  2093. let curRect = curNode.getBoundingClientRect();
  2094. if (curRect.left > windowWidth>>2 && curRect.left <= nextLeftPos && curRect.right > nextLeftPos) {
  2095. continue;
  2096. }
  2097. }*/
  2098. let a = h * w, moreChild = curNode.children[0];
  2099. while (moreChild) {
  2100. let validSize = self.getValidSize(moreChild, curWin);
  2101. let ch = validSize.h;
  2102. let cw = validSize.w;
  2103. if (h < ch) {
  2104. h = ch;
  2105. }
  2106. if (moreChild.innerText !== "" && ch && cw) {
  2107. a += ch * cw;
  2108. }
  2109. moreChild = moreChild.nextElementSibling;
  2110. }
  2111. let isMax = false;
  2112. if (isHori) {
  2113. if (curMaxEle) {
  2114. if (w > curWidth && (windowWidth>>1) > curWidth) {
  2115. isMax = true;
  2116. } else if (w + 300 > curWidth && a > curMaxArea) {
  2117. isMax = true;
  2118. }
  2119. }
  2120. } else {
  2121. if (curMaxEle && curMaxEle.offsetParent === curNode.offsetParent && curMaxEle.offsetTop === curNode.offsetTop) {
  2122. if (curMaxArea * 2 > a) continue;
  2123. }
  2124. isMax = curMaxArea < a;
  2125. }
  2126. if (curMaxEle === null || isMax) {
  2127. if (isHori) {
  2128. if (w < minWidth) {
  2129. continue;
  2130. }
  2131. }
  2132. if (h < minHeight) {
  2133. if (!needCheckNext || h < (windowHeight>>1)) {
  2134. continue;
  2135. }
  2136. if (!ele.contains(self.initNext)) {
  2137. continue;
  2138. } else if (!curNode.contains(self.initNext) && h < curHeight >> 1) {
  2139. continue;
  2140. }
  2141. }
  2142. curHeight = h;
  2143. curMaxArea = a;
  2144. curWidth = w;
  2145. curMaxEle = curNode;
  2146. preOffsetTop = curNode.offsetTop;
  2147. }
  2148. }
  2149. let curHeightPercent = curHeight / bodyHeight;
  2150. if (curMaxEle && curHeightPercent <= 0.18) {
  2151. let article;
  2152. for (let i = 0; i < mainSel.length; i++) {
  2153. article = doc.querySelectorAll(mainSel[i]);
  2154. if (article && article.length === 1) break;
  2155. }
  2156. if (article && article.length === 1) {
  2157. article = article[0];
  2158. let childrenEnd = self.checkTargetChildren(article, curWin, articleNum, curHeight);
  2159. self.curSiteRule.pageElement = article.nodeName.toLowerCase() + (article.id ? "#" + article.id : "") + (article.className ? "." + article.className.replace(/ /g, ".") : "") + childrenEnd;
  2160. debug(self.curSiteRule.pageElement, 'Page element');
  2161. return childrenEnd ? article.children : [article];
  2162. }
  2163. curMaxEle = null;
  2164. }
  2165. if (curMaxEle && (!compareNodeName(curMaxEle, ["ul"]) || curHeightPercent > 0.8)) {
  2166. let sameClassNum = 0, hasDifferent = false;
  2167. if (curMaxEle.className) {
  2168. for(i = 0; i < ele.children.length; i++) {
  2169. let curNode = ele.children[i];
  2170. if (curMaxEle !== curNode && curNode.style.display !== 'none' && curMaxEle.className === curNode.className && curMaxEle.nodeName === curNode.nodeName){
  2171. sameClassNum++;
  2172. } else if (curMaxEle.className !== curNode.className) {
  2173. hasDifferent = true;
  2174. }
  2175. }
  2176. }
  2177. if (sameClassNum < 2 || (sameClassNum < 5 && hasDifferent)) {
  2178. return checkElement(curMaxEle);
  2179. }
  2180. }
  2181. if (ele.nodeName === "APP-ROOT") {
  2182. isPause = true;
  2183. debug(ele, "Angular root");
  2184. return null;
  2185. }
  2186. while (compareNodeName(ele, ["p", "br", "td"])) {
  2187. ele = ele.parentNode;
  2188. }
  2189. if (compareNodeName(ele, ["tbody"])) {
  2190. self.curSiteRule.pageElement = geneSelector(ele) + ">*";
  2191. if (ele.children.length > 0 && ele.children[0].querySelector("th")) {
  2192. self.curSiteRule.pageElement += ":not(:first-child)";
  2193. }
  2194. debug(self.curSiteRule.pageElement, 'Page element');
  2195. return ele.children;
  2196. }
  2197. let imgs = ele.querySelectorAll('img');
  2198. if (imgs.length === 1) {
  2199. let img = imgs[0];
  2200. if (img.offsetWidth > ele.offsetWidth / 3 * 2 && img.offsetHeight > ele.offsetHeight / 2) {
  2201. ele = img;
  2202. }
  2203. }
  2204. let childrenEnd = self.checkTargetChildren(ele, curWin, articleNum, curHeight);
  2205. if (childrenEnd) {
  2206. self.curSiteRule.pageElement = geneSelector(ele) + childrenEnd;
  2207. ele = ele.children;
  2208. } else {
  2209. if (ele.scrollHeight === 0 && ele.parentNode.children.length === 1) {
  2210. ele = ele.parentNode;
  2211. }
  2212. self.curSiteRule.pageElement = geneSelector(ele);
  2213. ele = [ele];
  2214. }
  2215. debug(self.curSiteRule.pageElement, 'Page element');
  2216. return ele;
  2217. }
  2218. pageElement = checkElement(body);
  2219. if (doc === document && pageElement && pageElement.length > 0 && self.initNext) {
  2220. let posEle = pageElement[pageElement.length - 1];
  2221. while (posEle && !posEle.offsetParent) {
  2222. posEle = posEle.previousElementSibling || posEle.parentNode;
  2223. }
  2224. if (posEle && posEle.scrollHeight === 0 && posEle.lastElementChild) posEle = posEle.lastElementChild;
  2225. let lastBottom = forceState !== 2 && forceState !== 3 && posEle && getElementBottom(posEle);
  2226. if (lastBottom && getElementTop(self.initNext) - lastBottom > 1000) {
  2227. debug("Stop as too long between next & page element, try to enable Force-Join mode.");
  2228. isPause = true;
  2229. pageElement = [];
  2230. sideController.remove();
  2231. } else {
  2232. if (pageElement.length === 1 && compareNodeName(pageElement[0], ["img"])) {
  2233. self.curSiteRule.pageBar = 0;
  2234. }
  2235. }
  2236. }
  2237. //if(pageElement)this.saveCurSiteRule();
  2238. }
  2239.  
  2240. if (doc !== document) {
  2241. this.setPageElementCss(pageElement);
  2242. this.lazyImgAction(pageElement, doc);
  2243. this.filterEles(doc, pageElement);
  2244. } else if (!this.docPageElement) {
  2245. this.setPageElementCss(pageElement, true);
  2246. this.docPageElement = pageElement;
  2247. this.filterEles(doc, pageElement);
  2248. if (this.nextLinkHref) {
  2249. this.openInNewTab(pageElement);
  2250. }
  2251. }
  2252. return pageElement;
  2253. }
  2254.  
  2255. showAddedElements() {
  2256. if (!this.addedElementsIsHide) return;
  2257. if (this.addedElePool && this.addedElePool.length) {
  2258. this.addedElePool.forEach(ele => {
  2259. ele.classList && ele.classList.remove("pagetual-hide");
  2260. });
  2261. }
  2262. this.addedElementsIsHide = false;
  2263. }
  2264.  
  2265. hideAddedElements() {
  2266. if (this.addedElePool && this.addedElePool.length) {
  2267. this.addedElePool.forEach(ele => {
  2268. ele.classList && ele.classList.add("pagetual-hide");
  2269. });
  2270. }
  2271. this.addedElementsIsHide = true;
  2272. }
  2273.  
  2274. toggleAddedElements() {
  2275. if (this.addedElementsIsHide) {
  2276. this.showAddedElements();
  2277. } else {
  2278. this.hideAddedElements();
  2279. }
  2280. }
  2281.  
  2282. changeVisibility() {
  2283. let contentVisibility = this.curSiteRule.contentVisibility || rulesData.contentVisibility;
  2284. if (!contentVisibility) return;
  2285. if (!this.changingVisibility) {
  2286. clearTimeout(this.changeVisibilityTimer);
  2287. this.changeVisibilityTimer = setTimeout(() => {
  2288. this.changingVisibility = true;
  2289. this.changeVisibility();
  2290. }, 300);
  2291. return;
  2292. }
  2293. this.changingVisibility = false;
  2294. if (!this.visibilityItems || !this.visibilityItems.length || this.visibleIndex < 0) return;
  2295. let tempIndex = this.visibleIndex, findVisible = false, lastVisible = 0;
  2296. let viewPortHeight = window.innerHeight || document.documentElement.clientHeight || getBody(document).clientHeight;
  2297. let checkItem = this.visibilityItems[tempIndex];
  2298. while(checkItem) {
  2299. if (checkItem.offsetParent) {
  2300. if (!checkItem.style.containIntrinsicSize) return;
  2301. let clientRect = checkItem.getBoundingClientRect();
  2302. let top = clientRect && clientRect.top;
  2303. let bottom = clientRect && clientRect.bottom;
  2304. if (bottom > 0 && top < viewPortHeight) {
  2305. if (!findVisible) {
  2306. findVisible = true;
  2307. lastVisible = tempIndex;
  2308. }
  2309. checkItem.style.contentVisibility = "visible";
  2310. } else {
  2311. if (top < viewPortHeight && checkItem.style.contentVisibility === "auto") {
  2312. break;
  2313. } else checkItem.style.contentVisibility = "auto";
  2314. }
  2315. }
  2316. if (tempIndex === 0) break;
  2317. tempIndex--;
  2318. checkItem = this.visibilityItems[tempIndex];
  2319. }
  2320. tempIndex = this.visibleIndex + 1;
  2321. if (findVisible) {
  2322. this.visibleIndex = lastVisible;
  2323. }
  2324. checkItem = this.visibilityItems[tempIndex];
  2325. while(checkItem) {
  2326. if (checkItem.offsetParent) {
  2327. if (!checkItem.style.containIntrinsicSize) return;
  2328. let clientRect = checkItem.getBoundingClientRect();
  2329. let top = clientRect && clientRect.top;
  2330. let bottom = clientRect && clientRect.bottom;
  2331. if (bottom > 0 && top < viewPortHeight) {
  2332. findVisible = true;
  2333. lastVisible = tempIndex;
  2334. checkItem.style.contentVisibility = "visible";
  2335. } else {
  2336. if (findVisible && checkItem.style.contentVisibility === "auto") {
  2337. break;
  2338. } else checkItem.style.contentVisibility = "auto";
  2339. }
  2340. }
  2341. if (tempIndex === this.visibilityItems.length - 1) break;
  2342. tempIndex++;
  2343. checkItem = this.visibilityItems[tempIndex];
  2344. }
  2345. if (findVisible) {
  2346. this.visibleIndex = lastVisible;
  2347. }
  2348. }
  2349.  
  2350. setPageElementCss(pageElement, init) {
  2351. let self = this;
  2352. if (pageElement && pageElement.length > 0) {
  2353. let pageElementCss = this.curSiteRule.pageElementCss || rulesData.pageElementCss;
  2354. if (!pageElementCss && init && !this.nextLinkHref) return;
  2355. let contentVisibility = this.curSiteRule.contentVisibility || rulesData.contentVisibility;
  2356. if (!contentVisibility && !pageElementCss) return;
  2357. [].forEach.call(pageElement, (ele, i) => {
  2358. if (!compareNodeName(ele, ["link", "meta", "style", "script"])) {
  2359. if (pageElementCss) {
  2360. if (pageElementCss !== '0' && !ele.dataset.pagetualPageElement) {
  2361. ele.style.cssText = (ele.style.cssText || '') + pageElementCss;
  2362. ele.dataset.pagetualPageElement = 1;
  2363. }
  2364. }
  2365. if (contentVisibility) {
  2366. ele.style.containIntrinsicSize = `auto ${ele.offsetHeight || self.preVisibleHeight || 100}px`;
  2367. if (ele.style.containIntrinsicSize) {
  2368. if (ele.offsetHeight) self.preVisibleHeight = ele.offsetHeight;
  2369. if (init) {
  2370. ele.style.contentVisibility = "visible";
  2371. self.visibilityItems.push(ele);
  2372. self.visibleIndex++;
  2373. } else {
  2374. ele.style.contentVisibility = emuIframe ? "visible" : "auto";
  2375. }
  2376. }
  2377. }
  2378. }
  2379. });
  2380. }
  2381. }
  2382.  
  2383. clearAddedElements() {
  2384. if (this.addedElePool && this.addedElePool.length) {
  2385. this.addedElePool.forEach(ele => {
  2386. if (ele.parentNode) ele.parentNode.removeChild(ele);
  2387. });
  2388. }
  2389. this.addedElePool = [];
  2390. sideController.remove();
  2391. }
  2392.  
  2393. linkHasHref(link) {
  2394. return link.href && link.href.replace && !this.hrefIsJs(link.href);
  2395. }
  2396.  
  2397. hrefIsJs(href) {
  2398. return /^(javascript|#|$)/.test(href.trim().replace("#p{", "").replace(location.href, ""));
  2399. }
  2400.  
  2401. async querySelectorList(source, list, defaultView) {
  2402. for (let i = 0; i < list.length; i++) {
  2403. await sleep(1);
  2404. let sel = list[i];
  2405. let result = getAllElements(sel, source);
  2406. if (result.length > 0) {
  2407. if (defaultView) {
  2408. for (let i = result.length - 1; i >= 0; i--) {
  2409. let ele = result[i];
  2410. if (isVisible(ele, defaultView)) return ele;
  2411. }
  2412. }
  2413. return result[result.length - 1];
  2414. }
  2415. }
  2416. return null;
  2417. }
  2418.  
  2419. verifyElement(ele) {
  2420. let verifyHandler = e => {
  2421. if (e.nodeType == 9) return true;
  2422. if (e.style.display === "none" || e.getAttribute("aria-disabled") === "true") {
  2423. return false;
  2424. }
  2425. if (e.className) {
  2426. if (/slick|slide|gallery|disabled\s*$/i.test(e.className)) {
  2427. return false;
  2428. } else if (e.classList) {
  2429. if (e.classList.contains('disabled') || e.classList.contains('active')) {
  2430. return false;
  2431. }
  2432. }
  2433. }
  2434. let ariaLabel = e.getAttribute("aria-label");
  2435. if (ariaLabel && /slick|slide|gallery/i.test(ariaLabel)) return false;
  2436. return true;
  2437. };
  2438. if (!ele) return false;
  2439. let i = 0;
  2440. while (ele && i++ < 6) {
  2441. if (!verifyHandler(ele)) return false;
  2442. ele = ele.parentNode;
  2443. }
  2444. return true;
  2445. }
  2446.  
  2447. async getPage(doc, exist) {
  2448. if (document.documentElement.className.indexOf && document.documentElement.className.indexOf('discourse') !== -1) return {};
  2449. let body = getBody(doc);
  2450. let canSave = false;//發現頁碼選擇器在其他頁對不上,還是別保存了
  2451. let url = this.curUrl.slice(0, 250).replace("index.php?", "?");
  2452. let _url = url.replace(/\.s?html?$/i, "").toLowerCase();
  2453. let pageNum = 1, preStr = "", afterStr = "";
  2454. let pageTwoReg = /^[\/\?&]?[_-]?(p|page)?=?\/?2(\/[^\/]*$|\?|&|$)/i;
  2455. let pageMatch1 = url.match(/(.*[\?&]p(?:age)?=)(\d+)($|[#&].*)/i);
  2456. let doubtTextReg = /^\s*(»|>>)\s*$/;
  2457. if (pageMatch1) {
  2458. preStr = pageMatch1[1];
  2459. pageNum = parseInt(pageMatch1[2]);
  2460. afterStr = pageMatch1[3];
  2461. } else {
  2462. let pageMatch2 = url.match(/(.*[a-z\/\-_](?:p|page)?\/?)(\d+)(\.s?html?$|\/?$)/i);
  2463. if (pageMatch2) {
  2464. preStr = pageMatch2[1];
  2465. pageNum = parseInt(pageMatch2[2]);
  2466. afterStr = pageMatch2[3];
  2467. if (/^\/?$/.test(afterStr) && !/(p(age)?|_|\-|\/)$/.test(preStr)) {
  2468. preStr = "";
  2469. afterStr = "";
  2470. }
  2471. }
  2472. }
  2473. if (pageNum > 999) {
  2474. pageNum = 1;
  2475. preStr = "";
  2476. afterStr = "";
  2477. }
  2478. let curPage = doc, i, cur, jsNext;
  2479. let next1, next2, next3, next4, nextJs1, nextJs2;
  2480. let selectorList = [
  2481. ".page-next>a",
  2482. "a.next_page",
  2483. "#next_page",
  2484. ".curPage+a",
  2485. ".nextPage",
  2486. ".pagination-next>a",
  2487. "a[data-pagination=next]",
  2488. ".pageButtonsCurrent+a",
  2489. "a[class*=nextpage]",
  2490. "li.page-current+li>a",
  2491. "[class^=pag] a[rel=next]",
  2492. "[class^=Pag] [aria-label=next]",
  2493. "[aria-label='Next Page']",
  2494. "[aria-label='Next page']",
  2495. "[aria-label='next page']",
  2496. ".pagination-nav__item--next>a",
  2497. "a.pageright",
  2498. ".page-numbers.current+a",
  2499. "a.page-numbers.next",
  2500. "body [class*=pagination] li.active+span+li>a",
  2501. "body [class*=pagination] li.active+li>a",
  2502. "body [class^=pag] .current+a",
  2503. ".page_current+a",
  2504. "input[value='next']",
  2505. "input[value='Next page']",
  2506. "input[value='下一页']",
  2507. "input[value='下一頁']",
  2508. "a#pb_next",
  2509. "a#rightFix",
  2510. "a#btnPreGn",
  2511. "a.page-next",
  2512. "a.pages-next",
  2513. "a.page.right",
  2514. ".paging>.active+.item",
  2515. "a#next",
  2516. ".next>a",
  2517. ".next>button",
  2518. "a[alt=next]",
  2519. ".pg_area>em+a",
  2520. "button.next:not([disabled])",
  2521. ".btn_next:not([disabled])",
  2522. ".btn-next:not([disabled])",
  2523. "a#linkNext",
  2524. "a[class*=page__next]",
  2525. "[class*=pager]>a.next",
  2526. "[class*=pagination-next]>a",
  2527. "[class*=pagination-next]>button",
  2528. "[class*=page--current]+li>a",
  2529. "[class*=Pages]>.curr+a",
  2530. ".page>em+a",
  2531. '//button[contains(@class, "Page")][text()="Next"]',
  2532. '//button[contains(@class, "page")][text()="next"]'
  2533. ];
  2534. let next = await this.querySelectorList(body, selectorList, doc.defaultView);
  2535. if (!next) {
  2536. await sleep(1);
  2537. let nexts = body.querySelectorAll("a.next");
  2538. const prevReg = /^\s*([上前首尾]|previous)/i;
  2539. for (i = 0; i < nexts.length; i++) {
  2540. let n = nexts[i];
  2541. if (this.verifyElement(n) && this.linkHasHref(n) && !prevReg.test(n.innerText.trim())) {
  2542. next = n;
  2543. break;
  2544. }
  2545. }
  2546. }
  2547. if (next) {
  2548. let innerText = next.innerText;
  2549. let isJs = !this.linkHasHref(next);
  2550. if (innerText && nextTextReg2.test(innerText.trim())) {
  2551. if (isJs) {
  2552. if (this.verifyElement(next)) {
  2553. nextJs2 = next;
  2554. }
  2555. } else {
  2556. next2 = next;
  2557. }
  2558. next = null;
  2559. } else {
  2560. if (isJs) {
  2561. if (this.verifyElement(next)) {
  2562. jsNext = next;
  2563. }
  2564. next = null;
  2565. }
  2566. }
  2567. }
  2568. if (!next) {
  2569. await sleep(1);
  2570. next = body.querySelector("a.curr+a") ||
  2571. body.querySelector("div.wp-pagenavi>span.current+a,div.page-nav>span.current+a,div.article-paging>span+a") ||
  2572. body.querySelector(".number>ul>li.active+li>a");
  2573. }
  2574. if (!next) {
  2575. await sleep(1);
  2576. let pageDiv = body.querySelector(".pages>ul,.page_no>ul");
  2577. if (pageDiv) {
  2578. cur = pageDiv.querySelector("li>b,li>strong");
  2579. if (cur) next = cur.parentNode.nextElementSibling;
  2580. if (next) next = next.querySelector("a");
  2581. }
  2582. }
  2583. if (!next) {
  2584. await sleep(1);
  2585. next = body.querySelector(".pages>a[href='javascript:;']+a");
  2586. if (next && (next.href === "javascript:;" || next.getAttribute("href") === "#")) next = null;
  2587. }
  2588. if (!next) {
  2589. await sleep(1);
  2590. let pageDiv = body.querySelector(".pagination");
  2591. if (pageDiv) {
  2592. cur = pageDiv.querySelector("[class*=current],.page-selected");
  2593. if (cur) next = cur.parentNode.nextElementSibling;
  2594. if (next) next = next.querySelector("a");
  2595. }
  2596. }
  2597. if (!next) {
  2598. await sleep(1);
  2599. let pageDivs = body.querySelectorAll("[class*=pagination],[class*=Pagination]");
  2600. if (pageDivs && pageDivs.length) {
  2601. for (let i = pageDivs.length - 1; i >= 0; i--) {
  2602. let p = pageDivs[i];
  2603. if (/(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)/i.test(p.title || p.value || '')) {
  2604. next = p.querySelector("a,button,[type='button']") || p;
  2605. break;
  2606. } else if (/^(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)$/i.test((p.innerText || '').trim())) {
  2607. next = p.querySelector("a,button,[type='button']") || p;
  2608. break;
  2609. }
  2610. }
  2611. if (next && !this.linkHasHref(next)) {
  2612. if (!jsNext) jsNext = next;
  2613. next = null;
  2614. }
  2615. }
  2616. }
  2617. if (!next) {
  2618. let isApp = !!body.querySelector("main#app");
  2619. let aTags = body.querySelectorAll("a,button,[type='button']");
  2620. for (i = aTags.length - 1; i >= 0; i--) {
  2621. if (next1) break;
  2622. if (i % 100 === 0) {
  2623. await sleep(1);
  2624. }
  2625. let aTag = aTags[i];
  2626. let title = aTag.title || "";
  2627. let value = aTag.value || "";
  2628. let innerText = aTag.innerText || "";
  2629. if (innerText === "" || (title !== "" && title.length < innerText.length)) {
  2630. innerText = title;
  2631. }
  2632. if (innerText === "" || (value !== "" && value.length < innerText.length)) {
  2633. innerText = value;
  2634. }
  2635. if (innerText !== "") {
  2636. if (innerText === "§") continue;
  2637. innerText = innerText.trim();
  2638. if (innerText.length > 80) continue;
  2639. }
  2640. if (!this.verifyElement(aTag)) continue;
  2641. if (aTag.dataset && aTag.dataset.preview) continue;
  2642. let availableHref = aTag.href && aTag.href.length < 250 && !/^(javascript:|#)/.test(aTag.href);
  2643. if (availableHref && /next\-?(page)?$|\/video\/|\/vod\/play\//i.test(aTag.href)) continue;
  2644. if (compareNodeName(aTag.parentNode, ["blockquote"])) continue;
  2645. if (aTag.previousElementSibling && /\b(play|volume)\b/.test(aTag.previousElementSibling.className)) continue;
  2646. if (aTag.nextElementSibling && /\b(play|volume)\b/.test(aTag.nextElementSibling.className)) continue;
  2647. let isJs = !this.linkHasHref(aTag);
  2648. if (exist && isJs && !aTag.offsetParent) continue;
  2649. if (innerText) {
  2650. innerText = innerText.split(/\n/)[0].replace(/ /g, '');
  2651. if (isJs && /^(»|>>|>|›|→|❯)$/.test(innerText)) continue;
  2652. if (innerText && innerText.length <= 25) {
  2653. if (!next1) {
  2654. if (nextTextReg1.test(innerText)) {
  2655. if (isJs) {
  2656. if (!nextJs1) nextJs1 = aTag;
  2657. } else {
  2658. next1 = aTag;
  2659. }
  2660. }
  2661. }
  2662. if (!next4) {
  2663. if (!next2) {
  2664. if (nextTextReg2.test(innerText) || /nextpage|pager\-older/i.test(aTag.className) || /^(»|>>)$/.test(innerText)) {
  2665. if (isJs) {
  2666. if (!nextJs2) nextJs2 = aTag;
  2667. } else {
  2668. next2 = aTag;
  2669. }
  2670. }
  2671. }
  2672. if (!isApp && !next3 && !isJs) {
  2673. if (/^(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)$/i.test(aTag.textContent) && aTag.parentNode.hasAttribute && !aTag.parentNode.hasAttribute("jsaction")) {
  2674. next3 = aTag;
  2675. }
  2676. }
  2677. }
  2678. }
  2679. }
  2680. if (isJs) continue;
  2681. if (!next4) {
  2682. let prevEle = aTag.previousElementSibling;
  2683. if (prevEle && compareNodeName(prevEle, ["b", "span", "strong"])) {
  2684. if (/^\d+$/.test(aTag.innerText.trim()) && /^\d+$/.test(prevEle.innerText.trim()) && parseInt(aTag.innerText) === parseInt(prevEle.innerText) + 1) {
  2685. next4 = aTag;
  2686. }
  2687. }
  2688. }
  2689. if (urlWillChange) continue;
  2690. if (!next4 && availableHref) {
  2691. let aHref = aTag.href.indexOf("http") === 0 ? aTag.href : this.canonicalUri(aTag.href);
  2692. if (aHref.indexOf(location.hostname) === -1) continue;
  2693. let _aHref = aHref.replace("?&", "?").replace("index.php?", "?");
  2694. if (preStr || afterStr) {
  2695. let _aHrefTrim = _aHref;
  2696. if (preStr) _aHrefTrim = _aHrefTrim.replace(preStr, "");
  2697. if (afterStr) _aHrefTrim = _aHrefTrim.replace(afterStr, "");
  2698. if (_aHrefTrim == pageNum + 1) {
  2699. next4 = aTag;
  2700. }
  2701. } else if (this.curUrl !== aHref) {
  2702. _aHref = _aHref.replace(/\.s?html?$/i, "").toLowerCase();
  2703. if (_aHref.indexOf(_url) !== -1) {
  2704. let pageTwoMatch = _aHref.replace(_url, "").match(pageTwoReg);
  2705. if (pageTwoMatch) {
  2706. afterStr = pageTwoMatch[2];
  2707. next4 = aTag;
  2708. }
  2709. }
  2710. }
  2711. if (next4 && !/page/.test(next4.href)) {
  2712. let curHref = next4.getAttribute("href");
  2713. let curPageReg = new RegExp("(.*)" + (pageNum + 1) + afterStr.replace(/([\.\?])/g, '\\$1'));
  2714. let otherPageHref = curHref.replace(curPageReg, `$1${pageNum}${afterStr}`);
  2715. let otherPageEle = body.querySelector(`a[href='${otherPageHref}']`);
  2716. if (!otherPageEle) {
  2717. otherPageHref = curHref.replace(curPageReg, `$1${pageNum + 2}${afterStr}`);
  2718. otherPageEle = body.querySelector(`a[href='${otherPageHref}']`);
  2719. }
  2720. if (otherPageEle) {
  2721. let parent = otherPageEle.parentNode;
  2722. if (parent && parent.parentNode) {
  2723. parent = parent.parentNode;
  2724. if (parent.parentNode) {
  2725. parent = parent.parentNode;
  2726. }
  2727. }
  2728. if (parent && parent.contains(next4) && !/^\d+$/.test(next4.innerText.trim())) {
  2729. next4 = null;
  2730. }
  2731. }
  2732. }
  2733. }
  2734. }
  2735. if (next2 && doubtTextReg.test(next2.innerText)) {
  2736. next2 = this.verifyNext(next2, doc, false);
  2737. }
  2738. if (nextJs2 && doubtTextReg.test(nextJs2.innerText)) {
  2739. nextJs2 = this.verifyNext(nextJs2, doc, true);
  2740. }
  2741. if (next3) {
  2742. next3 = this.verifyNext(next3, doc, false);
  2743. }
  2744. }
  2745. if (!next) next = next1 || next4 || next3 || next2;
  2746. if (!next && location.pathname + location.search !== "/") {
  2747. next = jsNext || nextJs1 || nextJs2;
  2748. if (next && next.parentNode.className && next.parentNode.className.indexOf && next.parentNode.className.indexOf('tab') !== -1) next = null;
  2749. }
  2750. if (next && next.classList && (next.classList.contains("results-more") || next.classList.contains("no"))) next = null;
  2751. if (next && next.hasAttribute && next.hasAttribute("disabled")) next = null;
  2752. if (next && next.parentNode.href && compareNodeName(next.parentNode, ["a"])) next = next.parentNode;
  2753. return {next:next, canSave:canSave};
  2754. }
  2755.  
  2756. verifyNext(next, doc, isJs) {
  2757. if (!next) return null;
  2758. if (!isJs) {
  2759. let href = next.getAttribute("href");
  2760. if (href && !/\d/.test(next.getAttribute("href"))) {
  2761. return null;
  2762. }
  2763. }
  2764. if (next.previousElementSibling && compareNodeName(next.previousElementSibling, ["br"])) return null;
  2765. let eles = [];
  2766. if (next.innerText && next.innerText.indexOf("\n") === -1) {
  2767. eles = getAllElements(`//${next.nodeName}[text()='${next.innerText}']`, doc);
  2768. }
  2769. if (eles.length >= 2 && eles[0].href !== eles[1].href) {
  2770. next = null;
  2771. } else if (doc === document) {
  2772. let left = getElementLeft(next);
  2773. if (left < 20 || (document.documentElement.scrollWidth > 500 && left < 250)) {
  2774. next = null;
  2775. } else {
  2776. let top = getElementTop(next);
  2777. if (top < 20 || (left < window.innerWidth / 3 && top < window.innerHeight / 3)) {
  2778. next = null;
  2779. } else {
  2780. let bottom = top + next.offsetHeight || 0;
  2781. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  2782. if (scrollH - bottom < 10) next = null;
  2783. }
  2784. }
  2785. }
  2786. return next;
  2787. }
  2788.  
  2789. canonicalUri(src) {
  2790. if (!src) {
  2791. return "";
  2792. }
  2793. if (src.charAt(0) === "#") return this.curUrl + src;
  2794. if (src.charAt(0) === "?") return this.curUrl.replace(/^([^\?#]+).*/, "$1" + src);
  2795. let origin = location.protocol + '//' + location.host;
  2796. let url = this.basePath || origin;
  2797. url = url.replace(/(\?|#).*/, "");
  2798. if (/https?:\/\/[^\/]+$/.test(url)) url = url + '/';
  2799. if (url.indexOf("http") !== 0) url = origin + url;
  2800. var root_page = /^[^\?#]*\//.exec(url)[0],
  2801. root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  2802. absolute_regex = /^\w+\:\/\//;
  2803. this.updateUrl = false;
  2804. while (src.indexOf("../") === 0) {
  2805. src = src.substr(3);
  2806. root_page = root_page.replace(/\/[^\/]+\/$/, "/");
  2807. this.updateUrl = true;
  2808. }
  2809. src = src.replace(/\.\//, "");
  2810. if (/^\/\/\/?/.test(src)) {
  2811. src = location.protocol + src;
  2812. }
  2813. return (absolute_regex.test(src) ? src : ((src.charAt(0) === "/" ? root_domain : root_page) + src));
  2814. }
  2815.  
  2816. getLinkByPage(url, pageNum) {
  2817. if (!url) return null;
  2818. if (this.curSiteRule.pageNum) {
  2819. let result = this.curSiteRule.pageNum;
  2820. let strMatch = result.match(/\{.*?}/);
  2821. if (!strMatch) return null;
  2822. let urlReg = new RegExp("(" + result.replace(strMatch[0], ")\\d+(") + ")", "i");
  2823. let code = strMatch[0].replace(/^{/, "").replace(/}$/, "").replace(/\$p/g, pageNum);
  2824. if (code === pageNum) {
  2825. result = url.replace(urlReg, "$1" + code + "$2");
  2826. } else {
  2827. try {
  2828. code = Function('"use strict";return ' + code)();
  2829. if (code && code % 1 == 0) {
  2830. result = url.replace(urlReg, "$1" + code + "$2");
  2831. } else return null;
  2832. } catch(e) {
  2833. debug(e);
  2834. }
  2835. }
  2836. if (result != url) {
  2837. return result;
  2838. }
  2839. }
  2840. return url.replace(/([&\/\?](p=|page[=\/_-]?))\d+/i, "$1" + pageNum).replace(/([_-])\d+\./i, "$1" + pageNum + ".");
  2841. }
  2842.  
  2843. getPageNumFromUrl(url, defaultPage) {
  2844. if (!url) return defaultPage;
  2845. if (this.curSiteRule.pageNum) {
  2846. let result = this.curSiteRule.pageNum;
  2847. let strMatch = result.match(/\{.*?}/);
  2848. if (!strMatch) return defaultPage;
  2849. let urlReg = new RegExp(".*" + result.replace(strMatch[0], "(\\d+)") + ".*", "i");
  2850. let curShowNum = url.replace(urlReg, "$1");
  2851. if (curShowNum !== url) {
  2852. let code = strMatch[0].replace(/^{/, "").replace(/}$/, "");
  2853. if (code === "$p") {
  2854. return curShowNum;
  2855. } else {
  2856. try {
  2857. let page1 = parseInt(Function('"use strict";return ' + code.replace("$p", "0"))());
  2858. let page2 = parseInt(Function('"use strict";return ' + code.replace("$p", "1"))());
  2859. let numGap = page2 - page1;
  2860. let _page = (parseInt(curShowNum) - page1) / numGap;
  2861. if (_page && _page % 1 === 0) return _page;
  2862. else {
  2863. this.curSiteRule.pageNum = null;
  2864. return defaultPage;
  2865. }
  2866. } catch(e) {
  2867. debug(e);
  2868. }
  2869. }
  2870. } else {
  2871. return defaultPage;
  2872. }
  2873. }
  2874. let pageNum = url.replace(/.*[&\/\?](p=|page[=\/_-]?)(\d+).*/i, "$2");
  2875. return pageNum === url ? defaultPage : (pageNum.length > 4 ? defaultPage : pageNum);
  2876. }
  2877.  
  2878. async getNextLink(doc, exist) {
  2879. let nextLink = null, page, href;
  2880. let getNextLinkByForm = (form, submitBtn, n) => {
  2881. let params = [];
  2882. let formData = new FormData(form);
  2883. if (submitBtn && submitBtn.getAttribute) {
  2884. let btnValue, btnName;
  2885. btnName = submitBtn.getAttribute("name");
  2886. btnValue = submitBtn.getAttribute("value");
  2887. if (btnName && btnValue) params = [btnName + "=" + encodeURIComponent(btnValue)];
  2888. }
  2889. for (let [key, value] of formData) {
  2890. if (n && /^(p|page)$/i.test(key)) {
  2891. params.push(key + '=' + n);
  2892. } else {
  2893. params.push(key + '=' + encodeURIComponent(value));
  2894. }
  2895. }
  2896. params = params.join('&');
  2897. return form.action + (form.action.indexOf('?') === -1 ? '?' : '&') + params + (form.method === 'post' ? '#p{' + params + '}' : '');
  2898. };
  2899. if (this.curSiteRule.pageElementByJs) {
  2900. this.nextLinkHref = "#";
  2901. return true;
  2902. } else if (this.curSiteRule.nextLinkByJs) {
  2903. try {
  2904. let over = _url => {};
  2905. let targetUrl = await ((typeof this.curSiteRule.nextLinkByJs === 'function') ? this.curSiteRule.nextLinkByJs : new AsyncFunction("doc", '"use strict";' + this.curSiteRule.nextLinkByJs))(doc);
  2906. if (targetUrl) nextLink = {href: targetUrl};
  2907. } catch(e) {
  2908. debug(e);
  2909. }
  2910. } else if (this.curSiteRule.nextLinkByUrl) {
  2911. let targetUrl = this.curUrl.replace(new RegExp(this.curSiteRule.nextLinkByUrl[0], "i"), this.curSiteRule.nextLinkByUrl[1]);
  2912. if (targetUrl !== this.curUrl) {
  2913. let includeSel = this.curSiteRule.nextLinkByUrl[2];
  2914. let excludeSel = this.curSiteRule.nextLinkByUrl[3];
  2915. if (includeSel) {
  2916. includeSel = includeSel.trim();
  2917. if (!getElement(includeSel, doc)) {
  2918. this.nextLinkHref=false;
  2919. return null;
  2920. }
  2921. }
  2922. if (excludeSel) {
  2923. excludeSel = excludeSel.trim();
  2924. if (getElement(excludeSel, doc)) {
  2925. this.nextLinkHref=false;
  2926. return null;
  2927. }
  2928. }
  2929. let reps = targetUrl.match(/{.*?}/g);
  2930. if (reps) {
  2931. reps.forEach(rep => {
  2932. let code = rep.replace("{", "").replace("}", "").replace(/\(\)/g, "0");
  2933. let result = code.match(/^(\d*)\+1$/);
  2934. if (result) {
  2935. result = parseInt(result[1] || 1) + 1;
  2936. } else {
  2937. try {
  2938. result = Function('"use strict";return ' + code)();
  2939. } catch(e) {
  2940. debug(e);
  2941. }
  2942. }
  2943. targetUrl = targetUrl.replace(rep, result);
  2944. });
  2945. }
  2946. }
  2947. nextLink = {href: targetUrl};
  2948. } else if (typeof this.curSiteRule.nextLink !== 'undefined') {
  2949. let nextLinkSel = this.curSiteRule.nextLink;
  2950. if (nextLinkSel != 0) {
  2951. if (Array && Array.isArray && Array.isArray(nextLinkSel)) {
  2952. nextLink = getElement(nextLinkSel[nextIndex], doc, null, true);
  2953. if (!nextLink && curPage === 1 && nextIndex !== 0) {
  2954. nextIndex = 0;
  2955. nextLink = getElement(nextLinkSel[nextIndex], doc, null, true);
  2956. }
  2957. } else nextLink = getElement(nextLinkSel, doc, null, true);
  2958. }
  2959. if (nextLink && (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2)) {
  2960. let form = doc.querySelector('#search-form');
  2961. if (!nextLink.href && nextLink.hasAttribute && nextLink.hasAttribute("onclick") && form) {
  2962. if (/^\d+$/.test(nextLink.innerText)) {
  2963. nextLink.href = getNextLinkByForm(form, nextLink, nextLink.innerText);
  2964. }
  2965. } else if (compareNodeName(nextLink, ["input"]) || nextLink.type === "submit") {
  2966. form = nextLink.parentNode;
  2967. while (form) {
  2968. if (compareNodeName(form, ["form"])) break;
  2969. else form = form.parentNode;
  2970. }
  2971. if (form) {
  2972. nextLink.href = getNextLinkByForm(form, nextLink);
  2973. }
  2974. }
  2975. if (nextLink.href && this.curSiteRule.action != 0) {
  2976. nextLink.href = nextLink.href.replace(/#p{.*/, "");
  2977. }
  2978. }
  2979. } else {
  2980. page = await this.getPage(doc, exist);
  2981. nextLink = page.next;
  2982. if (nextLink) {
  2983. if (compareNodeName(nextLink, ["input"]) || nextLink.type === "submit") {
  2984. if (!/next/i.test(nextLink.getAttribute("onclick"))) {
  2985. let form = nextLink.parentNode;
  2986. while (form) {
  2987. if (compareNodeName(form, ["form"])) break;
  2988. else form = form.parentNode;
  2989. }
  2990. if (form) {
  2991. nextLink.href = getNextLinkByForm(form, nextLink);
  2992. }
  2993. }
  2994. }
  2995. let parent = nextLink;
  2996. while (parent && !compareNodeName(parent, ["body"])) {
  2997. if (parent.hasAttribute && parent.hasAttribute("disabled")) {
  2998. this.nextLinkHref = false;
  2999. return null;
  3000. }
  3001. if (parent.className && parent.classList) {
  3002. if (parent.classList.contains("noClick") || parent.classList.contains("no-pages") || parent.classList.contains("disabled")) {
  3003. this.nextLinkHref = false;
  3004. return null;
  3005. }
  3006. }
  3007. if (parent.style && parent.style.display === "none") {
  3008. this.nextLinkHref = false;
  3009. return null;
  3010. }
  3011. parent = parent.parentNode;
  3012. }
  3013. if (doc === document) {
  3014. if (!this.linkHasHref(nextLink)) {
  3015. if ((clickedSth && this.curSiteRule.smart) || !isVisible(nextLink, _unsafeWindow)) {
  3016. this.nextLinkHref = false;
  3017. return null;
  3018. }
  3019. let video = document.querySelector("video,iframe[id*=play],[id*=play]>iframe,iframe[src*=player],iframe[src*=m3u8]");
  3020. if (video) {
  3021. if (video.offsetParent && video.name !== 'pagetual-iframe') {
  3022. let scrollWidth = video.scrollWidth || video.offsetWidth;
  3023. let scrollHeight = video.scrollHeight || video.offsetHeight;
  3024. if (compareNodeName(video, ["iframe"])) {
  3025. } else if (scrollWidth > 100 && scrollHeight > 100) {
  3026. let winWidth = window.innerWidth || document.documentElement.clientWidth;
  3027. let winHeight = window.innerHeight || document.documentElement.clientHeight;
  3028. if (scrollWidth > winWidth>>1 && scrollHeight > winHeight>>1) {
  3029. debug("Disable when large media found");
  3030. } else {
  3031. video = null;
  3032. }
  3033. } else {
  3034. video = null;
  3035. }
  3036. } else {
  3037. video = null;
  3038. }
  3039. }
  3040. if (video) {
  3041. isPause = true;
  3042. this.clearAddedElements();
  3043. this.nextLinkHref = false;
  3044. return null;
  3045. }
  3046. }
  3047.  
  3048. let nextLinkCs = _unsafeWindow.getComputedStyle(nextLink);
  3049. if (nextLinkCs.cursor === "not-allowed") {
  3050. this.nextLinkHref = false;
  3051. return null;
  3052. }
  3053. this.initNext = nextLink;
  3054. }
  3055. let form = doc.querySelector('#search-form');
  3056. if (!nextLink.href && nextLink.hasAttribute("onclick") && form) {
  3057. if (form && /^\d+$/.test(nextLink.innerText)) {
  3058. href = getNextLinkByForm(form, nextLink, nextLink.innerText);
  3059. }
  3060. }
  3061. }
  3062. }
  3063. if (nextLink) {
  3064. if (!this.checkStopSign(nextLink, doc)) {
  3065. if (curPage > 1 && rulesData.lastPageTips) showTips(i18n("lastPage"), "", 800);
  3066. return null;
  3067. }
  3068. if (this.curSiteRule.action == 3) {
  3069. if (doc == document) debug(nextLink, 'Next link');
  3070. this.nextLinkHref = '#';
  3071. } else {
  3072. let needUrl = (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2);
  3073. if (!href) href = nextLink.href;
  3074. if (href && nextLink.getAttribute) {
  3075. let _href = nextLink.getAttribute("href");
  3076. if (_href) {
  3077. if (_href.charAt(0) === "#" || _href === "?"){
  3078. href = "#";
  3079. } else {
  3080. href = _href;
  3081. }
  3082. } else if (_href === "") {
  3083. href = _href;
  3084. }
  3085. }
  3086.  
  3087. if (needUrl && (href === "" || href === null)) {
  3088. this.nextLinkHref = false;
  3089. } else if (needUrl && /^(javascript:|#)/.test(href)) {
  3090. this.nextLinkHref = false;
  3091. } else {
  3092. this.nextLinkHref = (href && !/^(javascript:|#)/.test(href)) ? this.canonicalUri(href) : "#";
  3093. let tempUrl = this.nextLinkHref;
  3094. 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 + "#"))) {
  3095. this.nextLinkHref = false;
  3096. } else if (doc === document) {
  3097. debug(nextLink, 'Next link');
  3098. }
  3099. }
  3100. }
  3101. } else {
  3102. this.nextLinkHref = false;
  3103. }
  3104. this.nextLinkEle = nextLink;
  3105. this.preload();
  3106. return nextLink;
  3107. }
  3108.  
  3109. compareUrl(url1, url2) {
  3110. if (url1 === url2) return true;
  3111. if (!url1 || !url2) return false;
  3112. let url1Arr = url1.split("?");
  3113. let url2Arr = url2.split("?");
  3114. if (url1Arr[0] != url2Arr[0]) return false;
  3115. if (!url1Arr[1] || !url2Arr[1]) return false;
  3116. url1Arr = url1Arr[1].split("&").sort().join("&");
  3117. url2Arr = url2Arr[1].split("&").sort().join("&");
  3118. return url1Arr === url2Arr;
  3119. }
  3120.  
  3121. filterEles(doc, eles) {
  3122. let filter = this.curSiteRule.filter;
  3123. if (!filter || !eles || eles.length === 0) return;
  3124. if (eles.length === 1) {
  3125. eles = eles[0].children;
  3126. if (eles.length === 1) {
  3127. eles = eles[0].children;
  3128. }
  3129. }
  3130. if (typeof filter === "string") {
  3131. if (/^\d+$/.test(filter)) {
  3132. filter = {count: parseInt(filter)};
  3133. } else filter = {words: filter};
  3134. }
  3135. [].forEach.call(eles, ele => {
  3136. if (!ele.parentNode) return;
  3137. let canKeep = (() => {
  3138. let innerText = (ele.innerText && ele.innerText.trim()) || "";
  3139. if (filter.count) {
  3140. if (innerText.length < filter.count) return false;
  3141. }
  3142. if (filter.words) {
  3143. let wordsRegExp = new RegExp(filter.words, "i");
  3144. if (innerText && wordsRegExp.test(innerText)) return false;
  3145. }
  3146. if (filter.link) {
  3147. let linkRegExp = new RegExp(filter.link, "i");
  3148. if (compareNodeName(ele, ["a"]) && linkRegExp.test(ele.href)) return false;
  3149. let aChildren = ele.querySelectorAll("a");
  3150. for (let i = 0; i < aChildren.length; i++) {
  3151. let child = aChildren[i];
  3152. if (linkRegExp.test(child.href)) return false;
  3153. }
  3154. }
  3155. if (filter.selector) {
  3156. if (getElement(filter.selector, doc, ele)) return false;
  3157. }
  3158. return true;
  3159. })();
  3160. if (!canKeep) {
  3161. ele.parentNode.removeChild(ele);
  3162. }
  3163. });
  3164. }
  3165.  
  3166. checkStopSign(nextLink, doc) {
  3167. if (this.curSiteRule.stopSign) {
  3168. let typeArray = Array && Array.isArray && Array.isArray(this.curSiteRule.stopSign);
  3169. let typeObject = !typeArray && (this.curSiteRule.stopSign.include || this.curSiteRule.stopSign.exclude || this.curSiteRule.stopSign.pageNum);
  3170. if (typeArray || typeObject) {
  3171. let includeSel, excludeSel, curSign, maxSign;
  3172. if (typeArray) {
  3173. includeSel = this.curSiteRule.stopSign[0];
  3174. excludeSel = this.curSiteRule.stopSign[1];
  3175. curSign = this.curSiteRule.stopSign[2];
  3176. maxSign = this.curSiteRule.stopSign[3];
  3177. if (Array && Array.isArray && Array.isArray(includeSel) && !curSign) {
  3178. curSign = includeSel;
  3179. includeSel = false;
  3180. }
  3181. if (excludeSel && Array && Array.isArray && Array.isArray(excludeSel) && !maxSign) {
  3182. maxSign = excludeSel;
  3183. excludeSel = false;
  3184. }
  3185. } else {
  3186. includeSel = this.curSiteRule.stopSign.include;
  3187. excludeSel = this.curSiteRule.stopSign.exclude;
  3188. curSign = this.curSiteRule.stopSign.pageNum;
  3189. }
  3190. if (includeSel) {
  3191. includeSel = includeSel.trim();
  3192. if (!getElement(includeSel, doc)) {
  3193. isPause = true;
  3194. this.nextLinkHref = false;
  3195. return false;
  3196. }
  3197. }
  3198. if (excludeSel) {
  3199. excludeSel = excludeSel.trim();
  3200. if (getElement(excludeSel, doc)) {
  3201. isPause = true;
  3202. this.nextLinkHref = false;
  3203. return false;
  3204. }
  3205. }
  3206. if (curSign) {
  3207. if (!maxSign) maxSign = curSign.slice(2);
  3208. let currentEle = getElement(curSign[0], doc);
  3209. let maxEle = getElement(maxSign[0], doc);
  3210. if (currentEle && maxEle) {
  3211. let currentSignNum, maxSignNum;
  3212. if (/\(.*\)/.test(curSign[1])) {
  3213. currentSignNum = currentEle.innerText.match(new RegExp(curSign[1]));
  3214. if (currentSignNum) currentSignNum = currentSignNum[1];
  3215. } else if (currentEle.getAttribute) {
  3216. currentSignNum = currentEle.getAttribute(curSign[1]);
  3217. }
  3218. if (/\(.*\)/.test(maxSign[1])) {
  3219. maxSignNum = maxEle.innerText.match(new RegExp(maxSign[1]));
  3220. if (maxSignNum) maxSignNum = maxSignNum[1];
  3221. } else if (maxEle.getAttribute) {
  3222. maxSignNum = maxEle.getAttribute(maxSign[1]);
  3223. }
  3224. if (currentSignNum && maxSignNum && currentSignNum == maxSignNum) {
  3225. isPause = true;
  3226. this.nextLinkHref = false;
  3227. return false;
  3228. }
  3229. }
  3230. }
  3231. } else {
  3232. try {
  3233. let stopSign = ((typeof this.curSiteRule.stopSign === 'function') ? this.curSiteRule.stopSign : Function("doc", "nextLink", '"use strict";' + this.curSiteRule.stopSign))(doc, nextLink);
  3234. if (stopSign) {
  3235. isPause = true;
  3236. this.nextLinkHref = false;
  3237. return false;
  3238. }
  3239. } catch(e) {
  3240. debug(e);
  3241. }
  3242. }
  3243. }
  3244. return true;
  3245. }
  3246.  
  3247. preloadImageHandler() {
  3248. if (this.preloadingImage || !this.unCheckedImgs.length) return;
  3249. this.preloadingImage = true;
  3250. setTimeout(() => {
  3251. this.preloadingImage = false;
  3252. this.preloadImageHandler();
  3253. }, 10);
  3254. let iSrc = this.unCheckedImgs.shift();
  3255. let img = document.createElement('img');
  3256. img.src = iSrc;
  3257. this.preloadDiv.appendChild(img);
  3258. }
  3259.  
  3260. preload() {
  3261. if (!rulesData.preload) return;
  3262. if (this.curSiteRule.preload === 0) return;
  3263. if (!this.nextLinkHref || this.nextLinkHref == "#") return;
  3264. if (this.readyStateUnComplete) return;
  3265. if (document.readyState !== 'complete') {
  3266. this.readyStateUnComplete = true;
  3267. let self = this;
  3268. window.addEventListener("load", e => {
  3269. self.readyStateUnComplete = false;
  3270. self.preload();
  3271. });
  3272. return;
  3273. }
  3274. let self = this, url = this.nextLinkHref;
  3275. let postParams = url.match(/#p{(.*)}$/);
  3276. if (postParams) {
  3277. postParams = postParams[1];
  3278. url = url.replace(/#p{.*/, "");
  3279. }
  3280. _GM_xmlhttpRequest({
  3281. url: url,
  3282. method: postParams ? 'POST' : 'GET',
  3283. data: postParams,
  3284. overrideMimeType: 'text/html;charset=' + charset,
  3285. headers: {
  3286. 'Referer': location.href,
  3287. 'User-Agent': navigator.userAgent,
  3288. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + charset,
  3289. },
  3290. timeout: 10000,
  3291. onload: function(res) {
  3292. var doc = null;
  3293. try {
  3294. doc = document.implementation.createHTMLDocument('');
  3295. doc.documentElement.innerHTML = createHTML(res.response);
  3296. var body = getBody(doc);
  3297. if (!self.preloadDiv) {
  3298. self.preloadDiv = document.createElement('div');
  3299. self.preloadDiv.id = "pagetual-preload";
  3300. self.preloadDiv.style.cssText = 'display:none!important;';
  3301. getBody(document).appendChild(self.preloadDiv);
  3302. self.checkedImgs = {};
  3303. self.unCheckedImgs = [];
  3304. }
  3305. let code = self.curSiteRule.preloadImages;
  3306. if (code) {
  3307. let imgSrcArr = new Function("doc", '"use strict";' + code)(doc);
  3308. if (imgSrcArr && imgSrcArr.length) {
  3309. imgSrcArr.forEach(imgSrc => {
  3310. if (imgSrc && !self.checkedImgs[imgSrc]) {
  3311. self.checkedImgs[imgSrc] = true;
  3312. self.unCheckedImgs.push(imgSrc);
  3313. }
  3314. });
  3315. }
  3316. self.preloadImageHandler();
  3317. } else if (code !== 0 && code !== false) {
  3318. if (body && body.firstChild) {
  3319. self.lazyImgAction(body.children, doc);
  3320. }
  3321. [].forEach.call(doc.images, i => {
  3322. let iSrc = i.src;
  3323. if (iSrc && !self.checkedImgs[iSrc]) {
  3324. self.checkedImgs[iSrc] = true;
  3325. self.unCheckedImgs.push(iSrc);
  3326. }
  3327. });
  3328. self.preloadImageHandler();
  3329. }
  3330. }
  3331. catch(e) {
  3332. debug(e);
  3333. return;
  3334. }
  3335. }
  3336. });
  3337. }
  3338.  
  3339. getInsert(refresh) {
  3340. if (refresh) {
  3341. this.insert = null;
  3342. }
  3343. if (this.insert && this.insert.parentNode && document.documentElement.contains(this.insert)) {
  3344. return this.insert;
  3345. }
  3346. if (this.curSiteRule.insert) {
  3347. let insertSel = this.curSiteRule.insert;
  3348. if (Array && Array.isArray && Array.isArray(insertSel)) {
  3349. insertSel = insertSel[nextIndex < insertSel.length ? nextIndex : 0];
  3350. }
  3351. this.insert = getElement(insertSel, document, null, true);
  3352. } else {
  3353. this.docPageElement = null;
  3354. let pageElement = this.getPageElement(document, _unsafeWindow);
  3355. if (this.curSiteRule.smart && this.nextLinkHref == "#" && this.curSiteRule.pageElement === 'body') {
  3356. debug("Stop as jsNext & whole body");
  3357. isPause = true;
  3358. return null;
  3359. }
  3360. if (pageElement && pageElement.length > 0) {
  3361. let pEIndex = pageElement.length - 1;
  3362. let pELast = pageElement[pEIndex];
  3363. while(pELast && compareNodeName(pELast, ["link", "meta", "style", "script"])) {
  3364. pEIndex--;
  3365. pELast = pageElement[pEIndex];
  3366. }
  3367. this.insert = pELast.nextSibling ? pELast.nextSibling : pELast.parentNode.appendChild(document.createTextNode(' '));
  3368. }
  3369. }
  3370. return this.insert;
  3371. }
  3372.  
  3373. pageInit(doc, eles) {
  3374. let code = this.curSiteRule.pageInit;
  3375. if (code) {
  3376. let initFunc = ((typeof code == 'function') ? code : Function("doc", "eles", '"use strict";' + code));
  3377. let checkInit = (resolve) => {
  3378. try {
  3379. if (initFunc(doc, eles) === false) {
  3380. setTimeout(() => {
  3381. checkInit(resolve);
  3382. }, 100);
  3383. } else {
  3384. resolve(true);
  3385. }
  3386. } catch(e) {
  3387. resolve(false);
  3388. debug(e);
  3389. }
  3390. };
  3391. return new Promise((resolve) => {
  3392. checkInit(function(e) {
  3393. resolve(e)
  3394. });
  3395. })
  3396. }
  3397. }
  3398.  
  3399. pageAction(doc, eles) {
  3400. let code = this.curSiteRule.pageAction;
  3401. if (code) {
  3402. try {
  3403. ((typeof code == 'function') ? code : Function("doc", "eles", '"use strict";' + code))(doc, eles);
  3404. } catch(e) {
  3405. debug(e);
  3406. }
  3407. }
  3408. this.openInNewTab(eles);
  3409. this.replaceElement(doc);
  3410. }
  3411.  
  3412. openInNewTab(eles) {
  3413. if (openInNewTab) {
  3414. [].forEach.call(eles, ele => {
  3415. if (compareNodeName(ele, ["a"]) && ele.href && !/^(mailto:|javascript:)|#/.test(ele.href)) {
  3416. ele.setAttribute('target', openInNewTab == 1 ? '_blank' : '_self');
  3417. } else {
  3418. [].forEach.call(ele.querySelectorAll('a[href]:not([href^="mailto:"]):not([href^="javascript:"]):not([href^="#"])'), a => {
  3419. if (openInNewTab == 1) {
  3420. a.setAttribute('target', '_blank');
  3421. if (a.getAttribute('onclick') == 'atarget(this)') {
  3422. a.removeAttribute('onclick');
  3423. }
  3424. } else a.setAttribute('target', '_self');
  3425. });
  3426. }
  3427. });
  3428. }
  3429. }
  3430.  
  3431. lazyImgAction(eles, doc) {
  3432. if (!eles || eles.length == 0) return;
  3433. let lazyImgSrc = this.curSiteRule.lazyImgSrc;
  3434. if (lazyImgSrc === 0 || lazyImgSrc === '0') return;
  3435. let imgLazyAttrs = [];
  3436. 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"];
  3437. let removeProps = [];
  3438. let setLazyImg = img => {
  3439. let realSrc;
  3440. imgLazyAttrs.forEach(attr => {
  3441. realSrc = img.getAttribute(lazyImgSrc[0]);
  3442. if (realSrc) {
  3443. removeProps.forEach(prop => {
  3444. img.removeAttribute(prop.trim());
  3445. });
  3446. img.src = realSrc;
  3447. return;
  3448. }
  3449. })
  3450. if (!realSrc) {
  3451. let lazyAttr = "";
  3452. if (img.getAttribute("_src") && !img.src) {
  3453. lazyAttr = "_src";
  3454. realSrc = img.getAttribute(lazyAttr);
  3455. } else {
  3456. for (let i in lazyImgAttr) {
  3457. lazyAttr = lazyImgAttr[i];
  3458. let attrValue = img.getAttribute(lazyAttr);
  3459. if (attrValue) {
  3460. realSrc = attrValue;
  3461. break;
  3462. }
  3463. }
  3464. }
  3465. if (!realSrc && img._lazyrias && img._lazyrias.srcset) {
  3466. realSrc = img._lazyrias.srcset[img._lazyrias.srcset.length - 1];
  3467. lazyAttr = "_lazyrias";
  3468. }
  3469. if (!realSrc && img.srcset) {
  3470. lazyAttr = "srcset";
  3471. var srcs = img.srcset.split(/[xw],/i), largeSize = 0;
  3472. srcs.forEach(srci => {
  3473. let srcInfo = srci.trim().split(" "), curSize = parseInt(srcInfo[1]);
  3474. if (srcInfo[1] && curSize > largeSize) {
  3475. largeSize = curSize;
  3476. realSrc = srcInfo[0];
  3477. }
  3478. });
  3479. }
  3480. if (realSrc) {
  3481. img.src = realSrc;
  3482. img.removeAttribute("srcset");
  3483. img.removeAttribute(lazyAttr);
  3484. if (img.classList && img.classList.contains && img.classList.contains("lazy")) {
  3485. img.classList.remove("lazy");
  3486. }
  3487. if (img.style.display == "none") {
  3488. img.style.display = "";
  3489. }
  3490. if (img.style.visibility == "hidden") {
  3491. img.style.visibility = "";
  3492. }
  3493. if (img.style.opacity == 0) {
  3494. img.style.opacity = "";
  3495. }
  3496. }
  3497. }
  3498. };
  3499. if (lazyImgSrc) {
  3500. if (!Array.isArray(lazyImgSrc)) {
  3501. lazyAttrs = lazyImgSrc.split(",");
  3502. } else {
  3503. lazyAttrs = lazyImgSrc[0].split(",");
  3504. removeProps = lazyImgSrc[1].split(",");
  3505. }
  3506. }
  3507. lazyAttrs.forEach(attr => {
  3508. let attrArr = attr.split("|");
  3509. if (attrArr.length !== 2) {
  3510. imgLazyAttrs.push(attr.trim());
  3511. } else {
  3512. let selector = attrArr[0].trim();
  3513. let lazyAttr = attrArr[1].trim();
  3514. if (selector == "img") {
  3515. imgLazyAttrs.push(lazyAttr);
  3516. } else {
  3517. selector += "[" + lazyAttr + "]";
  3518. [].forEach.call(doc.querySelectorAll(selector), ele => {
  3519. ele.style.setProperty("background-image", "url(" + ele.getAttribute(lazyAttr) + ")", "important");
  3520. removeProps.forEach(prop => {
  3521. ele.removeAttribute(prop.trim());
  3522. });
  3523. });
  3524. }
  3525. }
  3526. });
  3527. [].forEach.call(doc.querySelectorAll("img,picture>source"), img => {
  3528. setLazyImg(img);
  3529. });
  3530. }
  3531.  
  3532. canListenUrlChange() {
  3533. if (this.curSiteRule && typeof this.curSiteRule.listenUrlChange === 'undefined' && this.docElementValid()) {
  3534. return false;
  3535. }
  3536. return true;
  3537. }
  3538.  
  3539. docElementValid() {
  3540. return (this.docPageElement && document.documentElement.contains(this.docPageElement[0]));
  3541. }
  3542.  
  3543. urlChanged() {
  3544. urlChanged = true;
  3545. this.clearAddedElements();
  3546. }
  3547.  
  3548. initPage(callback) {
  3549. let self = this;
  3550. if (self.initing) return;
  3551. self.initing = true;
  3552. setTimeout(() => {
  3553. self.initing = false;
  3554. }, 100);
  3555. curPage = 1;
  3556. urlChanged = false;
  3557. tryTimes = 0;
  3558. this.clearAddedElements();
  3559. this.insert = null;
  3560. this.visibilityItems = [];
  3561. this.visibleIndex = -1;
  3562. this.pageDoc = document;
  3563. this.nextLinkHref = null;
  3564. this.curUrl = location.href;
  3565. this.oldUrl = "";
  3566. this.initUrl = location.href;
  3567. this.historyUrl = "";
  3568. this.possibleCheck = 0;
  3569. let base = document.querySelector("base");
  3570. this.basePath = base ? base.href : location.href;
  3571. this.getRule(async () => {
  3572. if (self.curSiteRule.sideController === true || (self.curSiteRule.sideController !== false && rulesData.sideController)) {
  3573. isPause = manualPause;
  3574. }
  3575. if (typeof(self.curSiteRule.rate) !== "undefined") {
  3576. rate = self.curSiteRule.rate;
  3577. }
  3578. if (self.curSiteRule.enable == 0) {
  3579. debug("Stop as rule disable");
  3580. isPause = true;
  3581. _GM_registerMenuCommand(i18n("enable"), () => {
  3582. showTips(i18n("enableSiteTips"));
  3583. if(!self.customRules) {
  3584. self.customRules = [];
  3585. }
  3586. for (let i in self.customRules) {
  3587. if (self.customRules[i].url == self.curSiteRule.url) {
  3588. self.customRules.splice(i, 1);
  3589. break;
  3590. }
  3591. }
  3592. self.curSiteRule.enable = 1;
  3593. self.customRules.unshift(self.curSiteRule);
  3594. storage.setItem("customRules", self.customRules);
  3595. location.reload();
  3596. });
  3597. return;
  3598. }
  3599. if (rulesData.sideControllerAlways) {
  3600. sideController.setup();
  3601. }
  3602. //若是再亂匹配就不緩存wedata,或者只在找完本地規則之後再考慮wedata的緩存
  3603. if (self.curSiteRule.smart) {
  3604. delete self.curSiteRule.pageElement;
  3605. if (!self.possibleRule) {
  3606. self.smartRules = self.smartRules.filter(item => {return item && item.url != self.curSiteRule.url});
  3607. self.smartRules.unshift(self.curSiteRule);
  3608. if (self.smartRules.length > 100) {
  3609. self.smartRules.pop();
  3610. }
  3611. storage.setItem("smartRules", self.smartRules);
  3612. }
  3613. } else if (self.curSiteRule && self.curSiteRule.url.length > 13) {
  3614. self.addToHpRules();
  3615. }
  3616. let css = self.curSiteRule.css || rulesData.customCss;
  3617. if (css) {
  3618. let cssArr = css.split("inIframe:");
  3619. if (cssArr && cssArr.length) {
  3620. _GM_addStyle(cssArr[0]);
  3621. }
  3622. }
  3623. if (/sidesearch=(1|true)$/.test(self.curUrl)) {
  3624. openInNewTab = 0;
  3625. } else if (typeof self.curSiteRule.openInNewTab !== 'undefined') {
  3626. openInNewTab = self.curSiteRule.openInNewTab ? 1 : 2;
  3627. }
  3628. let autoClick = self.curSiteRule.autoClick;
  3629. if (autoClick) {
  3630. let autoClickBtn;
  3631. autoClickBtn = getElement(autoClick, document, null, true);
  3632. if (autoClickBtn) {
  3633. emuClick(autoClickBtn);
  3634. }
  3635. }
  3636. let code = self.curSiteRule.init;
  3637. if (code) {
  3638. try {
  3639. 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)});
  3640. } catch(e) {
  3641. debug(e);
  3642. }
  3643. }
  3644. await self.getNextLink(document, true);
  3645. if (self.curSiteRule.pageNum && self.nextLinkHref && self.nextLinkHref != "#") {
  3646. let num1st = self.getPageNumFromUrl(location.href, 1);
  3647. let num2nd = self.getPageNumFromUrl(self.nextLinkHref, 1);
  3648. if (num2nd != num1st + 1) {
  3649. self.curSiteRule.pageNum = null;
  3650. }
  3651. }
  3652. if (self.curSiteRule.smart && self.nextLinkHref == false && self.possibleRule) {
  3653. let urlReg = new RegExp(self.possibleRule.url, "i");
  3654. function checkPossible () {
  3655. if (self.possibleCheck++ < 3) {
  3656. setTimeout(() => {
  3657. if (self.curSiteRule.smart) {
  3658. var href = location.href.slice(0, 500);
  3659. if (urlReg.test(href) && self.ruleMatch(self.possibleRule)) {
  3660. self.initPage(() => {});
  3661. } else checkPossible();
  3662. }
  3663. }, 3000);
  3664. }
  3665. }
  3666. checkPossible();
  3667. }
  3668. self.refreshByClick();
  3669. if (emuIframe && emuIframe.parentNode) {
  3670. emuIframe.parentNode.removeChild(emuIframe);
  3671. emuIframe = null;
  3672. }
  3673.  
  3674. let pageElementCss = self.curSiteRule.pageElementCss || rulesData.pageElementCss;
  3675. if (pageElementCss && pageElementCss !== '0') {
  3676. self.getPageElement(document, _unsafeWindow);
  3677. }
  3678. callback();
  3679. let initRun = typeof self.curSiteRule.initRun == 'undefined' ? rulesData.initRun : self.curSiteRule.initRun;
  3680. if (self.nextLinkHref) {
  3681. sideController.setup();
  3682. if (initRun && initRun != false) {
  3683. setTimeout(() => {
  3684. nextPage();
  3685. }, 300);
  3686. }
  3687. }
  3688. });
  3689. }
  3690.  
  3691. async hookUrlSetEle(ele, doc) {
  3692. let self = this;
  3693. return new Promise((resolve) => {
  3694. let catchUrl = e => {
  3695. ele.dataset.url = self.catchedUrl;
  3696. ele.setAttribute('onclick', 'window.open(this.dataset.url)');
  3697. window.removeEventListener('pagetual_openUrl', catchUrl);
  3698. resolve();
  3699. };
  3700. window.addEventListener('pagetual_openUrl', catchUrl);
  3701. emuClick(ele, doc);
  3702. });
  3703. }
  3704.  
  3705. async hookUrl(doc) {
  3706. let sel = this.curSiteRule.hookUrl;
  3707. if (!sel) return;
  3708. let self = this;
  3709. if (!this.initHook) {
  3710. this.initHook = true;
  3711. Object.defineProperty(doc.defaultView, 'open', {
  3712. get: function () {
  3713. return (s) => {
  3714. self.catchedUrl = s;
  3715. var e = new CustomEvent('pagetual_openUrl');
  3716. window.dispatchEvent(e);
  3717. }
  3718. }
  3719. });
  3720. }
  3721. let eles = getAllElements(sel, doc);
  3722. for (let i = 0; i < eles.length; i++) {
  3723. await sleep(1);
  3724. let ele = eles[i];
  3725. if (!ele.dataset.url) {
  3726. await this.hookUrlSetEle(ele, doc);
  3727. }
  3728. }
  3729. }
  3730.  
  3731. beginLoading() {
  3732. isLoading = true;
  3733. if (targetY >= 0) {
  3734. window.scrollTo({ top: targetY, behavior: 'instant'});
  3735. targetY = -1;
  3736. }
  3737. let lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3738. ruleParser.insertElement(loadingDiv);
  3739. if (forceState == 2) {
  3740. getBody(document).appendChild(loadingDiv);
  3741. } else {
  3742. let parent = loadingDiv.parentNode;
  3743. if (compareNodeName(parent, ["tbody"])) {
  3744. parent = parent.parentNode;
  3745. }
  3746. if (compareNodeName(parent, ["table"])) {
  3747. parent.parentNode.appendChild(loadingDiv);
  3748. }
  3749. }
  3750. getBody(document).scrollTop = lastScrollTop;
  3751. document.documentElement.scrollTop = lastScrollTop;
  3752. }
  3753.  
  3754. insertElement(ele) {
  3755. if (!this.insert || !this.insert.parentNode) {
  3756. this.getInsert();
  3757. }
  3758. if (this.insert && this.insert.parentNode) {
  3759. let self = this;
  3760. if (ele.nodeName == "#document-fragment") {
  3761. [].forEach.call(ele.children, el => {
  3762. self.addedElePool.push(el);
  3763. });
  3764. } else {
  3765. this.addedElePool.push(ele);
  3766. }
  3767. if (this.curSiteRule.insertPos == 2 || this.curSiteRule.insertPos == "in") {
  3768. this.insert.appendChild(ele);
  3769. } else {
  3770. this.insert.parentNode.insertBefore(ele, this.insert);
  3771. }
  3772. }
  3773. }
  3774.  
  3775. noValidContent(url) {
  3776. if (!this.curSiteRule.nextLinkByUrl) showTips(i18n("noValidContent"), url);
  3777. }
  3778.  
  3779. async insertPage(doc, eles, url, callback, tried) {
  3780. this.oldUrl = this.curUrl;
  3781. let oldTitle = document.title;
  3782. try {
  3783. let oldTitle = this.pageDoc.title;
  3784. } catch (e) {}
  3785. this.pageDoc = doc;
  3786. this.curUrl = url;
  3787. isLoading = true;
  3788. let nextLink = await this.getNextLink(doc);
  3789. this.nextTitle = "";
  3790. if (this.curSiteRule.pageBarText) {
  3791. if (this.curSiteRule.pageBarText == 1 || this.curSiteRule.pageBarText == true) {
  3792. this.nextTitle = doc.title;
  3793. } else {
  3794. try {
  3795. this.nextTitle = ((typeof this.curSiteRule.pageBarText == 'function') ? this.curSiteRule.pageBarText : Function("doc",'"use strict";' + this.curSiteRule.pageBarText))(doc);
  3796. } catch(e) {
  3797. debug(e);
  3798. }
  3799. }
  3800. }
  3801. if (curPage == 1 && !tried && !nextLink && this.curSiteRule.smart && this.curSiteRule.pageElement && this.curSiteRule.action != 0) {
  3802. this.curSiteRule.action = 1;
  3803. this.curUrl = location.href;
  3804. isLoading = false;
  3805. return false;
  3806. }
  3807.  
  3808. if (targetY >= 0) {
  3809. window.scrollTo({ top: targetY, behavior: 'instant'});
  3810. targetY = -1;
  3811. }
  3812. let lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3813. this.getInsert();
  3814. await this.pageInit(doc, eles);
  3815. var self = this, newEles = [];
  3816. if (!eles || eles.length == 0 || !self.insert || !self.insert.parentNode) {
  3817. if (callback) callback(eles);
  3818. loadPageOver();
  3819. } else {
  3820. if (callback) callback(eles);
  3821. loadPageOver();
  3822. const collection = document.createDocumentFragment();
  3823. [].forEach.call(eles, ele => {
  3824. let newEle = ele.cloneNode(true);
  3825. let oldCanvass = ele.querySelectorAll("canvas");
  3826. let newCanvass = newEle.querySelectorAll("canvas");
  3827. if (self.updateUrl) {
  3828. [].forEach.call(newEle.querySelectorAll("img"), img => {
  3829. if (img.getAttribute("src")) img.src = self.canonicalUri(img.getAttribute("src"));
  3830. });
  3831. [].forEach.call(newEle.querySelectorAll("a"), a => {
  3832. if (a.getAttribute("href")) a.href = self.canonicalUri(a.getAttribute("href"));
  3833. });
  3834. }
  3835. for (let i = 0; i < oldCanvass.length; i++) {
  3836. let oldCanvas = oldCanvass[i];
  3837. let newCanvas = newCanvass[i];
  3838. newCanvas.getContext('2d').drawImage(oldCanvas, 0, 0);
  3839. }
  3840. if (!compareNodeName(newEle, ["style", "script"])) self.visibilityItems.push(newEle);
  3841. collection.appendChild(newEle)
  3842. newEles.push(newEle);
  3843. });
  3844. self.insertElement(collection);
  3845. }
  3846. getBody(document).scrollTop = lastScrollTop;
  3847. document.documentElement.scrollTop = lastScrollTop;
  3848. this.pageAction(doc, newEles);
  3849. let enableHistory = this.curSiteRule.history;
  3850. let enableHistoryAfterInsert = false;
  3851. if (enableHistory == 1) {
  3852. enableHistory = true;
  3853. } else if (enableHistory == 2) {
  3854. enableHistory = true;
  3855. enableHistoryAfterInsert = true;
  3856. } else if (enableHistory == 0) {
  3857. enableHistory = false;
  3858. } else {
  3859. enableHistory = rulesData.enableHistory;
  3860. enableHistoryAfterInsert = rulesData.enableHistoryAfterInsert;
  3861. }
  3862. if (enableHistory) {
  3863. this.historyUrl = enableHistoryAfterInsert ? this.curUrl : this.oldUrl;
  3864. if(this.historyUrl != location.href) {
  3865. let isJs = this.hrefIsJs(this.historyUrl);
  3866. if (!isJs) {
  3867. let historyTitle = enableHistoryAfterInsert ? doc.title : oldTitle;
  3868. _unsafeWindow.history.replaceState(undefined, historyTitle, this.historyUrl);
  3869. document.title = historyTitle;
  3870. }
  3871. }
  3872. }
  3873. isLoading = false;
  3874. return true;
  3875. }
  3876. }
  3877. var ruleParser = new RuleParser();
  3878.  
  3879. class SideController {
  3880. //static controller;
  3881. constructor() {
  3882. this.inited = false;
  3883. }
  3884.  
  3885. /*static getInstance() {
  3886. if (!SideController.controller) {
  3887. SideController.controller = new SideController();
  3888. }
  3889. return SideController.controller;
  3890. }*/
  3891.  
  3892. setup() {
  3893. if (ruleParser.curSiteRule.sideController === false) return;
  3894. if (!rulesData.sideController && !ruleParser.curSiteRule.sideController) return;
  3895. this.addToStage();
  3896. }
  3897.  
  3898. init() {
  3899. if (this.inited) return;
  3900. this.inited = true;
  3901. let self = this;
  3902. this.cssText = `
  3903. #pagetual-sideController {
  3904. position: fixed;
  3905. top: calc(50% - 83px);
  3906. left: calc(99% - 40px);
  3907. width: 40px;
  3908. border-radius: 20px;
  3909. box-shadow: rgb(0 0 0) 0px 0px 10px;
  3910. text-align: center;
  3911. background: #ffffffd0!important;
  3912. user-select: none;
  3913. z-index: 2147483646!important;
  3914. padding: 0!important;
  3915. opacity: 0.35;
  3916. transition: opacity .5s ease, background .5s, box-shadow .5s;
  3917. }
  3918. #pagetual-sideController * {
  3919. font-weight: bold;
  3920. font-family: arial;
  3921. font-style: normal;
  3922. font-size: 20px!important;
  3923. color: black!important;
  3924. line-height: normal;
  3925. float: none;
  3926. text-align: center;
  3927. }
  3928. #pagetual-sideController.stop {
  3929. -webkit-filter: invert(100%);
  3930. filter: invert(100%);
  3931. }
  3932. .pagetual-sideController-btn {
  3933. padding: 5px 0;
  3934. cursor: pointer;
  3935. transition: transform .15s ease-in-out, opacity .3s ease;
  3936. }
  3937. #pagetual-sideController .pagetual-sideController-btn:hover {
  3938. transform: scale(1.5);
  3939. color: red!important;
  3940. }
  3941. #pagetual-sideController #pagetual-sideController-move > svg {
  3942. transition: transform .3s ease;
  3943. }
  3944. #pagetual-sideController #pagetual-sideController-move > svg:hover {
  3945. transform: scale(1.2);
  3946. }
  3947. #pagetual-sideController.minSize #pagetual-sideController-move > svg {
  3948. background: white;
  3949. opacity: 0;
  3950. }
  3951. #pagetual-sideController #pagetual-sideController-move > img,
  3952. #pagetual-sideController #pagetual-sideController-move > span {
  3953. width: 35px;
  3954. height: 35px;
  3955. cursor: pointer;
  3956. }
  3957. #pagetual-sideController.minSize #pagetual-sideController-move > img,
  3958. #pagetual-sideController.minSize #pagetual-sideController-move > span {
  3959. border-radius: 50px;
  3960. text-shadow: rgb(255 255 255) 0px 0px 10px;
  3961. }
  3962. #pagetual-sideController #pagetual-sideController-pagenum {
  3963. font-size: 15px!important;
  3964. line-height: 30px;
  3965. text-align: center;
  3966. position: absolute;
  3967. right: calc(50% - 15px);
  3968. top: calc(50% - 15px);
  3969. border: 1px solid #00000099;
  3970. display: inline-block;
  3971. width: 30px;
  3972. height: 30px;
  3973. box-sizing: border-box;
  3974. border-radius: 50%;
  3975. background: white;
  3976. opacity: 0;
  3977. transition: opacity .5s ease;
  3978. pointer-events: none;
  3979. }
  3980. #pagetual-sideController.minSize #pagetual-sideController-pagenum {
  3981. opacity: 0.8;
  3982. }
  3983. #pagetual-sideController:hover {
  3984. opacity: 1;
  3985. }
  3986. #pagetual-sideController>.extra {
  3987. bottom: 170px;
  3988. left: 0px;
  3989. width: 40px;
  3990. position: absolute;
  3991. }
  3992. #pagetual-sideController>.extra>svg {
  3993. width: 40px;
  3994. height: 30px;
  3995. opacity: 0.1;
  3996. cursor: pointer;
  3997. margin: 0 0 5px 0;
  3998. transition: opacity .3s ease;
  3999. }
  4000. #pagetual-sideController.minSize>.extra>svg {
  4001. opacity: 0;
  4002. }
  4003. #pagetual-sideController>.extra>svg:hover {
  4004. opacity: 1;
  4005. }
  4006. #pagetual-sideController.minSize {
  4007. box-shadow: rgb(0 0 0 / 0%) 0px 0px 0px;
  4008. background: #00000000!important;
  4009. pointer-events: none;
  4010. }
  4011. #pagetual-sideController.minSize #pagetual-sideController-move {
  4012. pointer-events: all;
  4013. }
  4014. #pagetual-sideController.minSize .pagetual-sideController-btn {
  4015. opacity: 0;
  4016. }
  4017. `;
  4018. let frame = document.createElement("div");
  4019. frame.id = "pagetual-sideController";
  4020. frame.innerHTML = createHTML(`
  4021. <div class="extra">
  4022. <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>
  4023. <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>
  4024. </div>
  4025. <div id="pagetual-sideController-top" class="pagetual-sideController-btn">⊼</div>
  4026. <div>
  4027. <div id="pagetual-sideController-pre" class="pagetual-sideController-btn">∧</div>
  4028. <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>
  4029. <div id="pagetual-sideController-next" class="pagetual-sideController-btn">∨</div>
  4030. </div>
  4031. <div id="pagetual-sideController-bottom" class="pagetual-sideController-btn">⊻</div>
  4032. `);
  4033. frame.classList.add("stop");
  4034. let top = frame.querySelector("#pagetual-sideController-top");
  4035. let pre = frame.querySelector("#pagetual-sideController-pre");
  4036. let move = frame.querySelector("#pagetual-sideController-move");
  4037. let next = frame.querySelector("#pagetual-sideController-next");
  4038. let bottom = frame.querySelector("#pagetual-sideController-bottom");
  4039. let pagenum = frame.querySelector("#pagetual-sideController-pagenum");
  4040. let scroll = frame.querySelector("#scroll");
  4041. let loadNow = frame.querySelector("#loadNow");
  4042. if (rulesData.sideControllerScroll === false) {
  4043. scroll.style.display = "none";
  4044. }
  4045. if (rulesData.sideControllerLoadNow === false) {
  4046. loadNow.style.display = "none";
  4047. }
  4048. if (sideControllerIcon) move.innerHTML = sideControllerIcon;
  4049.  
  4050. frame.addEventListener("dblclick", e => {
  4051. e.preventDefault();
  4052. e.stopPropagation();
  4053. });
  4054.  
  4055. frame.addEventListener("mouseenter", e => {
  4056. clearTimeout(self.hideTimer);
  4057. frame.classList.remove("minSize");
  4058. });
  4059.  
  4060. frame.addEventListener("mouseleave", e => {
  4061. clearTimeout(self.hideTimer);
  4062. self.hideTimer = setTimeout(() => {
  4063. frame.classList.add("minSize");
  4064. }, 800);
  4065. });
  4066.  
  4067. document.body.addEventListener('touchstart', e => {
  4068. if (e.target === frame || frame.contains(e.target)) {
  4069. frame.classList.remove("minSize");
  4070. } else {
  4071. frame.classList.add("minSize");
  4072. }
  4073. });
  4074.  
  4075. scroll.addEventListener("click", e => {
  4076. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  4077. autoScroll = parseInt(autoScroll) || 0;
  4078. if (autoScroll < 0) autoScroll = 0;
  4079. if (autoScroll && autoScroll != autoScrollRate) {
  4080. autoScrollRate = autoScroll;
  4081. storage.setItem("autoScrollRate", autoScrollRate);
  4082. }
  4083. setListData("autoScroll", location.host + location.pathname, autoScroll);
  4084. startAutoScroll();
  4085. }, true);
  4086.  
  4087. loadNow.addEventListener("click", e => {
  4088. if (autoLoadNum != -1) {
  4089. autoLoadNum = -1;
  4090. return;
  4091. }
  4092. let loadNum = window.prompt(i18n("loadConfirm"), loadNowNum);
  4093. if (loadNum === "" || loadNum === null) return;
  4094. loadNum = Math.abs(parseInt(loadNum)) || 0;
  4095. if (loadNowNum != loadNum) {
  4096. loadNowNum = loadNum;
  4097. storage.setItem("loadNowNum", loadNowNum);
  4098. }
  4099. autoLoadNum = loadNum;
  4100. nextPage();
  4101. }, true);
  4102.  
  4103. pre.addEventListener("click", e => {
  4104. let prePageBar = getPageBar().preBar;
  4105. if (prePageBar) {
  4106. scrollToPageBar(prePageBar);
  4107. } else {
  4108. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  4109. targetY = scrollTop - (window.innerHeight || document.documentElement.clientHeight);
  4110. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4111. }
  4112. }, true);
  4113.  
  4114. next.addEventListener("click", e => {
  4115. let pageBarObj = getPageBar();
  4116. let nextPageBar = pageBarObj.nextBar;
  4117. if (nextPageBar) {
  4118. scrollToPageBar(nextPageBar);
  4119. } else {
  4120. if (pageBarObj.preBar) {
  4121. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  4122. targetY = scrollH || 9999999;
  4123. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4124. } else {
  4125. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  4126. targetY = scrollTop + (window.innerHeight || document.documentElement.clientHeight);
  4127. window.scrollTo({ top: targetY, behavior: 'smooth'});
  4128. }
  4129. }
  4130. }, true);
  4131.  
  4132. top.addEventListener("click", e => {
  4133. getBody(document).scrollTop=0;
  4134. document.documentElement.scrollTop=0;
  4135. e.preventDefault();
  4136. e.stopPropagation();
  4137. }, true);
  4138.  
  4139. bottom.addEventListener("click", e => {
  4140. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  4141. changeStop(true);
  4142. }
  4143. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  4144. getBody(document).scrollTop = scrollH || 9999999;
  4145. document.documentElement.scrollTop = scrollH || 9999999;
  4146. e.preventDefault();
  4147. e.stopPropagation();
  4148. }, true);
  4149.  
  4150. let initX, initY, moving = false;
  4151. let removeTimer;
  4152. move.addEventListener("click", e => {
  4153. if (!moving) {
  4154. changeStop(!isPause);
  4155. }
  4156. }, true);
  4157. move.addEventListener("dblclick", e => {
  4158. clearTimeout(removeTimer);
  4159. document.removeEventListener("mousemove", mouseMoveHandler, true);
  4160. document.removeEventListener("mouseup", mouseUpHandler, true);
  4161. changeStop(!isPause);
  4162. if (isPause) {
  4163. ruleParser.hideAddedElements();
  4164. } else {
  4165. ruleParser.showAddedElements();
  4166. }
  4167. }, true);
  4168.  
  4169. move.oncontextmenu = e => {
  4170. e.preventDefault();
  4171. picker.start();
  4172. };
  4173.  
  4174. let clientX = e => {
  4175. if (e.type.indexOf('mouse') === 0) {
  4176. return e.clientX;
  4177. } else {
  4178. return e.changedTouches[0].clientX;
  4179. }
  4180. };
  4181.  
  4182. let clientY = e => {
  4183. if (e.type.indexOf('mouse') === 0) {
  4184. return e.clientY;
  4185. } else {
  4186. return e.changedTouches[0].clientY;
  4187. }
  4188. };
  4189.  
  4190. let mouseMoveHandler = e => {
  4191. if (moving) {
  4192. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  4193. let windowWidth = window.innerWidth || document.documentElement.clientWidth;
  4194. initX = (clientX(e) - 10 + 40) / windowWidth * 100;
  4195. initY = (clientY(e) - 83 + 83) / windowHeight * 100;
  4196. this.frame.style.top = `calc(${initY}% - 83px)`;
  4197. this.frame.style.left = `calc(${initX}% - 40px)`;
  4198. } else if (Math.abs(clientX(e) - initX) + Math.abs(clientY(e) - initY) > 20) {
  4199. moving = true;
  4200. clearTimeout(removeTimer);
  4201. }
  4202. };
  4203. let mouseUpHandler = e => {
  4204. clearTimeout(removeTimer);
  4205. document.removeEventListener("mousemove", mouseMoveHandler, true);
  4206. document.removeEventListener("mouseup", mouseUpHandler, true);
  4207. document.removeEventListener("touchmove", mouseMoveHandler, true);
  4208. document.removeEventListener("touchend", mouseUpHandler, true);
  4209. if (moving) {
  4210. rulesData.sideControllerPos = {x: parseInt(initX), y: parseInt(initY)};
  4211. storage.setItem("rulesData", rulesData);
  4212. }
  4213. };
  4214. let mouseDownHandler = e => {
  4215. initX = clientX(e);
  4216. initY = clientY(e);
  4217. moving = false;
  4218. clearTimeout(removeTimer);
  4219. removeTimer = setTimeout(() => {
  4220. if (e.type === "touchstart") {
  4221. picker.start();
  4222. } else {
  4223. self.remove();
  4224. }
  4225. }, 1500);
  4226. document.addEventListener("mousemove", mouseMoveHandler, true);
  4227. document.addEventListener("mouseup", mouseUpHandler, true);
  4228. document.addEventListener("touchmove", mouseMoveHandler, true);
  4229. document.addEventListener("touchend", mouseUpHandler, true);
  4230. e.stopPropagation();
  4231. e.preventDefault();
  4232. };
  4233.  
  4234. move.addEventListener("mousedown", mouseDownHandler, true);
  4235. move.addEventListener("touchstart", mouseDownHandler, { passive: false, capture: true });
  4236.  
  4237. this.frame = frame;
  4238. this.pagenum = pagenum;
  4239. if (rulesData.sideControllerPos) {
  4240. this.frame.style.top = `calc(${rulesData.sideControllerPos.y}% - 83px)`;
  4241. this.frame.style.left = `calc(${rulesData.sideControllerPos.x}% - 40px)`;
  4242. }
  4243. }
  4244.  
  4245. addToStage() {
  4246. this.init();
  4247. if (!this.styleEle || !this.styleEle.parentNode) {
  4248. this.styleEle = _GM_addStyle(this.cssText);
  4249. }
  4250. if (!isPause) {
  4251. this.frame.classList.remove("stop");
  4252. }
  4253. this.pagenum.innerHTML = createHTML(curPage);
  4254. this.frame.title = i18n("page") + curPage;
  4255. if (this.frame.parentNode) return;
  4256. getBody(document).appendChild(this.frame);
  4257. clearTimeout(this.hideTimer);
  4258. this.frame.classList.add("minSize");
  4259. }
  4260.  
  4261. remove() {
  4262. if (this.frame && this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  4263. }
  4264. }
  4265. const sideController = new SideController();
  4266.  
  4267. class NextSwitch {
  4268. //static nextSwitch;
  4269. constructor() {
  4270. this.inited = false;
  4271. }
  4272.  
  4273. /*static getInstance() {
  4274. if (!NextSwitch.nextSwitch) {
  4275. NextSwitch.nextSwitch = new NextSwitch();
  4276. }
  4277. return NextSwitch.nextSwitch;
  4278. }*/
  4279.  
  4280. init() {
  4281. if (this.inited) return;
  4282. this.inited = true;
  4283. let self = this;
  4284. this.cssText = `
  4285. #pagetual-nextSwitch {
  4286. position: fixed;
  4287. top: 10px;
  4288. left: calc(50% - 160px);
  4289. background: aliceblue;
  4290. padding: 10px;
  4291. border-radius: 5px;
  4292. text-align: center;
  4293. opacity: 0.95;
  4294. color: #161616;
  4295. z-index: 2147483647;
  4296. font-size: 16px;
  4297. box-shadow: rgb(0 0 0) 0px 0px 10px;
  4298. }
  4299. #pagetual-nextSwitch>.title {
  4300. margin: -5px 45px 10px 45px;
  4301. font-size: 20px;
  4302. font-weight: bold;
  4303. border-bottom: 1px solid black;
  4304. user-select: none;
  4305. color: orangered;
  4306. }
  4307. #pagetual-nextSwitch>.group {
  4308. display: flex;
  4309. flex-direction: column;
  4310. }
  4311. #pagetual-nextSwitch>.group>span {
  4312. color: #161616;
  4313. cursor: pointer;
  4314. margin: 3px;
  4315. font-size: larger;
  4316. }
  4317. #pagetual-nextSwitch>.group>span:hover {
  4318. color: red;
  4319. }
  4320. #pagetual-nextSwitch>.group>span.current {
  4321. border: 2px dotted red;
  4322. border-radius: 10px;
  4323. }
  4324. #pagetual-nextSwitch>.closeSwitch {
  4325. position: absolute;
  4326. top: 3px;
  4327. right: 10px;
  4328. background: none;
  4329. border: none;
  4330. vertical-align: top;
  4331. transition: transform .15s ease-in-out;
  4332. float: right;
  4333. cursor: pointer;
  4334. }
  4335. #pagetual-nextSwitch svg {
  4336. width: 30px;
  4337. height: 30px;
  4338. vertical-align: middle;
  4339. fill: #161616;
  4340. overflow: hidden;
  4341. }
  4342. #pagetual-nextSwitch button:hover {
  4343. transform: scale(1.2);
  4344. }
  4345. `;
  4346. let frame = document.createElement("div");
  4347. frame.id = "pagetual-nextSwitch";
  4348. frame.innerHTML = createHTML(`
  4349. <div class="title">${i18n("nextSwitch")}</div>
  4350. <button type="button" class="closeSwitch">
  4351. <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2754">
  4352. <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">
  4353. </path>
  4354. </svg>
  4355. </button>
  4356. <div class="group"></div>
  4357. `);
  4358. let group = frame.querySelector(".group");
  4359. let closeBtn = frame.querySelector(".closeSwitch");
  4360. closeBtn.addEventListener("click", e => {
  4361. self.close();
  4362. }, true);
  4363. this.frame = frame;
  4364. let currentSpan;
  4365. ruleParser.curSiteRule.nextLink.forEach((link, i) => {
  4366. let span = document.createElement("span");
  4367. let target = getElement(link, document);
  4368. let index = "<b>" + (i + 1) + "</b>: ";
  4369. if (target) {
  4370. let targetInner = target.innerText.trim();
  4371. span.innerHTML = index + (targetInner || link);
  4372. } else {
  4373. span.innerHTML = index + "Not Found";
  4374. }
  4375. span.title = link;
  4376. span.addEventListener("click", e => {
  4377. if (currentSpan) currentSpan.classList.remove("current");
  4378. span.classList.add("current");
  4379. currentSpan = span;
  4380. nextIndex = i;
  4381. setListData("nextSwitch", location.host, nextIndex === 0 ? "" : nextIndex);
  4382. ruleParser.curUrl += "#pagetual";
  4383. ruleParser.oldUrl = ruleParser.curUrl;
  4384. autoLoadNum = -1;
  4385. if (!ruleParser.nextLinkHref) {
  4386. isLoading = false;
  4387. }
  4388. ruleParser.getNextLink(ruleParser.pageDoc || document);
  4389. self.close();
  4390. }, true);
  4391. if (i == nextIndex) {
  4392. span.classList.add("current");
  4393. currentSpan = span;
  4394. }
  4395. group.appendChild(span);
  4396. });
  4397. }
  4398.  
  4399. start() {
  4400. this.init();
  4401. if (!this.styleEle || !this.styleEle.parentNode) {
  4402. this.styleEle = _GM_addStyle(this.cssText);
  4403. }
  4404. document.documentElement.appendChild(this.frame);
  4405. }
  4406.  
  4407. close() {
  4408. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  4409. }
  4410. }
  4411. const nextSwitch = new NextSwitch();
  4412.  
  4413. class Picker {
  4414. //static picker;
  4415. constructor() {
  4416. this.inited = false;
  4417. }
  4418.  
  4419. /*static getInstance() {
  4420. if (!Picker.picker) {
  4421. Picker.picker = new Picker();
  4422. }
  4423. return Picker.picker;
  4424. }*/
  4425.  
  4426. init() {
  4427. if (this.inited) return;
  4428. this.inited = true;
  4429. let self = this;
  4430. this.signList = [];
  4431. this.cssText = `
  4432. body.pagetual-picker,
  4433. body.pagetual-picker *:hover,
  4434. body.pagetual-picker a:hover {
  4435. cursor: crosshair !important;
  4436. }
  4437. #pagetual-picker {
  4438. position: fixed;
  4439. top: 10px;
  4440. left: calc(50% - 178px);
  4441. background: aliceblue;
  4442. padding: 10px;
  4443. border-radius: 5px;
  4444. text-align: center;
  4445. opacity: 0.95;
  4446. color: #161616;
  4447. z-index: 2147483646;
  4448. font-size: 16px;
  4449. overflow: hidden;
  4450. box-shadow: rgb(0 0 0) 0px 0px 10px;
  4451. }
  4452. #pagetual-picker * {
  4453. margin: 0;
  4454. padding: 0;
  4455. font-family: Times New Roman;
  4456. overflow: initial;
  4457. user-select: none;
  4458. line-height: unset;
  4459. min-width: unset;
  4460. min-height: unset;
  4461. }
  4462. #pagetual-picker>.title {
  4463. margin: -5px 45px 10px 45px;
  4464. font-size: 20px;
  4465. font-weight: bold;
  4466. cursor: pointer;
  4467. border-bottom: 1px solid black;
  4468. user-select: none;
  4469. color: orangered;
  4470. height: initial;
  4471. width: initial;
  4472. position: initial;
  4473. transition: transform .3s ease;
  4474. }
  4475. #pagetual-picker>.title:hover {
  4476. transform: scale(1.1);
  4477. }
  4478. #pagetual-picker button {
  4479. background: none;
  4480. border: none;
  4481. vertical-align: top;
  4482. transition: transform .15s ease-in-out;
  4483. float: right;
  4484. cursor: pointer;
  4485. overflow: hidden;
  4486. background-color: unset!important;
  4487. }
  4488. #pagetual-picker button:hover {
  4489. transform: scale(1.2);
  4490. }
  4491. #pagetual-picker>.closePicker {
  4492. position: absolute;
  4493. top: 3px;
  4494. right: 10px;
  4495. }
  4496. #pagetual-picker>.logoIcon {
  4497. position: absolute;
  4498. top: 3px;
  4499. left: 10px;
  4500. }
  4501. #pagetual-picker>.logoIcon.showSign>svg>path {
  4502. fill: gray!important;
  4503. }
  4504. #pagetual-picker textarea{
  4505. display: inline-block;
  4506. width: calc(100% - 65px);
  4507. height: 20px;
  4508. min-width: 250px;
  4509. max-width: calc(65vw - 50px);
  4510. min-height: unset;
  4511. max-height: unset;
  4512. padding: 6px 12px;
  4513. font-size: 16px;
  4514. font-weight: 400;
  4515. line-height: 1.5;
  4516. color: #495057;
  4517. background-color: #fff;
  4518. background-clip: padding-box;
  4519. border: 1px solid #ced4da;
  4520. border-radius: 4px;
  4521. transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
  4522. box-sizing: content-box;
  4523. margin-right: 5px;
  4524. resize: both;
  4525. box-shadow: 0 1px 5px 1px #ddd;
  4526. overflow-wrap: anywhere;
  4527. }
  4528. #pagetual-picker textarea:focus {
  4529. color: black;
  4530. background-color: #fff;
  4531. border-color: #80bdff;
  4532. outline: 0;
  4533. box-shadow: 0 0 0 3.2px rgb(0 123 255 / 25%);
  4534. }
  4535. #pagetual-picker [type=checkbox],
  4536. #pagetual-picker [type=radio] {
  4537. line-height: 20px;
  4538. height: 25px;
  4539. width: 25px;
  4540. margin-left: 5px;
  4541. vertical-align: middle;
  4542. appearance: auto;
  4543. display: inline-block;
  4544. position: initial;
  4545. }
  4546. #pagetual-picker [type=checkbox]:after,
  4547. #pagetual-picker [type=radio]:after,
  4548. #pagetual-picker [type=checkbox]:before,
  4549. #pagetual-picker [type=radio]:before {
  4550. border: none;
  4551. background: none;
  4552. }
  4553. #pagetual-picker label {
  4554. font-size: 18px;
  4555. line-height: 25px;
  4556. vertical-align: middle;
  4557. display: inline-block;
  4558. color: black;
  4559. position: initial;
  4560. cursor: pointer;
  4561. }
  4562. #pagetual-picker .bottom {
  4563. text-align: left;
  4564. margin: 10px 0;
  4565. width: 100%;
  4566. }
  4567. #pagetual-picker .bottom>button {
  4568. float: right;
  4569. }
  4570. #pagetual-picker svg {
  4571. width: 30px;
  4572. height: 30px;
  4573. vertical-align: middle;
  4574. fill: #161616;
  4575. overflow: hidden;
  4576. }
  4577. #pagetual-picker svg * {
  4578. pointer-events: none;
  4579. }
  4580. #pagetual-picker .allpath {
  4581. font-size: 18px;
  4582. margin: 10px auto;
  4583. max-width: 330px;
  4584. word-break: break-all;
  4585. cursor: context-menu;
  4586. overflow: hidden;
  4587. max-height: 42px;
  4588. -moz-transition:max-height 1s ease-in;
  4589. -webkit-transition:max-height 1s ease-in;
  4590. transition:max-height 1s ease-in;
  4591. color: black;
  4592. }
  4593. #pagetual-picker .allpath:hover {
  4594. max-height: calc(100vh - 130px);
  4595. overflow: auto;
  4596. }
  4597. #pagetual-picker .allpath>span.path {
  4598. cursor: pointer;
  4599. }
  4600. #pagetual-picker .allpath>span.path:hover {
  4601. opacity: 0.6;
  4602. }
  4603. #pagetual-picker .allpath>span.path:hover,
  4604. #pagetual-picker .allpath>span.path.checked {
  4605. color: orangered;
  4606. }
  4607. #pagetual-picker .moreConfig {
  4608. display: flex;
  4609. justify-content: space-between;
  4610. border-top: 1px solid;
  4611. padding-top: 10px;
  4612. width: 100%;
  4613. }
  4614. #pagetual-picker .command {
  4615. width: 100%;
  4616. color: black!important;
  4617. text-align: center;
  4618. font-size: large;
  4619. margin-top: 10px;
  4620. box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.12);
  4621. border-radius: 5px;
  4622. }
  4623. #pagetual-picker .command:hover {
  4624. color: orangered;
  4625. }
  4626. #pagetual-picker #showDetail {
  4627. float: initial;
  4628. margin-top: 10px;
  4629. }
  4630. #pagetual-picker.showDetail #showDetail {
  4631. float: right;
  4632. }
  4633. #pagetual-picker #showDetail>svg {
  4634. -moz-transition:transform 0.3s ease;
  4635. -webkit-transition:transform 0.3s ease;
  4636. transition:transform 0.3 ease;
  4637. }
  4638. #pagetual-picker.showDetail #showDetail>svg {
  4639. transform: rotate(180deg);
  4640. }
  4641. #pagetual-picker .tempRule {
  4642. display: none;
  4643. margin-top: 10px;
  4644. height: 300px;
  4645. min-height: 150px;
  4646. }
  4647. #pagetual-picker.showDetail .tempRule {
  4648. display: inline-block;
  4649. word-break: break-all;
  4650. }
  4651. #pagetual-picker #saveDetail {
  4652. display: none;
  4653. position: absolute;
  4654. bottom: 10px;
  4655. right: 8px;
  4656. }
  4657. #pagetual-picker.showDetail #saveDetail {
  4658. display: inline-block;
  4659. }
  4660. #pagetual-picker #saveDetail svg {
  4661. width: 35px;
  4662. height: 35px;
  4663. }
  4664. #pagetual-picker .addProp {
  4665. display: none;
  4666. flex-direction: column;
  4667. position: absolute;
  4668. bottom: 45px;
  4669. right: 12px;
  4670. }
  4671. #pagetual-picker.showDetail .addProp {
  4672. display: flex;
  4673. }
  4674. #pagetual-picker .addProp>button {
  4675. font-size: 30px;
  4676. font-family: Arial,sans-serif;
  4677. line-height: 35px;
  4678. color: #161616;
  4679. }
  4680. #pagetual-picker #edit{
  4681. -webkit-animation: jumpAnimation .6s 5;
  4682. animation: jumpAnimation .6s 5;
  4683. }
  4684. @keyframes jumpAnimation {
  4685. 0% {
  4686. transform: scale(1) translateY(0);
  4687. animation-timing-function: ease-out;
  4688. }
  4689. 50% {
  4690. transform: scale(1.2) translateY(-5px);
  4691. animation-timing-function: ease-in;
  4692. }
  4693. 100% {
  4694. transform: scale(1) translateY(0);
  4695. animation-timing-function: ease-out;
  4696. }
  4697. }
  4698. @-webkit-keyframes jumpAnimation {
  4699. 0% {
  4700. -webkit-transform: scale(1) translateY(0);
  4701. animation-timing-function: ease-out;
  4702. }
  4703. 50% {
  4704. -webkit-transform: scale(1.2) translateY(-5px);
  4705. animation-timing-function: ease-in;
  4706. }
  4707. 100% {
  4708. -webkit-transform: scale(1) translateY(0);
  4709. animation-timing-function: ease-out;
  4710. }
  4711. }
  4712. `;
  4713. this.mainSignDiv = this.createSignDiv();
  4714. this.allSignDiv = [];
  4715. let frame = document.createElement("div");
  4716. frame.id = "pagetual-picker";
  4717. frame.innerHTML = createHTML(`
  4718. <button title="Pagetual" type="button" class="logoIcon">
  4719. <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>
  4720. </button>
  4721. <div class="title" title="${i18n("configure")}">${i18n("picker")}</div>
  4722. <button title="${i18n("closePicker")}" type="button" class="closePicker">
  4723. <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>
  4724. </button>
  4725. <div class="allpath" title="${i18n("switchSelector")}"></div>
  4726. <div>
  4727. <textarea class="selector" spellcheck="false" name="selector" placeholder="${i18n("pickerPlaceholder")}"></textarea>
  4728. <button id="check" title="${i18n("pickerCheck")}" type="button">
  4729. <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>
  4730. </button>
  4731. </div>
  4732. <div class="bottom">
  4733. <input name="xpath" id="checkbox_id" type="checkbox" />
  4734. <label for="checkbox_id">XPath</label>
  4735. <button id="edit" title="${i18n("gotoEdit")}" type="button">
  4736. <svg viewBox="0 0 1024 1024" style="color: orangered;fill: orangered;" version="1.1" xmlns="http://www.w3.org/2000/svg">
  4737. <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">
  4738. </path>
  4739. </svg>
  4740. </button>
  4741. </div>
  4742. <div class="moreConfig">
  4743. <div title="${i18n('forceStateIframe')}">
  4744. <input name="forceState" id="forceStateIframe" type="radio" />
  4745. <label for="forceStateIframe">${i18n('iframe')}</label>
  4746. </div>
  4747. <div title="${i18n('forceStateDynamic')}">
  4748. <input name="forceState" id="forceStateDynamic" type="radio" />
  4749. <label for="forceStateDynamic">${i18n('dynamic')}</label>
  4750. </div>
  4751. <div title="${i18n('forceStateDisable')}">
  4752. <input name="forceState" id="forceStateDisable" type="radio" />
  4753. <label for="forceStateDisable">${i18n('disable')}</label>
  4754. </div>
  4755. </div>
  4756. <button id="nextSwitch" class="command" title="${i18n("nextSwitch")}" type="button">${i18n("nextSwitch")}</button>
  4757. <button id="loadNow" class="command" title="${i18n("loadNow")}" type="button">${i18n("loadNow")}</button>
  4758. <button id="autoScroll" class="command" title="${i18n("toggleAutoScroll")}" type="button"></button>
  4759. <button id="ruleRequest" class="command" title="${i18n("ruleRequest")}" type="button">${i18n("ruleRequest")}</button>
  4760. <div>
  4761. <textarea class="tempRule" spellcheck="false" placeholder="{Rule object}" title="Rule for current site"></textarea>
  4762. <button id="showDetail" title="" type="button">
  4763. <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>
  4764. </button>
  4765. <div class="addProp">
  4766. <button id="addOtherProp" title="${i18n("addOtherProp")}" type="button">+</button>
  4767. <button id="addNextSelector" title="${i18n("addNextSelector")}" type="button">></button>
  4768. <button id="addPageSelector" title="${i18n("addPageSelector")}" type="button">❏</button>
  4769. </div>
  4770. <button id="saveDetail" title="${i18n("save")}" type="button">
  4771. <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>
  4772. </button>
  4773. </div>
  4774. `);
  4775. let forceStateIframe = frame.querySelector("#forceStateIframe");//forceState 1 禁用 2 强嵌 3 动态
  4776. let forceStateDynamic = frame.querySelector("#forceStateDynamic");
  4777. let forceStateDisable = frame.querySelector("#forceStateDisable");
  4778. let clickRadio = e => {
  4779. let radio = e.currentTarget.querySelector('input');
  4780. if (radio.checked) {
  4781. forceState = "";
  4782. } else {
  4783. switch (radio.id) {
  4784. case "forceStateIframe":
  4785. forceState = 2;
  4786. break;
  4787. case "forceStateDynamic":
  4788. forceState = 3;
  4789. break;
  4790. case "forceStateDisable":
  4791. forceState = 1;
  4792. break;
  4793. default:
  4794. return;
  4795. }
  4796. }
  4797. setListData("forceState", location.host, forceState);
  4798. self.close();
  4799. setTimeout(() => {
  4800. location.reload();
  4801. }, 500);
  4802. };
  4803. forceStateIframe.parentNode.addEventListener("mousedown", clickRadio);
  4804. forceStateDynamic.parentNode.addEventListener("mousedown", clickRadio);
  4805. forceStateDisable.parentNode.addEventListener("mousedown", clickRadio);
  4806. if (forceState == 1) forceStateDisable.checked = true;
  4807. else if (forceState == 2) forceStateIframe.checked = true;
  4808. else if (forceState == 3) forceStateDynamic.checked = true;
  4809. let closeBtn = frame.querySelector(".closePicker");
  4810. let logoBtn = frame.querySelector(".logoIcon");
  4811. let title = frame.querySelector(".title");
  4812. let allpath = frame.querySelector(".allpath");
  4813. let selectorInput = frame.querySelector(".selector");
  4814. let xpath = frame.querySelector("#checkbox_id");
  4815. let checkBtn = frame.querySelector("#check");
  4816. let editBtn = frame.querySelector("#edit");
  4817. let nextSwitchBtn = frame.querySelector("#nextSwitch");
  4818. let autoScrollBtn = frame.querySelector("#autoScroll");
  4819. let loadNow = frame.querySelector("#loadNow");
  4820. let tempRule = frame.querySelector(".tempRule");
  4821. let showDetailBtn = frame.querySelector("#showDetail");
  4822. let saveDetailBtn = frame.querySelector("#saveDetail");
  4823. let addOtherProp = frame.querySelector("#addOtherProp");
  4824. let addNextSelector = frame.querySelector("#addNextSelector");
  4825. let addPageSelector = frame.querySelector("#addPageSelector");
  4826. let ruleRequestBtn = frame.querySelector("#ruleRequest");
  4827. ruleRequestBtn.addEventListener("click", e => {
  4828. _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});
  4829. }, true);
  4830. autoScrollBtn.addEventListener("click", e => {
  4831. self.close();
  4832. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  4833. autoScroll = parseInt(autoScroll) || 0;
  4834. if (autoScroll < 0) autoScroll = 0;
  4835. if (autoScroll && autoScroll != autoScrollRate) {
  4836. autoScrollRate = autoScroll;
  4837. storage.setItem("autoScrollRate", autoScrollRate);
  4838. }
  4839. setListData("autoScroll", location.host + location.pathname, autoScroll);
  4840. startAutoScroll();
  4841. }, true);
  4842. addOtherProp.addEventListener("click", e => {
  4843. let propName = prompt(i18n("propName"), "author");
  4844. if (!propName) return;
  4845. let propValue = prompt(i18n("propValue"));
  4846. if (!propValue) return;
  4847. if (propValue === "true") propValue = true;
  4848. else if (propValue === "false") propValue = false;
  4849. else if (/^\d+$/.test(propValue)) propValue = parseInt(propValue);
  4850. if (propName === "author" && propValue) {
  4851. author = propValue;
  4852. storage.setItem("author", propValue);
  4853. }
  4854. let editTemp = self.getTempRule();
  4855. if (!editTemp) return;
  4856. editTemp[propName] = propValue;
  4857. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  4858. }, true);
  4859. addNextSelector.addEventListener("click", e => {
  4860. let editTemp = self.getTempRule();
  4861. if (!editTemp) return;
  4862. let selector = self.selectorInput.value;
  4863. if (selector) {
  4864. editTemp.nextLink = selector;
  4865. }
  4866. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  4867. }, true);
  4868. addPageSelector.addEventListener("click", e => {
  4869. let editTemp = self.getTempRule();
  4870. if (!editTemp) return;
  4871. let selector = self.selectorInput.value;
  4872. if (selector) {
  4873. editTemp.pageElement = selector;
  4874. }
  4875. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  4876. }, true);
  4877. showDetailBtn.addEventListener("click", e => {
  4878. frame.classList.toggle("showDetail");
  4879. }, true);
  4880. saveDetailBtn.addEventListener("click", e => {
  4881. let editTemp = self.getTempRule(true);
  4882. if (tempRule.value && !editTemp) {
  4883. return;
  4884. }
  4885. if(!ruleParser.customRules) {
  4886. ruleParser.customRules = [];
  4887. }
  4888. ruleParser.customRules = ruleParser.customRules.filter(item => {return item.url != editTemp.url || item.name != editTemp.name});
  4889. if (tempRule.value) {
  4890. ruleParser.customRules.unshift(editTemp);
  4891. ruleParser.curSiteRule = editTemp;
  4892. } else {
  4893. ruleParser.curSiteRule = {};
  4894. isPause = true;
  4895. }
  4896. storage.setItem("customRules", ruleParser.customRules);
  4897. if (ruleParser.hpRules && ruleParser.curSiteRule && !ruleParser.curSiteRule.smart) {
  4898. ruleParser.addToHpRules(true);
  4899. }
  4900. if (window.confirm(i18n("reloadPage"))) {
  4901. setTimeout(() => {location.reload()}, 100);
  4902. }
  4903. }, true);
  4904. nextSwitchBtn.addEventListener("click", e => {
  4905. self.close();
  4906. nextSwitch.start();
  4907. }, true);
  4908. loadNow.addEventListener("click", e => {
  4909. self.close();
  4910. let loadNum = window.prompt(i18n("loadConfirm"), "1");
  4911. if (loadNum === "" || loadNum === null) return;
  4912. autoLoadNum = Math.abs(parseInt(loadNum));
  4913. nextPage();
  4914. }, true);
  4915. closeBtn.addEventListener("click", e => {
  4916. self.close();
  4917. }, true);
  4918. this.showSign = true;
  4919. logoBtn.addEventListener("click", e => {
  4920. logoBtn.classList.toggle("showSign");
  4921. self.showSign = !self.showSign;
  4922. getBody(document).classList.toggle("pagetual-picker");
  4923. }, true);
  4924. let moving = false;
  4925. let initX = 0, initY = 0, initPos = {x: 0, y: 0};
  4926. let moveHanlder = e => {
  4927. if (moving) {
  4928. frame.style.left = e.clientX - initX + "px";
  4929. frame.style.top = e.clientY - initY + "px";
  4930. e.stopPropagation();
  4931. e.preventDefault();
  4932. } else if(Math.abs(e.clientX - initPos.x) + Math.abs(e.clientY - initPos.y) > 20) {
  4933. moving = true;
  4934. }
  4935. };
  4936. let upHanlder = e => {
  4937. if (moving) {
  4938. moving = false;
  4939. } else {
  4940. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  4941. }
  4942. document.removeEventListener("mousemove", moveHanlder, true);
  4943. title.removeEventListener("mouseup", upHanlder, true);
  4944. e.stopPropagation();
  4945. e.preventDefault();
  4946. };
  4947. title.addEventListener("mousedown", e => {
  4948. initPos = {x: e.clientX, y: e.clientY};
  4949. initX = e.clientX - parseInt(getComputedStyle(frame).left);
  4950. initY = e.clientY - parseInt(getComputedStyle(frame).top);
  4951. document.addEventListener("mousemove", moveHanlder, true);
  4952. title.addEventListener("mouseup", upHanlder, true);
  4953. });
  4954. frame.addEventListener("mouseenter", e => {
  4955. if (!self.showSign || moving) return;
  4956. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  4957. self.checkInputSelector(false);
  4958. });
  4959. frame.addEventListener("mouseleave", e => {
  4960. if (!self.showSign) {
  4961. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  4962. self.clearSigns();
  4963. return;
  4964. }
  4965. if (moving) return;
  4966. document.documentElement.appendChild(self.mainSignDiv);
  4967. self.clearSigns();
  4968. });
  4969. checkBtn.addEventListener("click", e => {
  4970. self.checkInputSelector();
  4971. if (this.selectorInput.value && self.foundEle) {
  4972. debug(self.foundEle);
  4973. self.foundEle[0].scrollIntoView({ behavior: "smooth" });
  4974. _GM_setClipboard(this.selectorInput.value);
  4975. showTips(i18n("copied"));
  4976. } else showTips("Null");
  4977. });
  4978. xpath.addEventListener("click", e => {
  4979. if (!selectorInput.value) {
  4980. self.setSelectorDiv("");
  4981. return;
  4982. }
  4983. let element = getElement(selectorInput.value, document);
  4984. let selector = self.getSelectorFromEle(element);
  4985. selectorInput.value = selector;
  4986. self.setSelectorDiv(selector);
  4987. });
  4988. editBtn.addEventListener("click", e => {
  4989. rulesData.editTemp = self.getTempRule();
  4990. storage.setItem("rulesData", rulesData);
  4991. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  4992. });
  4993. editBtn.oncontextmenu = e => {
  4994. e.preventDefault();
  4995. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  4996. };
  4997. this.frame = frame;
  4998. this.xpath = xpath;
  4999. this.allpath = allpath;
  5000. this.selectorInput = selectorInput;
  5001. this.nextSwitchBtn = nextSwitchBtn;
  5002. this.autoScrollBtn = autoScrollBtn;
  5003. this.loadNow = loadNow;
  5004. this.tempRule = tempRule;
  5005. this.logoBtn = logoBtn;
  5006. let setTitleTimer;
  5007. this.moveHandler = e => {
  5008. if (!self.showSign || e.target === document) return;
  5009. let target = self.getTarget(e.target);
  5010. self.adjustSignDiv(self.mainSignDiv, target);
  5011. clearTimeout(setTitleTimer);
  5012. setTitleTimer = setTimeout(() => {
  5013. if (self.inPicker && target.hasAttributes()) {
  5014. let title = target.nodeName.toLowerCase() + "\n";
  5015. for (const attr of target.attributes) {
  5016. title += `【${attr.name}】${attr.value ? " ➡️ " + attr.value : ""}\n`;
  5017. }
  5018. getBody(document).title = title;
  5019. }
  5020. }, 100);
  5021. };
  5022. this.clickHandler = e => {
  5023. if (!self.showSign) return;
  5024. if (self.inPicker) {
  5025. e.stopPropagation();
  5026. e.preventDefault();
  5027. }
  5028. let target = self.getTarget(e.target);
  5029. let selector = self.getSelectorFromEle(target);
  5030. selectorInput.value = selector;
  5031. self.setSelectorDiv(selector);
  5032. };
  5033. }
  5034.  
  5035. getTempRule(detail) {
  5036. if (this.tempRule.value) {
  5037. try {
  5038. this.editTemp = JSON.parse(this.tempRule.value);
  5039. } catch (e) {
  5040. this.editTemp = null;
  5041. if (detail) {
  5042. let pos = e && e.message && e.message.match(/position (\d+)/);
  5043. if (pos) {
  5044. pos = parseInt(pos[1]);
  5045. this.tempRule.value = this.tempRule.value.slice(0, pos) + "➡️" + this.tempRule.value.slice(pos);
  5046. }
  5047. showTips(i18n("errorJson"));
  5048. return null;
  5049. }
  5050. }
  5051. }
  5052. if (!this.editTemp) {
  5053. if (ruleParser.curSiteRule.url && !ruleParser.curSiteRule.smart) {
  5054. this.editTemp = ruleParser.curSiteRule;
  5055. } else {
  5056. this.editTemp = {
  5057. name: document.title,
  5058. url: "^" + (location.origin + location.pathname).replace(/[^\/]*$/, "").replace(/^https?/, "https?").replace(/\./g, "\\."),
  5059. example: location.href
  5060. };
  5061. if (author) this.editTemp.author = author;
  5062. }
  5063. delete this.editTemp.from;
  5064. delete this.editTemp.type;
  5065. delete this.editTemp.updatedAt;
  5066. }
  5067. if (this.selectorInput.value && (!this.frame.classList.contains("showDetail") || !this.editTemp || !this.editTemp.pageElement)) {
  5068. if (this.foundEle && this.foundEle.length === 1) {
  5069. let foundEleRect = this.foundEle[0].getBoundingClientRect();
  5070. if (foundEleRect.height < 100) {
  5071. showTips("Next Link", "", 500);
  5072. this.editTemp.nextLink = this.selectorInput.value;
  5073. return this.editTemp;
  5074. }
  5075. }
  5076. showTips("Page Element", "", 500);
  5077. this.editTemp.pageElement = this.selectorInput.value;
  5078. }
  5079. return this.editTemp;
  5080. }
  5081.  
  5082. getTarget(ele) {
  5083. while (ele.parentNode && (ele.offsetWidth === 0 || ele.offsetHeight === 0)) {
  5084. ele = ele.parentNode;
  5085. }
  5086. return ele;
  5087. }
  5088.  
  5089. close() {
  5090. this.clearSigns();
  5091. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  5092. if (this.mainSignDiv.parentNode) this.mainSignDiv.parentNode.removeChild(this.mainSignDiv);
  5093. getBody(document).classList.remove("pagetual-picker");
  5094. getBody(document).removeEventListener("mousemove", this.moveHandler, true);
  5095. getBody(document).removeEventListener("click", this.clickHandler, true);
  5096. getBody(document).title = "";
  5097. this.inPicker = false;
  5098. }
  5099.  
  5100. setImportant(ele, prop, value) {
  5101. ele.style.setProperty(prop, value, "important");
  5102. }
  5103.  
  5104. createSignDiv() {
  5105. let signDiv = document.createElement("div");
  5106. this.setImportant(signDiv, "position", "absolute");
  5107. this.setImportant(signDiv, "pointer-events", "none");
  5108. this.setImportant(signDiv, "z-index", "2147483645");
  5109. this.setImportant(signDiv, "background", "rgba(120, 170, 210, 0.6)");
  5110. this.setImportant(signDiv, "transition", "all 0.15s ease-out");
  5111. this.setImportant(signDiv, "box-shadow", "rgb(0 0 0) 0px 0px 3px 0px");
  5112. return signDiv;
  5113. }
  5114.  
  5115. adjustSignDiv(div, target) {
  5116. let rect = target.getBoundingClientRect();
  5117. this.setImportant(div, "width", rect.width + "px");
  5118. this.setImportant(div, "height", rect.height + "px");
  5119. this.setImportant(div, "left", rect.left + window.scrollX + "px");
  5120. this.setImportant(div, "top", rect.top + window.scrollY + "px");
  5121. }
  5122.  
  5123. getSelectorFromEle(ele) {
  5124. return this.xpath.checked ? createXPathFromElement(ele) : geneSelector(ele, true);
  5125. }
  5126.  
  5127. fillTempRuleTextarea() {
  5128. if (!this.frame.classList.contains("showDetail") || !this.editTemp || !this.editTemp.pageElement) this.tempRule.value = JSON.stringify(this.getTempRule(), null, 4);
  5129. }
  5130.  
  5131. setSelectorDiv(selector) {
  5132. let self = this;
  5133. this.allpath.innerHTML = createHTML("");
  5134. if (selector) {
  5135. if (this.xpath.checked) {
  5136. let span = document.createElement("span");
  5137. span.innerText = selector;
  5138. span.addEventListener("click", e => {
  5139. self.selectorInput.value = selector;
  5140. self.checkInputSelector();
  5141. }, true);
  5142. this.allpath.appendChild(span);
  5143. } else {
  5144. selector.split(">").forEach((item, index) => self.geneSelectorItem(item, index));
  5145. }
  5146. }
  5147. this.checkInputSelector();
  5148. }
  5149.  
  5150. geneSelectorItem(item, index) {
  5151. let self = this;
  5152. item = item.trim();
  5153. if (!item) return;
  5154. if (index !== 0) {
  5155. let span = document.createElement("span");
  5156. span.innerText = " > ";
  5157. this.allpath.appendChild(span);
  5158. }
  5159. let span = document.createElement("span");
  5160. span.className = "path";
  5161. span.innerText = item;
  5162. span.addEventListener("click", e => {
  5163. let selector = "";
  5164. let target = e.target;
  5165. while (target) {
  5166. selector = target.innerText + selector;
  5167. target = target.previousElementSibling;
  5168. }
  5169. self.selectorInput.value = selector;
  5170. self.checkInputSelector();
  5171. if (self.checkedPath) {
  5172. self.checkedPath.classList.remove("checked");
  5173. }
  5174. span.classList.add("checked");
  5175. self.checkedPath = span;
  5176. }, true);
  5177. this.allpath.appendChild(span);
  5178. }
  5179.  
  5180. checkInputSelector(fill = true) {
  5181. let self = this;
  5182. this.clearSigns();
  5183. if (!this.selectorInput.value) return;
  5184. let eles = getAllElements(this.selectorInput.value, document);
  5185. this.foundEle = null;
  5186. if (eles && eles.length > 0) {
  5187. this.foundEle = eles;
  5188. eles.forEach(ele => {
  5189. let sign = self.createSignDiv();
  5190. document.documentElement.appendChild(sign);
  5191. self.adjustSignDiv(sign, ele);
  5192. self.signList.push(sign);
  5193. });
  5194. if (fill) this.fillTempRuleTextarea();
  5195. }
  5196. }
  5197.  
  5198. clearSigns() {
  5199. this.signList.forEach(sign => {
  5200. if (sign.parentNode) sign.parentNode.removeChild(sign);
  5201. });
  5202. this.signList = [];
  5203. }
  5204.  
  5205. start() {
  5206. this.init();
  5207. if (this.inPicker) return;
  5208. this.inPicker = true;
  5209. if (!this.styleEle || !this.styleEle.parentNode) {
  5210. this.styleEle = _GM_addStyle(this.cssText);
  5211. }
  5212. document.documentElement.appendChild(this.frame);
  5213. document.documentElement.appendChild(this.mainSignDiv);
  5214. getBody(document).classList.add("pagetual-picker");
  5215.  
  5216. this.logoBtn.classList.remove("showSign");
  5217. this.showSign = true;
  5218.  
  5219. getBody(document).addEventListener("mousemove", this.moveHandler, true);
  5220. getBody(document).addEventListener("click", this.clickHandler, true);
  5221. this.xpath.checked = isXPath(ruleParser.curSiteRule.pageElement);
  5222. this.tempRule.value = "";
  5223. this.editTemp = null;
  5224. this.frame.classList.remove("showDetail");
  5225.  
  5226. this.loadNow.style.display = ruleParser.nextLinkHref ? "block" : "none";
  5227. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  5228. this.nextSwitchBtn.style.display = "block";
  5229. } else {
  5230. this.nextSwitchBtn.style.display = "none";
  5231. }
  5232. this.autoScrollBtn.innerText = i18n(autoScroll ? "disableAutoScroll" : "enableAutoScroll");
  5233.  
  5234. let pageElementSel = ruleParser.curSiteRule.pageElement || "";
  5235. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  5236. pageElementSel = pageElementSel[nextIndex < pageElementSel.length ? nextIndex : 0];
  5237. }
  5238. this.setSelectorDiv(pageElementSel);
  5239. this.fillTempRuleTextarea();
  5240. }
  5241. }
  5242. const picker = new Picker();
  5243.  
  5244. var editor, editorChanged = false, customRulesInput;
  5245. function createEdit() {
  5246. var options = {
  5247. mode: 'code',
  5248. modes: ['code', 'tree'],
  5249. templates: [
  5250. {
  5251. text: 'New site',
  5252. title: 'Insert a new site',
  5253. className: 'jsoneditor-type-object',
  5254. field: 'SiteTemplate',
  5255. value: {
  5256. 'name': 'Site name',
  5257. 'url': 'Site url'
  5258. }
  5259. }
  5260. ],
  5261. schema: {
  5262. "title": "Sites data",
  5263. "description": "Object containing site config",
  5264. "type": "array",
  5265. "items": {
  5266. "type": 'object',
  5267. "properties": {
  5268. "name": {
  5269. "title": "Site Name",
  5270. "description": "The site's name.",
  5271. "examples": [
  5272. "Google"
  5273. ],
  5274. "type": "string"
  5275. },
  5276. "url": {
  5277. "title": "Site Url",
  5278. "description": "The Regexp of site's url.",
  5279. "examples": [
  5280. "^https:\/\/yande\\.re\/"
  5281. ],
  5282. "type": "string"
  5283. }
  5284. },
  5285. "required": ["name", "url"]
  5286. }
  5287. },
  5288. onChange: () => {
  5289. editorChanged = true;
  5290. }
  5291. };
  5292. setTimeout(() => {
  5293. var container = document.getElementById("jsoneditor");
  5294. container.style.height = '800px';
  5295. container.innerHTML = "";
  5296. try {
  5297. editor = new _unsafeWindow.JSONEditor(container, options);
  5298. editor.set(ruleParser.customRules);
  5299. } catch (e) {
  5300. editor = null;
  5301. container.style.display = 'none';
  5302. customRulesInput.style.display = "";
  5303. }
  5304. }, 500);
  5305. }
  5306.  
  5307. function checkGuidePage(href) {
  5308. if (guidePage.test(href)) {
  5309. if (typeof _unsafeWindow.JSONEditor !== 'undefined') {
  5310. createEdit();
  5311. } else {
  5312. let timeout = 30;
  5313. let checkEditorReady = setInterval(() => {
  5314. if (typeof _unsafeWindow.JSONEditor !== 'undefined') {
  5315. createEdit();
  5316. clearInterval(checkEditorReady);
  5317. } else if (timeout-- <= 0) {
  5318. editor = null;
  5319. customRulesInput.style.display = "";
  5320. clearInterval(checkEditorReady);
  5321. }
  5322. }, 100);
  5323. }
  5324. return true;
  5325. }
  5326. return false;
  5327. }
  5328.  
  5329. function startAutoScroll() {
  5330. clearInterval(autoScrollInterval);
  5331. if (autoScroll <= 0) return;
  5332. let scrollRange_o = 1;
  5333. if (autoScroll > 1000) {
  5334. scrollRange_o = parseInt(autoScroll / 1000);
  5335. }
  5336. let devicePixelRatio = window.devicePixelRatio;
  5337. let scrollRange = Math.ceil(scrollRange_o / devicePixelRatio);
  5338. autoScrollInterval = setInterval(() => {
  5339. if (isPause) return;
  5340. if (devicePixelRatio !== window.devicePixelRatio) {
  5341. devicePixelRatio = window.devicePixelRatio;
  5342. scrollRange = Math.ceil(scrollRange_o / devicePixelRatio);
  5343. }
  5344. window.scroll(window.scrollX, window.scrollY + scrollRange);
  5345. }, parseInt(1000 / autoScroll));
  5346. }
  5347.  
  5348. var inUpdate = false;
  5349. var importHandler, configCon;
  5350. function initConfig(href) {
  5351. if (location.hostname === "github.com") {
  5352. 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) {
  5353. let issue_body = document.getElementById("issue_body");
  5354. if (!issue_body) return true;
  5355. issue_body.value = issue_body.value.replace("\n", "\n" + location.hash.slice(1) + "\n");
  5356. let starButton = document.createElement("a");
  5357. starButton.href = "https://github.com/hoothin/UserScripts#star";
  5358. starButton.className = "js-toggler-target rounded-left-2 btn-with-aria-count btn-sm btn";
  5359. 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>');
  5360. starButton.style.float = "right";
  5361. document.querySelector(".Layout-main>h2").appendChild(starButton);
  5362. return true;
  5363. } else if (location.href === "https://github.com/hoothin/UserScripts#star") {
  5364. let starButton = document.querySelector(".starring-container:not(.on)>.unstarred>form>button");
  5365. if (starButton) emuClick(starButton);
  5366. return true;
  5367. }
  5368. }
  5369. let isGuidePage = checkGuidePage(href);
  5370. if (!isGuidePage) {
  5371. if (href.indexOf("PagetualGuide") != -1) return true;
  5372. if (location.hostname === "pagetual.hoothin.com") return true;
  5373. }
  5374.  
  5375. var click2import, importUrlPres;
  5376.  
  5377. let inConfig = isGuidePage;
  5378. if (!inConfig) {
  5379. for (let i = 0; i < configPage.length; i++) {
  5380. if (configPage[i] == location.href) {
  5381. inConfig = true;
  5382. break;
  5383. }
  5384. }
  5385. }
  5386. configCon = document.getElementById("configCon");
  5387. if (configCon) {
  5388. configCon.parentNode.removeChild(configCon);
  5389. }
  5390. if (ruleImportUrlReg.test(href) || inConfig) {
  5391. let importing = false;
  5392. if (!inUpdate && rulesData.uninited) {
  5393. setTimeout(() => {
  5394. if (!inUpdate && !importing) showTips(i18n("firstAlert"));
  5395. }, 3000);
  5396. showTips(i18n("firstAlert"));
  5397. }
  5398. let defaultOption = document.querySelector('#discussion_rating_4');
  5399. if (defaultOption) defaultOption.checked = true;
  5400. let createImportBtn = (pre) => {
  5401. let importBtn = document.createElement("button");
  5402. importBtn.id = "pagetualImport";
  5403. importBtn.innerText = i18n("import");
  5404. importBtn.style.marginTop = "100px";
  5405. importBtn.style.float = "right";
  5406. importBtn.style.position = "relative";
  5407. importBtn.style.display = "block";
  5408. importBtn.style.fontSize = "20px";
  5409. importBtn.addEventListener("click", e => {
  5410. let parentNode = importBtn.parentNode;
  5411. if (!parentNode) return;
  5412. parentNode.removeChild(importBtn);
  5413. try {
  5414. let rules = parentNode.innerText.trim();
  5415. let isContent = /['"]name['"]/i.test(rules);
  5416. if (isContent) {
  5417. let ruleList = JSON.parse(`[${rules}]`);
  5418. for (let i in ruleList) {
  5419. let hasRule = false;
  5420. let r = ruleList[i];
  5421. for (let j in ruleParser.customRules) {
  5422. if (ruleParser.customRules[j].name == r.name) {
  5423. ruleParser.customRules[j] = r;
  5424. hasRule = true;
  5425. break;
  5426. }
  5427. }
  5428. if (!hasRule) ruleParser.customRules.push(r);
  5429. ruleParser.hpRules.unshift(r);
  5430. }
  5431. storage.setItem("customRules", ruleParser.customRules);
  5432. storage.setItem("hpRules", ruleParser.hpRules);
  5433. storage.setItem("smartRules", []);
  5434. showTips(i18n("importSucc"));
  5435. } else {
  5436. rules = rules.split("\n");
  5437. let diff = false;
  5438. for (let c = 0; c < rules.length; c++) {
  5439. let urlArr = rules[c].split("|"), url, type = 1;
  5440. if (urlArr.length == 1) {
  5441. url = urlArr[0].trim();
  5442. if (!/^http/.test(url)) {
  5443. showTips(i18n("errorWrongUrl"));
  5444. return;
  5445. }
  5446. } else if (urlArr.length == 2) {
  5447. type = urlArr[0].trim();
  5448. url = urlArr[1].trim();
  5449. if (!/^http/.test(url)) {
  5450. showTips(i18n("errorWrongUrl"));
  5451. return;
  5452. }
  5453. } else {
  5454. break;
  5455. }
  5456. let maxId = 1, hasUrl = false;
  5457. if (!rulesData.urls) {
  5458. rulesData.urls = [];
  5459. maxId = 1;
  5460. } else {
  5461. rulesData.urls.forEach(u => {
  5462. if (maxId < u.id) {
  5463. maxId = u.id;
  5464. }
  5465. if (u.url == url) {
  5466. hasUrl = true;
  5467. }
  5468. });
  5469. if (hasUrl) break;
  5470. }
  5471. diff = true;
  5472. if (!rulesData.sort) rulesData.sort = [1];
  5473. rulesData.urls.push({id: maxId + 1, url: url, type: type});
  5474. rulesData.sort.unshift(maxId + 1);
  5475. }
  5476. if (!diff) {
  5477. showTips(i18n("errorAlreadyExists"));
  5478. setTimeout(() => {
  5479. showTips(i18n("beginUpdate"), "", 50000);
  5480. updateRules(() => {
  5481. showTips(i18n("updateSucc"));
  5482. location.reload();
  5483. }, (rule, err) => {
  5484. showTips(`Failed to update ${rule.url} rules!`);
  5485. debug(err);
  5486. });
  5487. }, 500);
  5488. return;
  5489. }
  5490. storage.setItem("rulesData", rulesData);
  5491.  
  5492. if (rulesData.urls) ruleUrls = ruleUrls.concat(rulesData.urls);
  5493. if (rulesData.sort) {
  5494. let urls = [];
  5495. rulesData.sort.forEach(id => {
  5496. for (let s = 0; s < ruleUrls.length; s++) {
  5497. if (id == ruleUrls[s].id) {
  5498. urls.push(ruleUrls[s]);
  5499. break;
  5500. }
  5501. }
  5502. });
  5503. ruleUrls = urls;
  5504. }
  5505. showTips(i18n("beginUpdate"), "", 30000);
  5506. updateRules(() => {
  5507. showTips(i18n("updateSucc"));
  5508. location.reload();
  5509. }, (rule, err) => {
  5510. showTips(`Failed to update ${rule.url} rules!`);
  5511. debug(err);
  5512. });
  5513. importing = true;
  5514. }
  5515. } catch (e) {
  5516. _GM_notification(e.toString());
  5517. }
  5518. });
  5519. if (pre) {
  5520. let clientHeight = 35 - pre.clientHeight;
  5521. if (clientHeight > -20) clientHeight = -20;
  5522. importBtn.style.marginTop = `${clientHeight}px`;
  5523. pre.appendChild(importBtn);
  5524. }
  5525. return importBtn;
  5526. };
  5527. [].forEach.call(document.querySelectorAll('pre[name=pagetual],pre[name=user-content-pagetual]'), pre => {
  5528. let importBtn = createImportBtn(pre);
  5529. });
  5530. if (!importHandler) {
  5531. importHandler = e => {
  5532. if (compareNodeName(e.target, ["pre"])) {
  5533. let nameAttr = e.target.getAttribute("name");
  5534. if (nameAttr == "pagetual" || nameAttr == "user-content-pagetual") {
  5535. if (e.target.querySelector('#pagetualImport')) return;
  5536. let importBtn = createImportBtn(e.target);
  5537. }
  5538. }
  5539. };
  5540. }
  5541. document.removeEventListener("mouseover", importHandler);
  5542. document.addEventListener("mouseover", importHandler);
  5543.  
  5544. if (inConfig) {
  5545. if (!inUpdate && _GM_info.script && _GM_info.script.version && _GM_info.script.version !== '1.0.0') {
  5546. let versionEle = document.querySelector('.markdown-body>h1[id],article>h1');
  5547. let latestVer = versionEle && versionEle.innerText.match(/\d[\d\.]+/)[0];
  5548. if (latestVer && latestVer != _GM_info.script.version) {
  5549. showTips(i18n('outOfDate'), "", 3000);
  5550. }
  5551. }
  5552. _GM_addStyle(`
  5553. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  5554. cursor: pointer;
  5555. user-select: none;
  5556. display: inline-block;
  5557. margin-right: 5px;
  5558. -moz-transition:color 0.3s ease, transform 0.3s;
  5559. -webkit-transition:color 0.3s ease, transform 0.3s;
  5560. transition:color 0.3s ease, transform 0.3s;
  5561. }
  5562. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  5563. color:red;
  5564. transform: scale(1.5);
  5565. -webkit-transform: scale(1.5);
  5566. }
  5567. .updateDate{
  5568. cursor: pointer;
  5569. user-select: none;
  5570. -moz-transition:color 0.3s ease, transform 0.3s;
  5571. -webkit-transition:color 0.3s ease, transform 0.3s;
  5572. transition:color 0.3s ease, transform 0.3s;
  5573. transform-origin: left;
  5574. -webkit-transform-origin: left;
  5575. }
  5576. .updateDate:hover{
  5577. color:red;
  5578. transform: scale(1.1);
  5579. -webkit-transform: scale(1.1);
  5580. }
  5581. input[type=number]::-webkit-inner-spin-button,
  5582. input[type=number]::-webkit-outer-spin-button {
  5583. -webkit-appearance: none;
  5584. margin: 0;
  5585. }
  5586. input[type=number] {
  5587. -moz-appearance:textfield;
  5588. }
  5589. table td>h3 {
  5590. margin: 16px!important;
  5591. padding: 0!important;
  5592. }
  5593. table td>h4 {
  5594. padding: 0!important;
  5595. }
  5596. #saveBtn {
  5597. width: 60vw;
  5598. position: fixed;
  5599. z-index: 999;
  5600. bottom: 0;
  5601. left: 20vw;
  5602. font-size: xx-large;
  5603. opacity: 0.6;
  5604. cursor: pointer;
  5605. -moz-transition:all 0.3s ease;
  5606. -webkit-transition:all 0.3s ease;
  5607. transition:all 0.3s ease;
  5608. }
  5609. #configCon #saveBtn:hover {
  5610. opacity: 1;
  5611. margin-bottom: 0px;
  5612. }
  5613. #configCon #saveBtn {
  5614. margin-bottom: -40px;
  5615. }
  5616. #configCon.showSave #saveBtn {
  5617. margin-bottom: 0px;
  5618. }
  5619. `);
  5620. click2import = document.querySelector("[name='user-content-click2import'],[name='click2import']");
  5621. if (click2import) click2import.innerText = i18n("click2ImportRule")
  5622. configCon = document.querySelector(".markdown-body,.theme-default-content");
  5623. if (!configCon) {
  5624. setTimeout(() => {
  5625. location.reload();
  5626. }, 1000);
  5627. return true;
  5628. }
  5629. let insertPos = configCon.querySelector("hr,#jsoneditor");
  5630. configCon = document.createElement("div");
  5631. configCon.id = "configCon";
  5632. insertPos.parentNode.insertBefore(configCon, insertPos);
  5633.  
  5634. importUrlPres = document.querySelectorAll("pre[name='user-content-pagetual'],pre[name='pagetual']");
  5635. if (importUrlPres) {
  5636. [].forEach.call(importUrlPres, importUrlPre => {
  5637. importUrlPre.style.overflow = "hidden";
  5638. importUrlPre.style.display = rulesData.uninited ? "block" : "none";
  5639. });
  5640. }
  5641. if (click2import) click2import.style.display = rulesData.uninited ? "block" : "none";
  5642. let otherconfig = document.querySelector("a[name='user-content-otherconfig'],a[name='otherconfig']");
  5643. if (otherconfig) otherconfig.parentNode.removeChild(otherconfig);
  5644. let rulesExample = document.querySelector("#user-content-rules-example+a,#rules-example>a");
  5645. if (rulesExample) {
  5646. rulesExample.innerText = i18n("rulesExample");
  5647. if (lang == "zh-CN") {
  5648. rulesExample.href = rulesExample.href.replace("en", "cn");
  5649. } else if (lang == "zh-TW" || lang == "zh-HK") {
  5650. rulesExample.href = rulesExample.href.replace("/en", "");
  5651. }
  5652. }
  5653.  
  5654. let newPos, lastPos = 0;
  5655. window.addEventListener('scroll', function(e) {
  5656. newPos = window.scrollY;
  5657. if (newPos > lastPos) {
  5658. configCon.classList.add("showSave");
  5659. } else {
  5660. configCon.classList.remove("showSave");
  5661. }
  5662. lastPos = newPos;
  5663. });
  5664. } else return false;
  5665. } else return false;
  5666. let ruleBarInsertPos = document.createTextNode(' ');
  5667. configCon.appendChild(ruleBarInsertPos);
  5668. class Rulebar {
  5669. init(ruleUrl) {
  5670. let id = ruleUrl.id;
  5671. this.ruleUrl = ruleUrl;
  5672. this.item = document.createElement("p");
  5673. this.item.dataset.id = id;
  5674. let url = document.createElement("a");
  5675. url.href = ruleUrl.url;
  5676. url.innerHTML = ruleUrl.url;
  5677. url.title = ruleUrl.url;
  5678. let up = document.createElement("span");
  5679. up.innerHTML = "↑ ";
  5680. up.title = i18n("sortTitle");
  5681. let down = document.createElement("span");
  5682. down.innerHTML = "↓ ";
  5683. down.title = i18n("sortTitle");
  5684. let del = document.createElement("span");
  5685. del.innerHTML = "× ";
  5686. up.onclick = e => {
  5687. this.moveUp();
  5688. };
  5689. down.onclick = e => {
  5690. this.moveDown();
  5691. };
  5692. del.onclick = e => {
  5693. this.del();
  5694. };
  5695. this.item.appendChild(up);
  5696. this.item.appendChild(down);
  5697. this.item.appendChild(del);
  5698. this.item.appendChild(url);
  5699. if (ruleParser.rules) {
  5700. url.style.maxWidth = "calc(100% - 150px)";
  5701. url.style.overflow = "hidden";
  5702. url.style.display = "inline-block";
  5703. url.style.textOverflow = "ellipsis";
  5704. url.style.verticalAlign = "bottom";
  5705. url.style.whiteSpace = "nowrap";
  5706. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == id ? 1 : 0), 0);
  5707. let idSpan = document.createElement("span");
  5708. idSpan.style.float = "right";
  5709. idSpan.innerHTML = `[rules: ${rulesLength}]`;
  5710. this.item.appendChild(idSpan);
  5711. this.idSpan = idSpan;
  5712. }
  5713. configCon.insertBefore(this.item, ruleBarInsertPos);
  5714. }
  5715. updateNum() {
  5716. if (ruleParser.rules) {
  5717. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == this.item.dataset.id ? 1 : 0), 0);
  5718. this.idSpan.innerHTML = `[rules: ${rulesLength}]`;
  5719. }
  5720. }
  5721. saveSort() {
  5722. let sort = [];
  5723. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i => {
  5724. sort.push(i.dataset.id);
  5725. });
  5726. rulesData.sort = sort;
  5727. let urls = [];
  5728. sort.forEach(id => {
  5729. for (let s = 0; s < ruleUrls.length; s++) {
  5730. if (id == ruleUrls[s].id) {
  5731. urls.push(ruleUrls[s]);
  5732. break;
  5733. }
  5734. }
  5735. });
  5736. ruleUrls = urls;
  5737. storage.setItem("rulesData", rulesData);
  5738. showTips(i18n("sortTitle"));
  5739. }
  5740. moveUp() {
  5741. let preE = this.item.previousElementSibling;
  5742. if (compareNodeName(preE, ["p"]) && preE.children.length > 1) {
  5743. this.item.parentNode.insertBefore(this.item, preE);
  5744. this.saveSort();
  5745. }
  5746. }
  5747. moveDown() {
  5748. let nextE = this.item.nextElementSibling;
  5749. if (compareNodeName(nextE, ["p"]) && nextE.children.length > 1) {
  5750. this.item.parentNode.insertBefore(nextE, this.item);
  5751. this.saveSort();
  5752. }
  5753. }
  5754. del() {
  5755. if (this.ruleUrl.id < 2) {
  5756. showTips(i18n("cantDel"));
  5757. } else if (window.confirm(i18n("confirmDel"))) {
  5758. for (let u = 0; u < rulesData.urls.length; u++) {
  5759. if (this.ruleUrl.id == rulesData.urls[u].id) {
  5760. rulesData.urls.splice(u, 1);
  5761. break;
  5762. }
  5763. }
  5764. for (let u = 0; u < ruleUrls.length; u++) {
  5765. if (this.ruleUrl.id == ruleUrls[u].id) {
  5766. ruleUrls.splice(u, 1);
  5767. break;
  5768. }
  5769. }
  5770. for (let u = 0; u < rulesData.sort.length; u++) {
  5771. if (this.ruleUrl.id == rulesData.sort[u]) {
  5772. rulesData.sort.splice(u, 1);
  5773. break;
  5774. }
  5775. }
  5776. rulesData.ruleVersion = 0;
  5777. storage.setItem("rulesData", rulesData);
  5778. ruleParser.rules = ruleParser.rules.filter(item => {return item.from != this.ruleUrl.id});
  5779. storage.setItem("rules", ruleParser.rules);
  5780. this.item.parentNode.removeChild(this.item);
  5781. //location.reload();
  5782. }
  5783. }
  5784. }
  5785. let langSelect = document.createElement("select");
  5786. langSelect.style.float = "right";
  5787. langSelect.style.position = "relative";
  5788. langSelect.style.zIndex = "1";
  5789. let option = document.createElement("option");
  5790. option.value = "";
  5791. option.innerText = "Language";
  5792. langSelect.appendChild(option);
  5793. for (let key in langList) {
  5794. let option = document.createElement("option");
  5795. option.value = key;
  5796. option.innerText = langList[key];
  5797. langSelect.appendChild(option);
  5798. }
  5799. langSelect.value = rulesData.lang || "";
  5800. configCon.appendChild(langSelect);
  5801.  
  5802. let updateP = document.createElement("p"), i = 0;
  5803. let now = new Date().getTime();
  5804.  
  5805.  
  5806. let pastDate = (new Date(updateDate)).toString(), passStr;
  5807. let passTime = (now - updateDate) / 1000;
  5808. if (isNaN(passTime)) {
  5809. passStr = i18n("firstUpdate");
  5810. } else {
  5811. if (passTime < 60) {
  5812. passStr = i18n("passSec", parseInt(passTime));
  5813. } else if (passTime < 60 * 60) {
  5814. passStr = i18n("passMin", parseInt(passTime / 60));
  5815. } else if (passTime < 60 * 60 * 24) {
  5816. passStr = i18n("passHour", parseInt(passTime / 3600));
  5817. } else {
  5818. passStr = i18n("passDay", parseInt(passTime / 86400));
  5819. }
  5820. passStr += " 🖱 " + i18n("click2update");
  5821. }
  5822.  
  5823. let rulebarList = [], updateFail = false;
  5824. updateP.className = "updateDate";
  5825. updateP.innerHTML = passStr;
  5826. updateP.title = i18n("update") + " - " + pastDate;
  5827. configCon.appendChild(updateP);
  5828. if (ruleUrls) {
  5829. ruleUrls.forEach(ruleUrl => {
  5830. let rulebar = new Rulebar();
  5831. rulebar.init(ruleUrl);
  5832. rulebarList.push(rulebar);
  5833. });
  5834. }
  5835. let customUrlsTitle = document.createElement("h2");
  5836. customUrlsTitle.innerHTML = i18n("customUrls");
  5837. configCon.appendChild(customUrlsTitle);
  5838. let customUrlsInput = document.createElement("textarea");
  5839. customUrlsInput.style.width = "100%";
  5840. customUrlsInput.style.position = "relative";
  5841. customUrlsInput.placeholder = "http://wedata.net/databases/AutoPagerize/items_all.json \nhttps://hoothin.github.io/UserScripts/Pagetual/pagetualRules.json";
  5842. customUrlsInput.spellcheck = false;
  5843. configCon.appendChild(customUrlsInput);
  5844.  
  5845. let btns = document.createElement("div");
  5846. btns.style.display = "flex";
  5847. configCon.appendChild(btns);
  5848. let upBtnImg = document.createElement("div");
  5849. upBtnImg.style.width = "33%";
  5850. let upBtnImgTitle = document.createElement("h2");
  5851. upBtnImgTitle.style.whiteSpace = "nowrap";
  5852. upBtnImgTitle.style.overflow = "auto";
  5853. upBtnImgTitle.innerHTML = i18n("upBtnImg");
  5854. upBtnImg.appendChild(upBtnImgTitle);
  5855. let upBtnImgInput = document.createElement("input");
  5856. upBtnImgInput.style.width = "100%";
  5857. upBtnImgInput.style.position = "relative";
  5858. upBtnImgInput.placeholder = "data:image/png;base64,UpBtn";
  5859. upBtnImgInput.value = rulesData.upBtnImg || '';
  5860. upBtnImgInput.spellcheck = false;
  5861. upBtnImg.appendChild(upBtnImgInput);
  5862. btns.appendChild(upBtnImg);
  5863.  
  5864. let downBtnImg = document.createElement("div");
  5865. downBtnImg.style.width = "33%";
  5866. let downBtnImgTitle = document.createElement("h2");
  5867. downBtnImgTitle.style.whiteSpace = "nowrap";
  5868. downBtnImgTitle.style.overflow = "auto";
  5869. downBtnImgTitle.innerHTML = i18n("downBtnImg");
  5870. downBtnImg.appendChild(downBtnImgTitle);
  5871. let downBtnImgInput = document.createElement("input");
  5872. downBtnImgInput.style.width = "100%";
  5873. downBtnImgInput.style.position = "relative";
  5874. downBtnImgInput.placeholder = "data:image/png;base64,DownBtn";
  5875. downBtnImgInput.value = rulesData.downBtnImg || '';
  5876. downBtnImgInput.spellcheck = false;
  5877. downBtnImg.appendChild(downBtnImgInput);
  5878. btns.appendChild(downBtnImg);
  5879.  
  5880. let sideControllerIconDiv = document.createElement("div");
  5881. sideControllerIconDiv.style.width = "33%";
  5882. let sideControllerIconTitle = document.createElement("h2");
  5883. sideControllerIconTitle.style.whiteSpace = "nowrap";
  5884. sideControllerIconTitle.style.overflow = "auto";
  5885. sideControllerIconTitle.innerHTML = i18n("sideControllerIcon");
  5886. sideControllerIconDiv.appendChild(sideControllerIconTitle);
  5887. let sideControllerIconInput = document.createElement("input");
  5888. sideControllerIconInput.style.width = "100%";
  5889. sideControllerIconInput.style.position = "relative";
  5890. sideControllerIconInput.placeholder = "📄";
  5891. sideControllerIconInput.value = rulesData.sideControllerIcon || '';
  5892. sideControllerIconInput.spellcheck = false;
  5893. sideControllerIconDiv.appendChild(sideControllerIconInput);
  5894. btns.appendChild(sideControllerIconDiv);
  5895.  
  5896. let otherBtns = document.createElement("div");
  5897. otherBtns.style.display = "flex";
  5898. configCon.appendChild(otherBtns);
  5899. let loadingText = document.createElement("div");
  5900. loadingText.style.width = "100%";
  5901. let loadingTextTitle = document.createElement("h2");
  5902. loadingTextTitle.style.whiteSpace = "nowrap";
  5903. loadingTextTitle.style.overflow = "auto";
  5904. loadingTextTitle.innerHTML = i18n("loadingTextTitle");
  5905. loadingText.appendChild(loadingTextTitle);
  5906. let loadingTextInput = document.createElement("input");
  5907. loadingTextInput.value = rulesData.loadingText || '';
  5908. loadingTextInput.placeholder = i18n("loadingText");
  5909. loadingTextInput.style.width = "100%";
  5910. loadingTextInput.style.position = "relative";
  5911. loadingTextInput.style.margin = "0";
  5912. loadingTextInput.spellcheck = false;
  5913. loadingText.appendChild(loadingTextInput);
  5914. otherBtns.appendChild(loadingText);
  5915.  
  5916. let opacity = document.createElement("div");
  5917. let opacityTitle = document.createElement("h2");
  5918. opacityTitle.style.whiteSpace = "nowrap";
  5919. opacityTitle.style.overflow = "visible";
  5920. opacityTitle.innerHTML = i18n("opacity");
  5921. opacity.appendChild(opacityTitle);
  5922. let opacityInput = document.createElement("input");
  5923. opacityInput.value = rulesData.opacity * 100;
  5924. opacityInput.type = "number";
  5925. opacityInput.min = 0;
  5926. opacityInput.max = 100;
  5927. opacityInput.style.width = "110px";
  5928. opacityInput.style.position = "relative";
  5929. opacityInput.style.margin = "0";
  5930. opacityInput.placeholder = i18n("opacityPlaceholder");
  5931. opacityInput.spellcheck = false;
  5932. opacityInput.oninput = e => {
  5933. if (opacityInput.value > 100) opacityInput.value = 100;
  5934. else if (opacityInput.value < 0) opacityInput.value = 0;
  5935. };
  5936. opacity.appendChild(opacityInput);
  5937. otherBtns.appendChild(opacity);
  5938.  
  5939. let pageElementCss = document.createElement("div");
  5940. pageElementCss.style.marginBottom = "30px";
  5941. let pageElementCssTitle = document.createElement("h2");
  5942. pageElementCssTitle.innerHTML = i18n("pageElementCss");
  5943. pageElementCss.appendChild(pageElementCssTitle);
  5944. let pageElementCssInput = document.createElement("input");
  5945. pageElementCssInput.value = rulesData.pageElementCss || '';
  5946. pageElementCssInput.style.width = "100%";
  5947. pageElementCssInput.style.position = "relative";
  5948. pageElementCssInput.style.margin = "0";
  5949. pageElementCssInput.placeholder = "font-size: xx-large;";
  5950. pageElementCssInput.spellcheck = false;
  5951. pageElementCss.appendChild(pageElementCssInput);
  5952. configCon.appendChild(pageElementCss);
  5953.  
  5954. let customCss = document.createElement("div");
  5955. customCss.style.marginBottom = "50px";
  5956. let customCssTitle = document.createElement("h2");
  5957. customCssTitle.innerHTML = i18n("customCss");
  5958. customCss.appendChild(customCssTitle);
  5959. let customCssInput = document.createElement("textarea");
  5960. customCssInput.value = rulesData.customCss || '';
  5961. customCssInput.style.width = "100%";
  5962. customCssInput.style.position = "relative";
  5963. customCssInput.style.margin = "0";
  5964. customCssInput.placeholder = ".pagetual {\n}";
  5965. customCssInput.spellcheck = false;
  5966. customCss.appendChild(customCssInput);
  5967. configCon.appendChild(customCss);
  5968.  
  5969. let configTable = document.createElement("table");
  5970. configTable.style.width = "100%";
  5971. let configTbody = document.createElement("tbody");
  5972. configTbody.style.width = "99%";
  5973. configTbody.style.display = "inline-table";
  5974. configTable.appendChild(configTbody);
  5975. configCon.appendChild(configTable);
  5976. function createCheckbox(innerText, val, tag, parentCheck, otherType, alwaysShow) {
  5977. if (typeof val == 'undefined') val = "";
  5978. let title = document.createElement(tag || "h3");
  5979. title.innerHTML = innerText;
  5980. title.style.overflowWrap = "normal";
  5981. let input = document.createElement("input");
  5982. if (otherType === 'key') {
  5983. input.type = 'text';
  5984. input.setAttribute('readOnly', 'readonly');
  5985. input.addEventListener("keydown", e => {
  5986. if (e.key === 'Escape' || e.key === 'Backspace') input.value = '';
  5987. else input.value = e.key;
  5988. e.stopPropagation();
  5989. e.preventDefault();
  5990. });
  5991. } else {
  5992. input.type = otherType || "checkbox";
  5993. }
  5994. input.style.width = "35px";
  5995. input.style.height = "20px";
  5996. input.style.float = "left";
  5997. input.style.margin = "0 2px";
  5998. input.value = val;
  5999. input.checked = val;
  6000. let td = document.createElement("td");
  6001. td.appendChild(input);
  6002. if (parentCheck) {
  6003. title.appendChild(input);
  6004. title.style.margin = "0";
  6005. td.appendChild(title);
  6006. let parent = parentCheck.parentNode.nextElementSibling;
  6007. let tr = parent.querySelector("tr");
  6008. if (!tr) {
  6009. tr = document.createElement("tr");
  6010. parent.appendChild(tr);
  6011. }
  6012. tr.appendChild(td);
  6013. if (!alwaysShow) {
  6014. if (!parentCheck.checked) {
  6015. td.style.display = "none";
  6016. }
  6017. parentCheck.addEventListener("click", e => {
  6018. td.style.display = parentCheck.checked ? "" : "none";
  6019. });
  6020. }
  6021. } else {
  6022. let tr = document.createElement("tr");
  6023. tr.appendChild(td);
  6024. td = document.createElement("td");
  6025. td.appendChild(title);
  6026. tr.appendChild(td);
  6027. configTable.children[0].appendChild(tr);
  6028. }
  6029. let xNodePos = innerText.indexOf('【X】');
  6030. if (xNodePos !== -1) {
  6031. input.style.float = "";
  6032. let xNode = title.firstChild.splitText(xNodePos);
  6033. xNode.splitText(3);
  6034. xNode.parentNode.replaceChild(input, xNode);
  6035. }
  6036. return input;
  6037. }
  6038.  
  6039. let setConfigPageInput = createCheckbox(i18n("setConfigPage"), false);
  6040. let enableWhiteListInput = createCheckbox(i18n("autoRun"), rulesData.enableWhiteList != true);
  6041. let sideControllerInput = createCheckbox(i18n("sideController"), rulesData.sideController);
  6042. let sideControllerAlwaysInput = createCheckbox(i18n("sideControllerAlways"), rulesData.sideControllerAlways, "h4", sideControllerInput);
  6043. let sideControllerScrollInput = createCheckbox(i18n("sideControllerScroll"), rulesData.sideControllerScroll !== false, "h4", sideControllerInput);
  6044. let sideControllerLoadNowInput = createCheckbox(i18n("loadNow"), rulesData.sideControllerLoadNow !== false, "h4", sideControllerInput);
  6045. let enableDebugInput = createCheckbox(i18n("enableDebug"), rulesData.enableDebug != false);
  6046. let enableHistoryInput = createCheckbox(i18n("enableHistory"), rulesData.enableHistory === true);
  6047. let enableHistoryAfterInsertInput = createCheckbox(i18n("enableHistoryAfterInsert"), rulesData.enableHistoryAfterInsert === true, "h4", enableHistoryInput);
  6048. let openInNewTabInput = createCheckbox(i18n("openInNewTab"), rulesData.openInNewTab != false);
  6049. let hidePageBarInput = createCheckbox(i18n("hideBarTips"), rulesData.opacity == 0);
  6050. let hidePageBarArrowInput = createCheckbox(i18n("hideBarArrow"), rulesData.hideBarArrow);
  6051. let hideLoadingIconInput = createCheckbox(i18n("hideLoadingIcon"), rulesData.hideLoadingIcon != false);
  6052. let initRunInput = createCheckbox(i18n("initRun"), rulesData.initRun != false);
  6053. let autoLoadNumInput = createCheckbox(i18n("autoLoadNum"), rulesData.autoLoadNum, "h4", initRunInput, "number");
  6054. let preloadInput = createCheckbox(i18n("preload"), rulesData.preload != false);
  6055. let rateInput = createCheckbox(i18n("turnRate"), rulesData.rate, "h4", preloadInput, "number", true);
  6056. let dbClick2StopInput = createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  6057. let manualModeInput = createCheckbox(i18n("manualMode"), rulesData.manualMode);
  6058. let clickModeInput = createCheckbox(i18n("clickMode"), rulesData.clickMode);
  6059. let pageBarMenuInput = createCheckbox(i18n("pageBarMenu"), rulesData.pageBarMenu != false);
  6060. let arrowToScrollInput = createCheckbox(i18n("arrowToScroll"), rulesData.arrowToScroll);
  6061. let contentVisibilityInput = createCheckbox(i18n("contentVisibility"), rulesData.contentVisibility);
  6062. let wedata2githubInput = createCheckbox(i18n("wedata2github"), rulesData.wedata2github);
  6063. let customFirstInput = createCheckbox(i18n("customFirst"), rulesData.customFirst);
  6064. let lastPageTipsInput = createCheckbox(i18n("lastPageTips"), rulesData.lastPageTips);
  6065. let updateNotificationInput = createCheckbox(i18n("updateNotification"), rulesData.updateNotification != false);
  6066.  
  6067. let hideBarInput = createCheckbox(i18n("hideBar"), rulesData.hideBar && !rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  6068. hideBarInput.name = 'hideBar';
  6069. let hideBarButNoStopInput = createCheckbox(i18n("hideBarButNoStop"), rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  6070. hideBarButNoStopInput.name = 'hideBar';
  6071. hideBarInput.addEventListener('mouseup', e => {
  6072. if (hideBarInput.checked) {
  6073. setTimeout(() => {hideBarInput.checked = false}, 0);
  6074. }
  6075. });
  6076. hideBarButNoStopInput.addEventListener('mouseup', e => {
  6077. if (hideBarButNoStopInput.checked) {
  6078. setTimeout(() => {hideBarButNoStopInput.checked = false}, 0);
  6079. }
  6080. });
  6081. hidePageBarInput.addEventListener('click', e => {
  6082. opacityInput.value = hidePageBarInput.checked ? 0 : 100;
  6083. });
  6084.  
  6085. let dbClick2StopCtrlInput = createCheckbox(i18n("dbClick2StopCtrl"), rulesData.dbClick2StopCtrl, "h4", dbClick2StopInput);
  6086. let dbClick2StopAltInput = createCheckbox(i18n("dbClick2StopAlt"), rulesData.dbClick2StopAlt, "h4", dbClick2StopInput);
  6087. let dbClick2StopShiftInput = createCheckbox(i18n("dbClick2StopShift"), rulesData.dbClick2StopShift, "h4", dbClick2StopInput);
  6088. let dbClick2StopMetaInput = createCheckbox(i18n("dbClick2StopMeta"), rulesData.dbClick2StopMeta, "h4", dbClick2StopInput);
  6089. let dbClick2StopKeyInput = createCheckbox(i18n("dbClick2StopKey"), rulesData.dbClick2StopKey, "h4", dbClick2StopInput, "key");
  6090.  
  6091. let otherConfigPage = (rulesData.configPage || configPage[0]) != location.href;
  6092. if (!otherConfigPage) {
  6093. setConfigPageInput.parentNode.parentNode.style.display = "none";
  6094. }
  6095.  
  6096. updateP.onclick = e => {
  6097. updateFail = false;
  6098. //ruleParser.rules = [];
  6099. showTips(i18n("beginUpdate"), "", 30000);
  6100. updateRules(() => {
  6101. if (!updateFail) {
  6102. showTips(i18n("updateSucc"));
  6103. if (importUrlPres) {
  6104. [].forEach.call(importUrlPres, importUrlPre => {
  6105. importUrlPre.style.display = "none";
  6106. });
  6107. }
  6108. if (click2import) click2import.style.display = "none";
  6109. }
  6110. updateP.innerHTML = i18n("passSec", 0);
  6111. updateP.title = i18n("update");
  6112. rulebarList.forEach(rulebar => {
  6113. rulebar.updateNum();
  6114. });
  6115. }, (rule, err) => {
  6116. if (rule.id == 1) {
  6117. showTips(`Failed to update wedata rules! Try to switch to wedata mirror!`);
  6118. wedata2githubInput.scrollIntoView({ behavior: "smooth" });
  6119. } else {
  6120. showTips(`Failed to update ${rule.url} rules!`);
  6121. }
  6122. debug(err);
  6123. updateFail = true;
  6124. });
  6125. };
  6126. let customRulesTitle = document.createElement("h2");
  6127. 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');
  6128. configCon.appendChild(customRulesTitle);
  6129. customRulesInput = document.createElement("textarea");
  6130. customRulesInput.spellcheck = false;
  6131. configCon.appendChild(customRulesInput);
  6132. if (rulesData.editTemp) {
  6133. if (!ruleParser.customRules) {
  6134. ruleParser.customRules = [];
  6135. }
  6136. for (let i in ruleParser.customRules) {
  6137. if (ruleParser.customRules[i].url == rulesData.editTemp.url) {
  6138. ruleParser.customRules.splice(i, 1);
  6139. break;
  6140. }
  6141. }
  6142. ruleParser.customRules.unshift(rulesData.editTemp);
  6143. rulesData.editTemp = null;
  6144. storage.setItem("rulesData", rulesData);
  6145. customRulesInput.previousElementSibling.scrollIntoView();
  6146. }
  6147. customRulesInput.style.width = "100%";
  6148. customRulesInput.style.height = "800px";
  6149. 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]`;
  6150. let preCustom = getFormatJSON(ruleParser.customRules);
  6151. customRulesInput.value = preCustom;
  6152. if (isGuidePage) customRulesInput.style.display = "none";
  6153. let blacklistInput = document.createElement("textarea");
  6154. blacklistInput.style.width = "100%";
  6155. blacklistInput.style.height = "500px";
  6156. blacklistInput.style.display = "none";
  6157. blacklistInput.spellcheck = false;
  6158. 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";
  6159. blacklistInput.value = rulesData.blacklist ? rulesData.blacklist.join("\n") : "";
  6160. let blacklistBtn = document.createElement("button");
  6161. blacklistBtn.innerText = i18n("editBlacklist");
  6162. blacklistBtn.style.width = "100%";
  6163. blacklistBtn.onclick = e => {
  6164. blacklistInput.style.display = blacklistInput.style.display == "none" ? "" : "none";
  6165. };
  6166. configCon.appendChild(blacklistBtn);
  6167. configCon.appendChild(blacklistInput);
  6168. let saveBtn = document.createElement("button");
  6169. saveBtn.innerHTML = i18n("save");
  6170. saveBtn.id = "saveBtn";
  6171. configCon.appendChild(saveBtn);
  6172. saveBtn.onclick = e => {
  6173. try {
  6174. let customRules;
  6175. if (editor) {
  6176. if (editorChanged) {
  6177. editorChanged = false;
  6178. storage.setItem("hpRules", []);
  6179. storage.setItem("smartRules", []);
  6180. }
  6181. customRules = editor.get();
  6182. if (!customRules) {
  6183. customRules = "";
  6184. } else {
  6185. if (Array && Array.isArray && !Array.isArray(customRules)) {
  6186. showTips(i18n("errorRulesMustBeArray"));
  6187. return;
  6188. }
  6189. }
  6190. } else {
  6191. if (customRulesInput.value != preCustom) {
  6192. storage.setItem("hpRules", []);
  6193. storage.setItem("smartRules", []);
  6194. }
  6195. if (customRulesInput.value == "") {
  6196. customRules = "";
  6197. } else {
  6198. customRules = JSON.parse(customRulesInput.value);
  6199. if (Array && Array.isArray && !Array.isArray(customRules)) {
  6200. showTips(i18n("errorRulesMustBeArray"));
  6201. return;
  6202. }
  6203. customRulesInput.value = JSON.stringify(customRules, null, 4);
  6204. }
  6205. }
  6206. debug(customRules);
  6207. storage.setItem("customRules", customRules);
  6208. } catch(e) {
  6209. debug(e);
  6210. let pos = e && e.message && e.message.match(/position (\d+)/);
  6211. if (pos && !editor) {
  6212. pos = parseInt(pos[1]);
  6213. customRulesInput.value = customRulesInput.value.slice(0, pos) + "➡️" + customRulesInput.value.slice(pos);
  6214. }
  6215. showTips(i18n("errorJson"));
  6216. return;
  6217. }
  6218. rulesData.lang = langSelect.value || "";
  6219. if (setConfigPageInput.checked) rulesData.configPage = location.href;
  6220. rulesData.wedata2github = wedata2githubInput.checked;
  6221. let opacity = parseInt(opacityInput.value) || 0;
  6222. if (opacity > 100) opacity = 100;
  6223. else if (opacity < 0) opacity = 0;
  6224. rulesData.opacity = opacity / 100;
  6225. rulesData.blacklist = blacklistInput.value ? blacklistInput.value.trim().split("\n") : "";
  6226. rulesData.hideBar = hideBarInput.checked;
  6227. rulesData.hideBarButNoStop = hideBarButNoStopInput.checked;
  6228. rulesData.dbClick2Stop = dbClick2StopInput.checked;
  6229. rulesData.enableWhiteList = !enableWhiteListInput.checked;
  6230. rulesData.enableDebug = enableDebugInput.checked;
  6231. rulesData.updateNotification = updateNotificationInput.checked;
  6232. rulesData.enableHistory = enableHistoryInput.checked;
  6233. rulesData.enableHistoryAfterInsert = enableHistoryAfterInsertInput.checked;
  6234. rulesData.openInNewTab = openInNewTabInput.checked;
  6235. rulesData.hideLoadingIcon = hideLoadingIconInput.checked;
  6236. rulesData.hideBarArrow = hidePageBarArrowInput.checked;
  6237. rulesData.customFirst = customFirstInput.checked;
  6238. rulesData.lastPageTips = lastPageTipsInput.checked;
  6239. rulesData.initRun = initRunInput.checked;
  6240. rulesData.autoLoadNum = autoLoadNumInput.value !== "0" ? autoLoadNumInput.value : '';
  6241. rulesData.rate = parseFloat(rateInput.value) || 0;
  6242. rulesData.preload = preloadInput.checked;
  6243. rulesData.manualMode = manualModeInput.checked;
  6244. rulesData.clickMode = clickModeInput.checked;
  6245. rulesData.pageBarMenu = pageBarMenuInput.checked;
  6246. rulesData.arrowToScroll = arrowToScrollInput.checked;
  6247. rulesData.contentVisibility = contentVisibilityInput.checked;
  6248. if (rulesData.sideController != sideControllerInput.checked) {
  6249. rulesData.sideControllerPos = false;
  6250. }
  6251. rulesData.sideController = sideControllerInput.checked;
  6252. rulesData.sideControllerScroll = sideControllerScrollInput.checked;
  6253. rulesData.sideControllerLoadNow = sideControllerLoadNowInput.checked;
  6254. rulesData.sideControllerAlways = sideControllerAlwaysInput.checked;
  6255. rulesData.pageElementCss = pageElementCssInput.value;
  6256. rulesData.customCss = customCssInput.value;
  6257. rulesData.upBtnImg = upBtnImgInput.value;
  6258. rulesData.downBtnImg = downBtnImgInput.value;
  6259. rulesData.sideControllerIcon = sideControllerIconInput.value;
  6260. rulesData.loadingText = loadingTextInput.value;
  6261. rulesData.dbClick2StopCtrl = dbClick2StopCtrlInput.checked;
  6262. rulesData.dbClick2StopAlt = dbClick2StopAltInput.checked;
  6263. rulesData.dbClick2StopShift = dbClick2StopShiftInput.checked;
  6264. rulesData.dbClick2StopMeta = dbClick2StopMetaInput.checked;
  6265. rulesData.dbClick2StopKey = dbClick2StopKeyInput.value;
  6266. storage.setItem("rulesData", rulesData);
  6267. let customUrls = customUrlsInput.value.trim(), urlImported = false;
  6268. if (customUrls) {
  6269. customUrls = customUrls.split(/\n/);
  6270. for (let c = 0; c < customUrls.length; c++) {
  6271. let url;
  6272. if (/^0\s*\|/.test(customUrls[c])) {
  6273. url = customUrls[c].replace(/^0\s*\|\s*/, "").trim();
  6274. if (!/^http/.test(url)) {
  6275. showTips(i18n("errorWrongUrl"));
  6276. return;
  6277. }
  6278. } else {
  6279. url = customUrls[c].trim();
  6280. if (!/^http/.test(url)) {
  6281. showTips(i18n("errorWrongUrl"));
  6282. return;
  6283. }
  6284. }
  6285. let maxId = 1, hasUrl = false;
  6286. if (!rulesData.urls) {
  6287. rulesData.urls = [];
  6288. }
  6289. ruleUrls.forEach(u => {
  6290. if (maxId < u.id) {
  6291. maxId = u.id;
  6292. }
  6293. if (u.url == url) {
  6294. hasUrl = true;
  6295. }
  6296. });
  6297. if (hasUrl) break;
  6298. if (!rulesData.sort) rulesData.sort = [1];
  6299. let newRule = {id: maxId + 1, url: url};
  6300. ruleUrls.push(newRule);
  6301. rulesData.urls.push(newRule);
  6302. rulesData.sort.push(maxId + 1);
  6303. storage.setItem("rulesData", rulesData);
  6304. let rulebar = new Rulebar();
  6305. rulebar.init(newRule);
  6306. rulebarList.push(rulebar);
  6307. }
  6308. }
  6309. showTips(i18n("settingsSaved"));
  6310. };
  6311. return true;
  6312. }
  6313.  
  6314. function updateRules (success, fail, keepCache) {
  6315. if (!storage.supportCrossSave()) {
  6316. fail({url:''}, "Not support cross storage");
  6317. showTips("Current platform do not support cross storage!");
  6318. return;
  6319. }
  6320. if (inUpdate) return;
  6321. inUpdate = true;
  6322. let ruleIndex = ruleUrls.length - 1;
  6323. if (!keepCache) {
  6324. storage.setItem("hpRules", []);
  6325. storage.setItem("smartRules", []);
  6326. }
  6327. let allOk = true;
  6328. let preLength = ruleParser.rules.length;
  6329. let fetchVersion = -1;
  6330. async function needUpdate(url, id) {
  6331. if (!/^https:\/\/hoothin\.github\.io\/|\/hoothin\/UserScripts\/.*\/Pagetual\/pagetualRules\.json/i.test(url)) {
  6332. return true;
  6333. }
  6334. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == id ? 1 : 0), 0);
  6335. if (rulesLength === 0) return true;
  6336. if (fetchVersion >= 0) {
  6337. return fetchVersion > (rulesData.ruleVersion || 0);
  6338. }
  6339. fetchVersion = await new Promise(resolve => {
  6340. _GM_xmlhttpRequest({
  6341. url: url.replace(/\/\w+\.json/i, "/version"),
  6342. method: 'GET',
  6343. timeout: 20000,
  6344. headers: {
  6345. 'accept': 'application/json,text/html'
  6346. },
  6347. onload: function(res) {
  6348. let version = parseInt(res.response || res.responseText);
  6349. resolve(version || -1);
  6350. },
  6351. onerror: function(e) {
  6352. resolve(-1);
  6353. },
  6354. ontimeout: function(e) {
  6355. resolve(-1);
  6356. }
  6357. });
  6358. });
  6359. return fetchVersion > (rulesData.ruleVersion || 0);
  6360. }
  6361. async function addNextRule() {
  6362. if (ruleIndex < 0) {
  6363. let now = new Date().getTime();
  6364. storage.setItem("ruleLastUpdate", now);
  6365. storage.setItem("rules", ruleParser.rules);
  6366. let curLength = ruleParser.rules.length;
  6367. if (curLength !== preLength && rulesData.updateNotification) {
  6368. _GM_notification({
  6369. text: `Rules has updated( ${preLength} => ${curLength} )`,
  6370. title: "Pagetual rules updated",
  6371. onclick: (event) => {
  6372. event.preventDefault();
  6373. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  6374. }
  6375. });
  6376. }
  6377. inUpdate = false;
  6378. let rulesDataChanged = false;
  6379. if (fetchVersion >= 0 && rulesData.ruleVersion !== fetchVersion) {
  6380. rulesData.ruleVersion = fetchVersion;
  6381. rulesDataChanged = true;
  6382. }
  6383. if (rulesData.uninited && allOk && ruleUrls.length > 1) {
  6384. rulesData.uninited = false;
  6385. rulesDataChanged = true;
  6386. }
  6387. if (rulesDataChanged) {
  6388. storage.setItem("rulesData", rulesData);
  6389. }
  6390. success();
  6391. } else {
  6392. let rule = ruleUrls[ruleIndex--];
  6393. if (await needUpdate(rule.url, rule.id)) {
  6394. ruleParser.addRuleByUrl(rule.url, rule.id, (json, err) => {
  6395. if (!json) {
  6396. allOk = false;
  6397. fail(rule, err);
  6398. }
  6399. addNextRule();
  6400. });
  6401. } else {
  6402. addNextRule();
  6403. }
  6404. }
  6405. }
  6406. addNextRule();
  6407. }
  6408.  
  6409. function objIsArr(obj) {
  6410. return obj &&
  6411. typeof obj === 'object' &&
  6412. typeof obj.length === 'number' &&
  6413. !(obj.propertyIsEnumerable('length'));
  6414. }
  6415.  
  6416. function isVisible(el, win) {
  6417. if(!el || !el.offsetParent)return false;
  6418. var loopable = true,
  6419. visible = el.nodeName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  6420. while(loopable && visible) {
  6421. el = el.parentNode;
  6422.  
  6423. if(el && !compareNodeName(el, ["body"])) {
  6424. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  6425. }else {
  6426. loopable = false;
  6427. }
  6428. }
  6429. return visible;
  6430. }
  6431.  
  6432. function getElementTop(ele) {
  6433. if (!ele) return 0;
  6434. if (ele.getBoundingClientRect) {
  6435. return ele.getBoundingClientRect().top + document.documentElement.scrollTop;
  6436. }
  6437. var actualTop = ele.offsetTop;
  6438. var current = ele.offsetParent;
  6439. while (current) {
  6440. actualTop += current.offsetTop;
  6441. current = current.offsetParent;
  6442. }
  6443. return actualTop;
  6444. }
  6445.  
  6446. function getElementLeft(ele) {
  6447. if (!ele) return 0;
  6448. if (ele.getBoundingClientRect) {
  6449. return ele.getBoundingClientRect().left + document.documentElement.scrollLeft;
  6450. }
  6451. var actualLeft = ele.offsetLeft;
  6452. var current = ele.offsetParent;
  6453. while (current) {
  6454. actualLeft += current.offsetLeft;
  6455. current = current.offsetParent;
  6456. }
  6457. return actualLeft;
  6458. }
  6459.  
  6460. function getElementBottom(ele) {
  6461. return getElementTop(ele) + (ele.offsetHeight || ele.scrollHeight);
  6462. }
  6463.  
  6464. function getFormatJSON(obj){
  6465. if(!objIsArr(obj) || obj.length === 0)return "";
  6466. return JSON.stringify(obj, null, 4);
  6467. }
  6468.  
  6469. function globMatch(first, second) {
  6470. if (first === '*') {
  6471. return true;
  6472. }
  6473. if (first.length == 0 && second.length == 0){
  6474. return true;
  6475. }
  6476.  
  6477. if (first.length > 1 && first[0] == '*' &&
  6478. second.length == 0){
  6479. return false;
  6480. }
  6481.  
  6482. if ((first.length > 1 && first[0] == '?') ||
  6483. (first.length != 0 && second.length != 0 &&
  6484. first[0] == second[0])){
  6485. return globMatch(first.substring(1),
  6486. second.substring(1));
  6487. }
  6488.  
  6489. if (first.length > 0 && first[0] == '*'){
  6490. return globMatch(first.substring(1), second) ||
  6491. globMatch(first, second.substring(1));
  6492. }
  6493.  
  6494. return false;
  6495. }
  6496.  
  6497. let pageReady = false;
  6498. function initRules(callback) {
  6499. charset = (document.characterSet || document.charset || document.inputEncoding);
  6500. let equiv = document.querySelector('[http-equiv="Content-Type"]');
  6501. if (equiv && equiv.content) {
  6502. let innerCharSet = equiv.content.match(/charset\=([^;]+)/);
  6503. if (!innerCharSet) {
  6504. charsetValid = false;
  6505. } else if (innerCharSet[1].replace("-", "").toLowerCase() != charset.replace("-", "").toLowerCase()) {
  6506. charsetValid = false;
  6507. }
  6508. } else charsetValid = false;
  6509. storage.getItem("rulesData", data => {
  6510. /*0 wedata格式,1 pagetual格式*/
  6511. ruleUrls = [{
  6512. id: 1,
  6513. url: data && data.wedata2github ? 'https://hoothin.github.io/UserScripts/Pagetual/items_all.json' : 'http://wedata.net/databases/AutoPagerize/items_all.json',
  6514. type: 0,
  6515. }];
  6516. if (data) {
  6517. rulesData = data;
  6518. if (data.urls) ruleUrls = ruleUrls.concat(data.urls);
  6519. if (data.sort) {
  6520. let urls = [];
  6521. data.sort.forEach(id => {
  6522. for (let s = 0; s < ruleUrls.length; s++) {
  6523. if (id == ruleUrls[s].id) {
  6524. urls.push(ruleUrls[s]);
  6525. break;
  6526. }
  6527. }
  6528. });
  6529. ruleUrls = urls;
  6530. }
  6531. }
  6532. if (rulesData.lang) {
  6533. setLang(rulesData.lang);
  6534. }
  6535. if (rulesData.firstRun) {
  6536. rulesData.firstRun = false;
  6537. storage.setItem("rulesData", rulesData);
  6538. setTimeout(() => {
  6539. storage.getItem("rulesData", data => {
  6540. if (data.firstRun === false) {
  6541. _GM_openInTab(firstRunPage, {active: true});
  6542. }
  6543. });
  6544. }, 100);
  6545. }
  6546. _GM_registerMenuCommand(i18n("configure"), () => {
  6547. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  6548. });
  6549. if (rulesData.blacklist && rulesData.blacklist.length > 0) {
  6550. let href = location.href.slice(0, 500);
  6551. let commentStart = false;
  6552. for (let i = 0; i < rulesData.blacklist.length; i++) {
  6553. let curGlob = rulesData.blacklist[i];
  6554. if (!curGlob) continue;
  6555. if (curGlob.indexOf("//") == 0) continue;
  6556. if (commentStart) {
  6557. if (/\*\/$/.test(curGlob)) {
  6558. commentStart = false;
  6559. }
  6560. continue;
  6561. }
  6562. if (curGlob.indexOf("/*") == 0) {
  6563. commentStart = true;
  6564. continue;
  6565. }
  6566. if (curGlob.indexOf("/") == 0) {
  6567. let regMatch = curGlob.match(/^\/(.*)\/(\w*)$/);
  6568. if (regMatch && new RegExp(regMatch[1], regMatch[2]).test(href)) {
  6569. forceState == 1;
  6570. return;
  6571. }
  6572. } else if (globMatch(curGlob, href)) {
  6573. forceState == 1;
  6574. return;
  6575. }
  6576. }
  6577. }
  6578. _GM_registerMenuCommand(i18n("editCurrent"), () => {
  6579. picker.start();
  6580. });
  6581. ruleParser.initSavedRules(async () => {
  6582. let upBtnImg = rulesData.upBtnImg, downBtnImg = rulesData.downBtnImg, _sideControllerIcon = rulesData.sideControllerIcon;
  6583. if (upBtnImg && downBtnImg) {
  6584. downSvgCSS = downSvgCSS.replace("transform: rotate(180deg);", "");
  6585. } else if (upBtnImg && !downBtnImg) {
  6586. downBtnImg = upBtnImg;
  6587. } else if(downBtnImg && !upBtnImg) {
  6588. upBtnImg = downBtnImg;
  6589. }
  6590. if (upBtnImg) {
  6591. upSvg = /https?:|data/.test(upBtnImg) ? `<img class="pagetual" src="${upBtnImg}"/>` : `<span>${upBtnImg}</span>`;
  6592. }
  6593. if (downBtnImg) {
  6594. downSvg = /https?:|data/.test(downBtnImg) ? `<img class="pagetual" src="${downBtnImg}"/>` : `<span>${downBtnImg}</span>`;
  6595. }
  6596. if (_sideControllerIcon) {
  6597. sideControllerIcon = /https?:|data/.test(_sideControllerIcon) ? `<img class="pagetual" src="${_sideControllerIcon}"/>` : `<span>${_sideControllerIcon}</span>`;
  6598. }
  6599. setLoadingDiv(rulesData.loadingText || i18n("loadingText"));
  6600. if (typeof(rulesData.opacity) == "undefined") {
  6601. rulesData.opacity = 1;
  6602. }
  6603. if (typeof(rulesData.hideBar) == "undefined") {
  6604. rulesData.hideBar = false;
  6605. }
  6606. if (typeof(rulesData.dbClick2Stop) == "undefined") {
  6607. rulesData.dbClick2Stop = true;
  6608. }
  6609. if (typeof(rulesData.enableWhiteList) == "undefined") {
  6610. rulesData.enableWhiteList = false;
  6611. }
  6612. if (typeof(rulesData.enableHistory) == "undefined") {
  6613. rulesData.enableHistory = false;
  6614. }
  6615. if (typeof(rulesData.openInNewTab) == "undefined") {
  6616. rulesData.openInNewTab = false;
  6617. }
  6618. if (typeof(rulesData.enableDebug) == "undefined") {
  6619. rulesData.enableDebug = true;
  6620. }
  6621. if (typeof(rulesData.updateNotification) == "undefined") {
  6622. rulesData.updateNotification = true;
  6623. }
  6624. if (typeof(rulesData.initRun) == "undefined") {
  6625. rulesData.initRun = true;
  6626. }
  6627. if (typeof(rulesData.preload) == "undefined") {
  6628. rulesData.preload = true;
  6629. }
  6630. if (typeof(rulesData.customFirst) == "undefined") {
  6631. rulesData.customFirst = false;
  6632. }
  6633. if (typeof(rulesData.manualMode) == "undefined") {
  6634. rulesData.manualMode = false;
  6635. }
  6636. if (typeof(rulesData.clickMode) == "undefined") {
  6637. rulesData.clickMode = false;
  6638. }
  6639. if (typeof(rulesData.pageBarMenu) == "undefined") {
  6640. rulesData.pageBarMenu = true;
  6641. }
  6642. if (typeof(rulesData.arrowToScroll) == "undefined") {
  6643. rulesData.arrowToScroll = false;
  6644. }
  6645. if (typeof(rulesData.hideLoadingIcon) == "undefined") {
  6646. rulesData.hideLoadingIcon = false;
  6647. }
  6648. if (typeof(rulesData.hideBarArrow) == "undefined") {
  6649. rulesData.hideBarArrow = false;
  6650. }
  6651. if (typeof(rulesData.lastPageTips) == "undefined") {
  6652. rulesData.lastPageTips = true;
  6653. }
  6654. if (typeof(rulesData.rate) == "undefined") {
  6655. rulesData.rate = 1;
  6656. }
  6657. rate = rulesData.rate;
  6658. if (rulesData.autoLoadNum && rulesData.initRun) {
  6659. autoLoadNum = parseInt(rulesData.autoLoadNum);
  6660. }
  6661. openInNewTab = rulesData.openInNewTab ? 1 : 0;
  6662. enableDebug = rulesData.enableDebug;
  6663.  
  6664. let _nextSwitch = await getListData("nextSwitch", location.host);
  6665. if (typeof(_nextSwitch) !== "undefined") {
  6666. nextIndex = _nextSwitch || 0;
  6667. }
  6668.  
  6669. let _forceState = await getListData("forceState", location.host);
  6670. if (typeof(_forceState) == "undefined") {
  6671. _forceState = await getData("forceState_" + location.host);
  6672. }
  6673. if (typeof(_forceState) == "undefined") {
  6674. _forceState = (rulesData.enableWhiteList ? 1 : 0);
  6675. }
  6676. forceState = _forceState;
  6677.  
  6678. autoScroll = await getListData("autoScroll", location.host + location.pathname) || 0;
  6679.  
  6680. updateDate = await getData("ruleLastUpdate");
  6681.  
  6682. let _loadNowNum = await getData("loadNowNum");
  6683. if (typeof(_loadNowNum) != "undefined") {
  6684. loadNowNum = _loadNowNum;
  6685. }
  6686. let _autoScrollRate = await getData("autoScrollRate");
  6687. if (_autoScrollRate) {
  6688. autoScrollRate = _autoScrollRate;
  6689. }
  6690.  
  6691. author = await getData("author") || "";
  6692.  
  6693. manualPause = !!await getListData("pauseState", location.host);
  6694.  
  6695. let href = location.href.slice(0, 100);
  6696. try {
  6697. if (_unsafeWindow.initedPagetual) {
  6698. if (ruleImportUrlReg.test(href)) {
  6699. showTips(i18n('duplicate'));
  6700. }
  6701. return;
  6702. }
  6703. _unsafeWindow.initedPagetual = true;
  6704. } catch(e) {showTips(e)}
  6705. listenUrl();
  6706. _GM_registerMenuCommand(i18n("update"), () => {
  6707. showTips(i18n("beginUpdate"), "", 60000);
  6708. updateRules(() => {
  6709. showTips(i18n("updateSucc"));
  6710. location.reload();
  6711. },(rule, err) => {
  6712. showTips(`Failed to update ${rule.url} rules!`);
  6713. debug(err);
  6714. });
  6715. });
  6716. _GM_registerMenuCommand(i18n(forceState == 1 ? "enable" : "disableSite"), () => {
  6717. if (forceState == 1) {
  6718. forceState = 0;
  6719. showTips(i18n("enableSiteTips"));
  6720. changeStop(false);
  6721. } else {
  6722. forceState = 1;
  6723. showTips(i18n("disableSiteTips"));
  6724. changeStop(true);
  6725. sideController.remove();
  6726. }
  6727. setListData("forceState", location.host, forceState);
  6728. if (!ruleParser.curSiteRule.url) {
  6729. setTimeout(() => {
  6730. location.reload();
  6731. }, 500);
  6732. }
  6733. });
  6734. _GM_registerMenuCommand(i18n("toggleAutoScroll"), () => {
  6735. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), autoScrollRate)) || 0;
  6736. autoScroll = parseInt(autoScroll) || 0;
  6737. if (autoScroll < 0) autoScroll = 0;
  6738. if (autoScroll && autoScroll != autoScrollRate) {
  6739. autoScrollRate = autoScroll;
  6740. storage.setItem("autoScrollRate", autoScrollRate);
  6741. }
  6742. setListData("autoScroll", location.host + location.pathname, autoScroll);
  6743. startAutoScroll();
  6744. });
  6745. startAutoScroll();
  6746.  
  6747.  
  6748. if (initConfig(href)) return;
  6749. pageReady = true;
  6750. if (forceState == 1) return;
  6751. let now = new Date().getTime();
  6752. if (!updateDate || now - updateDate > 2 * 24 * 60 * 60 * 1000) {
  6753. updateRules(() => {
  6754. }, (rule, err) => {}, true);
  6755. storage.setItem("ruleLastUpdate", now);
  6756. }
  6757. callback();
  6758. });
  6759. });
  6760. }
  6761.  
  6762. function requestDoc(url, callback) {
  6763. let postParams = url.match(/#p{(.*)}$/);
  6764. if (postParams) {
  6765. postParams = postParams[1];
  6766. url = url.replace(/#p{.*/, "");
  6767. }
  6768. let ruleHeaders = ruleParser.curSiteRule.headers;
  6769. let headers = {
  6770. 'Referer': location.href,
  6771. 'User-Agent': navigator.userAgent,
  6772. 'accept': 'text/html,application/xhtml+xml,application/xml',
  6773. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + charset,
  6774. };
  6775. if (ruleHeaders) {
  6776. if (ruleHeaders.referer) {
  6777. headers.referer = ruleHeaders.referer;
  6778. }
  6779. if (ruleHeaders.userAgent) {
  6780. headers.userAgent = ruleHeaders.userAgent;
  6781. }
  6782. if (ruleHeaders.accept) {
  6783. headers.accept = ruleHeaders.accept;
  6784. }
  6785. if (ruleHeaders.contentType) {
  6786. headers.contentType = ruleHeaders.contentType;
  6787. let ruleCharset = ruleHeaders.contentType.match(/charset\=([^;]+)/);
  6788. if (ruleCharset) charset = ruleCharset[1];
  6789. }
  6790. if (ruleHeaders.cookie) {
  6791. headers.cookie = ruleHeaders.cookie;
  6792. }
  6793. }
  6794. _GM_xmlhttpRequest({
  6795. url: url,
  6796. method: postParams ? 'POST' : 'GET',
  6797. data: postParams,
  6798. overrideMimeType: 'text/html;charset=' + charset,
  6799. headers: headers,
  6800. timeout: 50000,
  6801. onload: async function(res) {
  6802. if (isPause) return callback(false);
  6803. var doc = null, response = res.response;
  6804. let preCode = ruleParser.curSiteRule.pageElementPre || ruleParser.curSiteRule.pagePre;
  6805. if (preCode) {
  6806. try {
  6807. if (typeof preCode == 'function') {
  6808. response = preCode(response);
  6809. } else if (preCode.length == 2) {
  6810. response = response.replace(new RegExp(preCode[0], "gi"), preCode[1]);
  6811. } else {
  6812. response = Function("response",'"use strict";' + preCode)(response);
  6813. }
  6814. } catch(e) {
  6815. debug(e);
  6816. }
  6817. }
  6818. try {
  6819. doc = document.implementation.createHTMLDocument('');
  6820. doc.documentElement.innerHTML = response;
  6821. let base = doc.querySelector("base");
  6822. ruleParser.basePath = base ? base.href : url;
  6823. } catch (e) {
  6824. debug('parse error:' + e.toString());
  6825. }
  6826. if (charsetValid && !ruleHeaders) {
  6827. let equiv = doc.querySelector('[http-equiv="Content-Type"]');
  6828. if (equiv && equiv.content) {
  6829. let innerCharSet = equiv.content.match(/charset\=([^;]+)/);
  6830. if (innerCharSet && innerCharSet[1].replace("-", "").toLowerCase() != charset.replace("-", "").toLowerCase()) {
  6831. charset = innerCharSet[1];
  6832. return requestDoc(url, callback);
  6833. }
  6834. }
  6835. }
  6836. let pageElement = ruleParser.getPageElement(doc);
  6837. if ((!pageElement || pageElement.length == 0) && res.status >= 400) {
  6838. debug(res.status + " " + url, "Error status");
  6839. return callback(false);
  6840. }
  6841. if (inCors && (!pageElement || pageElement.length == 0) && ruleParser.curSiteRule.smart) {
  6842. let article;
  6843. for (let i = 0; i < mainSel.length; i++) {
  6844. article = doc.querySelectorAll(mainSel[i]);
  6845. if (article && article.length === 1) break;
  6846. }
  6847. if (article && article.length == 1) {
  6848. article = article[0];
  6849. ruleParser.curSiteRule.pageElement = article.nodeName.toLowerCase() + (article.id ? "#" + article.id : "") + (article.className ? "." + article.className.replace(/ /g, ".") : "") + ">*";
  6850. pageElement = article.children;
  6851. } else {
  6852. ruleParser.curSiteRule.pageElement = allOfBody;
  6853. pageElement = ruleParser.getPageElement(doc);
  6854. }
  6855. ruleParser.getInsert(true);
  6856. }
  6857. //只有1的話怕不是圖片哦
  6858. if (pageElement && (pageElement.length > 1 || (pageElement.length == 1 && !compareNodeName(pageElement[0], ["img"])))) {
  6859. await ruleParser.insertPage(doc, pageElement, url, callback, false);
  6860. if (ruleParser.curSiteRule.action == 1) {
  6861. isLoading = true;
  6862. requestFromIframe(url, async (doc, eles) => {
  6863. if (eles) {
  6864. await ruleParser.insertPage(doc, eles, url, callback, true);
  6865. } else isLoading = false;
  6866. });
  6867. } else ruleParser.curSiteRule.action = 0;
  6868. } else if ((ruleParser.curSiteRule.smart || curPage == 1) && !inCors) {
  6869. ruleParser.curSiteRule.action = 1;
  6870. requestFromIframe(url, async (doc, eles) => {
  6871. if (eles) {
  6872. await ruleParser.insertPage(doc, eles, url, callback, true);
  6873. } else isLoading = false;
  6874. });
  6875. } else {
  6876. debug("Stop as no page element");
  6877. ruleParser.noValidContent(url);
  6878. changeStop(true);
  6879. callback(false);
  6880. }
  6881. },
  6882. onerror: function(e) {
  6883. debug(e, "NetError");
  6884. callback(false);
  6885. },
  6886. ontimeout: function(e) {
  6887. debug(e, "NetTimeout");
  6888. callback(false);
  6889. }
  6890. });
  6891. }
  6892.  
  6893. function initPage() {
  6894. ruleParser.initPage(() => {
  6895. if (ruleParser.curSiteRule.autoLoadNum) {
  6896. autoLoadNum = ruleParser.curSiteRule.autoLoadNum;
  6897. }
  6898. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  6899. _GM_registerMenuCommand(i18n("nextSwitch"), () => {
  6900. nextSwitch.start();
  6901. });
  6902. }
  6903. if (ruleParser.nextLinkHref) {
  6904. let isJs = ruleParser.hrefIsJs(ruleParser.nextLinkHref);
  6905. if (!isJs) {
  6906. let inForce = (forceState == 2 || forceState == 3);
  6907. _GM_registerMenuCommand(i18n(inForce ? "cancelForceIframe" : "forceIframe"), () => {
  6908. if (inForce) {
  6909. setListData("forceState", location.host, "");
  6910. } else {
  6911. let _state = ruleParser.curSiteRule.action > 0 || confirm(i18n("forceAllBody")) ? 2 : 3;
  6912. setListData("forceState", location.host, _state);
  6913. }
  6914. setTimeout(() => {
  6915. location.reload();
  6916. }, 500);
  6917. });
  6918. }
  6919. _GM_registerMenuCommand(i18n("loadNow"), () => {
  6920. if (autoLoadNum != -1) {
  6921. autoLoadNum = -1;
  6922. return;
  6923. }
  6924. let loadNum = window.prompt(i18n("loadConfirm"), loadNowNum);
  6925. if (loadNum === "" || loadNum === null) return;
  6926. loadNum = Math.abs(parseInt(loadNum)) || 0;
  6927. if (loadNowNum != loadNum) {
  6928. loadNowNum = loadNum;
  6929. storage.setItem("loadNowNum", loadNowNum);
  6930. }
  6931. autoLoadNum = loadNum;
  6932. nextPage();
  6933. });
  6934. }
  6935. initListener();
  6936. });
  6937. }
  6938.  
  6939. var pageBarStyle, mainStyleEle, mainStyleStyle;
  6940. function initView() {
  6941. if (!mainStyleStyle) {
  6942. mainStyleStyle = `
  6943. .pagetual_pageBar{
  6944. -moz-transition:all 0.3s ease-in-out 0s;
  6945. -webkit-transition:all 0.3s ease-in-out 0s;
  6946. transition:all 0.3s ease-in-out 0s;
  6947. font-family: Arial,sans-serif !important;
  6948. text-align: center !important;
  6949. }
  6950. .pagetual_pageBar.stop {
  6951. -webkit-filter: invert(100%);
  6952. filter: invert(100%);
  6953. opacity: 1!important;
  6954. }
  6955. .pagetual_pageBar.hide {
  6956. display: none!important;
  6957. }
  6958. .pagetual-hide {
  6959. display: none!important;
  6960. }
  6961. .pagetual_pageBar:hover {
  6962. opacity: 1!important;
  6963. box-shadow: 0px 0px 10px 0px #000000aa;
  6964. border-radius: 20px;
  6965. background-color: rgb(240 240 240 / 80%);
  6966. border-color: transparent!important;
  6967. }
  6968. .pagetual_pageBar span {
  6969. vertical-align: super;
  6970. }
  6971. .pagetual_pageBar a::before,
  6972. .pagetual_pageBar a::after {
  6973. content: none;
  6974. }
  6975. .pagetual_pageBar a>span {
  6976. margin-top: 0!important;
  6977. pointer-events: none;
  6978. padding: unset;
  6979. opacity: 0;
  6980. -moz-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  6981. -webkit-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  6982. transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  6983. transform: none;
  6984. left: 0;
  6985. margin-left: calc(50% - 20px);
  6986. }
  6987. .pagetual_pageBar a>span:hover {
  6988. color: red;
  6989. }
  6990. .pagetual_pageBar a:hover>span {
  6991. opacity: 1!important;
  6992. }
  6993. .pagetual_pageBar span.prevScreen,
  6994. .pagetual_pageBar span.nextScreen {
  6995. display: block!important;
  6996. top: unset !important;
  6997. padding: unset !important;
  6998. opacity: 0!important;
  6999. }
  7000. .pagetual_pageBar a:hover>span.prevScreen {
  7001. margin-top: -${rulesData.opacity == 1 ? 31 : 30}px!important;
  7002. pointer-events: all;
  7003. }
  7004. .pagetual_pageBar span.refreshRing {
  7005. position: absolute;
  7006. top: 0;
  7007. opacity: 0;
  7008. height: 30px;
  7009. margin-left: calc(50% - 23px);
  7010. display: block!important;
  7011. }
  7012. .pagetual_pageBar span.refreshRing>svg {
  7013. background: white;
  7014. border-radius: 50%;
  7015. }
  7016. .pagetual_pageBar a:hover>span.refreshRing {
  7017. opacity: 0.3;
  7018. -webkit-animation: pagetual_ring 2.0s infinite linear;
  7019. animation: pagetual_ring 2.0s infinite linear;
  7020. }
  7021. @-webkit-keyframes pagetual_ring {
  7022. 0% { -webkit-transform: rotate(0deg) }
  7023. 100% {
  7024. -webkit-transform: rotate(360deg);
  7025. }
  7026. }
  7027. @keyframes pagetual_ring {
  7028. 0% {
  7029. transform: rotate(0deg);
  7030. -webkit-transform: rotate(0deg);
  7031. } 100% {
  7032. transform: rotate(360deg);
  7033. -webkit-transform: rotate(360deg);
  7034. }
  7035. }
  7036. .pagetual_pageBar a:hover>span.nextScreen {
  7037. margin-top: 30px!important;
  7038. pointer-events: all;
  7039. }
  7040. .pagetual_pageBar span>svg {
  7041. -moz-transition:transform 0.5s ease, opacity 0.3s ease;
  7042. -webkit-transition:transform 0.5s ease, opacity 0.3s ease;
  7043. transition:transform 0.5 ease, opacity 0.3s ease;
  7044. opacity: 0;
  7045. }
  7046. .pagetual_pageBar.stop span>svg{
  7047. opacity: 1;
  7048. }
  7049. .pagetual_pageBar.stop span>svg>path{
  7050. transform: scale(.8);
  7051. transform-origin: center;
  7052. -moz-transition:transform 0.3s ease;
  7053. -webkit-transition:transform 0.3s ease;
  7054. transition:transform 0.3 ease;
  7055. }
  7056. .pagetual_pageBar.stop:hover span>svg>path{
  7057. transform: unset;
  7058. }
  7059. .pagetual_pageBar:hover span>svg {
  7060. opacity: 1;
  7061. }
  7062. .pagetual_pageBar span>svg.upSvg:hover {
  7063. transform: rotate(360deg) scale3d(1.2, 1.2, 1.2);
  7064. }
  7065. .pagetual_pageBar span>svg.downSvg:hover {
  7066. transform: rotate(540deg) scale3d(1.2, 1.2, 1.2)!important;
  7067. }
  7068. .pagetual_pageBar .pagetual_pageNum{
  7069. color: #55555f;
  7070. }
  7071. .pagetual_pageBar .pagetual_pageNum:hover{
  7072. color: #ff6464;
  7073. }
  7074. .pagetual_tipsWords {
  7075. font-size: 50px;
  7076. font-weight: bold;
  7077. font-family: "黑体", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
  7078. "Oxygen", "Ubuntu", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
  7079. "Segoe UI Emoji", "Segoe UI Symbol";
  7080. color: #ffffff;
  7081. min-height: 70px;
  7082. max-width: 80%;
  7083. line-height: 1.5;
  7084. position: fixed;
  7085. left: 50%;
  7086. top: 10%;
  7087. margin-left: -99999px;
  7088. padding: 0 15px;
  7089. z-index: 2147483647;
  7090. background-color: #000;
  7091. border: 1px solid #303030;
  7092. border-radius: 10px;
  7093. opacity: 0;
  7094. filter: alpha(opacity=65);
  7095. box-shadow: 5px 5px 20px 0px #000;
  7096. -moz-transition:opacity 0.3s ease-in-out 0s;
  7097. -webkit-transition:opacity 0.3s ease-in-out 0s;
  7098. transition:opacity 0.3s ease-in-out 0s;
  7099. pointer-events: none;
  7100. word-break: break-all;
  7101. }
  7102. .pagetual_tipsWords>a {
  7103. color: #ffffff;
  7104. }
  7105. .pagetual_loading {
  7106. width: 50px;
  7107. height: 50px;
  7108. margin: 10px auto;
  7109. border-radius: 100%;
  7110. display: flex;
  7111. -webkit-animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  7112. animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  7113. }
  7114. @-webkit-keyframes pagetual_loading_scaleout {
  7115. 0% { -webkit-transform: scale(0.0) }
  7116. 100% {
  7117. -webkit-transform: scale(1.0);
  7118. opacity: 0;
  7119. }
  7120. }
  7121. @keyframes pagetual_loading_scaleout {
  7122. 0% {
  7123. transform: scale(0.0);
  7124. -webkit-transform: scale(0.0);
  7125. } 100% {
  7126. transform: scale(1.0);
  7127. -webkit-transform: scale(1.0);
  7128. opacity: 0;
  7129. }
  7130. }
  7131. .pagetual_loading_text {
  7132. white-space: nowrap;
  7133. -webkit-animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  7134. animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  7135. }
  7136. @-webkit-keyframes pagetual_loading_opacity {
  7137. 0% { opacity: 1 }
  7138. 50% { opacity: 0.2 }
  7139. 100% { opacity: 1 }
  7140. }
  7141. @keyframes pagetual_loading_opacity {
  7142. 0% { opacity: 1 }
  7143. 50% { opacity: 0.2 }
  7144. 100% { opacity: 1 }
  7145. }
  7146. `;
  7147. 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%);"}`;
  7148. }
  7149. if (!mainStyleEle || !mainStyleEle.parentNode) {
  7150. mainStyleEle = _GM_addStyle(mainStyleStyle);
  7151. }
  7152. }
  7153. var loadingDiv = document.createElement("div");
  7154. 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;";
  7155.  
  7156. 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;`;
  7157. function setLoadingDiv(loadingText) {
  7158. 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>`}`);
  7159. }
  7160.  
  7161. 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>`;
  7162. 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;`;
  7163. 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>`;
  7164. 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);`;
  7165.  
  7166. 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;`;
  7167. 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;`;
  7168. var sideControllerIcon = '';
  7169.  
  7170. var tipsWords = document.createElement("div");
  7171. tipsWords.className = "pagetual_tipsWords";
  7172.  
  7173. function changeStop(stop) {
  7174. isPause = stop;
  7175. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar,#pagetual-sideController"), bar => {
  7176. if (isPause) {
  7177. bar.classList.add("stop");
  7178. } else {
  7179. bar.classList.remove("stop");
  7180. }
  7181. });
  7182. if (!isPause) ruleParser.showAddedElements();
  7183. manualPause = isPause;
  7184. if (sideController.inited) setListData("pauseState", location.host, isPause ? true : "");
  7185. }
  7186.  
  7187. function changeHideBar(hide) {
  7188. isHideBar = hide;
  7189. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar"), bar => {
  7190. if (isHideBar) {
  7191. bar.classList.add("hide");
  7192. } else {
  7193. bar.classList.remove("hide");
  7194. }
  7195. });
  7196. }
  7197.  
  7198. function isInViewPort(element) {
  7199. if (!getBody(document).contains(element)) return false;
  7200. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  7201. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  7202. const {
  7203. top,
  7204. right,
  7205. bottom,
  7206. left,
  7207. } = element.getBoundingClientRect();
  7208.  
  7209. return (
  7210. top >= 0 &&
  7211. left >= 0 &&
  7212. right <= viewWidth + 1 &&
  7213. top <= viewHeight * rate &&
  7214. isVisible(element, _unsafeWindow)
  7215. );
  7216. }
  7217.  
  7218. function getPageBar() {
  7219. let preBar = null, nextBar = null;
  7220. let pageBars = [].slice.call(document.querySelectorAll(".pagetual_pageBar"));
  7221. for (let i = 0; i < pageBars.length; i++) {
  7222. let pageBar = pageBars[i];
  7223. if (!pageBar || !getBody(document).contains(pageBar)) continue;
  7224. let {
  7225. top,
  7226. right,
  7227. bottom,
  7228. left,
  7229. } = pageBar.getBoundingClientRect();
  7230. if (top > 500) {
  7231. nextBar = pageBar;
  7232. preBar = (i - 1 >= 0 ? pageBars[i - 1] : null);
  7233. if (pageBar && getBody(document).contains(pageBar)) {
  7234. let {
  7235. top,
  7236. right,
  7237. bottom,
  7238. left,
  7239. } = pageBar.getBoundingClientRect();
  7240. if (top < -500) {
  7241. preBar = pageBar;
  7242. } else preBar = (i - 2 >= 0 ? pageBars[i - 2] : null);
  7243. }
  7244. break;
  7245. }
  7246. }
  7247. if (!nextBar) preBar = pageBars[pageBars.length - 2];
  7248. return {preBar: preBar, nextBar: nextBar};
  7249. }
  7250.  
  7251. var urlChanged = false;
  7252. var urlChanging = false;
  7253. var urlchangeHandler = e => {
  7254. if (ruleParser && ruleParser.curSiteRule && ruleParser.curSiteRule.listenUrlChange == false) return;
  7255. isPause = true;
  7256. setTimeout(() => {
  7257. lastActiveUrl = location.href;
  7258. if (urlChanging) return;
  7259. urlChanging = true;
  7260. let href = location.href.slice(0, 60);
  7261. if (href == configPage[1]) {
  7262. setTimeout(() => {
  7263. initConfig(href);
  7264. urlChanging = false;
  7265. }, 1000);
  7266. } else {
  7267. setTimeout(() => {
  7268. if (guidePage.test(href)) {
  7269. setTimeout(() => {
  7270. initConfig(href);
  7271. urlChanging = false;
  7272. }, 1000);
  7273. } else {
  7274. ruleParser.urlChanged();
  7275. if (!ruleParser.nextLinkHref) {
  7276. isLoading = false;
  7277. }
  7278. urlChanging = false;
  7279. //if (!pageReady && !ruleImportUrlReg.test(href)) location.reload();
  7280. }
  7281. }, 500);
  7282. }
  7283. }, 1);
  7284. };
  7285. window.addEventListener('pagetual_pushState', urlchangeHandler);
  7286. /*var _wr = function(type) {
  7287. var orig = history[type];
  7288. return function() {
  7289. var rv = orig.apply(this, arguments);
  7290. var e = new Event('pagetual_' + type);
  7291. e.arguments = arguments;
  7292. window.dispatchEvent(e);
  7293. return rv;
  7294. };
  7295. };
  7296. history.pushState = _wr('pushState');*/
  7297.  
  7298. function listenUrl() {
  7299. var prevPathname = window.location.pathname;
  7300. var prevSearch = window.location.search;
  7301. var checkUrlTime = 100;
  7302. var checkUrlTimer;
  7303. var checkClickedEle = null;
  7304. var checkFunc = () => {
  7305. if (forceState == 1) return;
  7306. if (checkClickedEle) {
  7307. if (!clickedSth && checkClickedEle && checkClickedEle.nodeName) {
  7308. if (compareNodeName(checkClickedEle, ["a", "button"])) {
  7309. clickedSth = true;
  7310. } else {
  7311. let targetStyle = _unsafeWindow.getComputedStyle(checkClickedEle);
  7312. if (targetStyle.cursor == "pointer") clickedSth = true;
  7313. }
  7314. }
  7315. checkClickedEle = null;
  7316. }
  7317. if (checkUrlTime < 5000) {
  7318. checkUrlTime += checkUrlTime>>1;
  7319. }
  7320. clearTimeout(checkUrlTimer);
  7321. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7322. if (document.hidden) return;
  7323. if (!ruleParser.canListenUrlChange()) {
  7324. return;
  7325. }
  7326. if ((prevPathname !== window.location.pathname || prevSearch !== window.location.search) && window.location.href != ruleParser.historyUrl) {
  7327. checkUrlTime = 2000;
  7328. urlWillChange = true;
  7329. var e = new Event('pagetual_pushState');
  7330. e.arguments = arguments;
  7331. window.dispatchEvent(e);
  7332. clickedSth = false;
  7333. }
  7334. prevPathname = window.location.pathname;
  7335. prevSearch = window.location.search;
  7336. };
  7337. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7338.  
  7339. document.addEventListener("click", e => {
  7340. if (!checkClickedEle) {
  7341. checkClickedEle = e.target;
  7342. checkUrlTime = 300;
  7343. clearTimeout(checkUrlTimer);
  7344. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  7345. }
  7346. });
  7347. }
  7348.  
  7349. let scrollContainer;
  7350. function distToBottom () {
  7351. let scrolly = window.scrollY;
  7352. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  7353. if (!scrollContainer || !document.documentElement.contains(scrollContainer)) {
  7354. if (curPage > 1 || ruleParser.nextLinkHref) {
  7355. let pageEle = ruleParser.getPageElement(document);
  7356. if (pageEle && pageEle.length) {
  7357. let parent = pageEle[0].parentNode, pageScrollY = parent.scrollTop;
  7358. while (parent && pageScrollY == 0) {
  7359. parent = parent.parentNode;
  7360. pageScrollY = parent.scrollTop;
  7361. }
  7362. if (pageScrollY) {
  7363. scrollContainer = parent;
  7364. return scrollContainer.scrollHeight - pageScrollY - windowHeight;
  7365. }
  7366. }
  7367. }
  7368. }
  7369. if (scrollContainer) {
  7370. return scrollContainer.scrollHeight - scrollContainer.scrollTop - windowHeight;
  7371. }
  7372.  
  7373. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7374. return scrollH - scrolly - windowHeight;
  7375. }
  7376.  
  7377. let scrollHandler, clickToResetHandler, dblclickHandler, keydownHandler, hashchangeHandler, manualModeKeyHandler, pagetualNextHandler, keyupHandler;
  7378. function initListener () {
  7379. document.removeEventListener('scroll', scrollHandler, true);
  7380. document.removeEventListener('wheel', scrollHandler, true);
  7381. document.removeEventListener('dblclick', dblclickHandler);
  7382. document.removeEventListener('keydown', keydownHandler);
  7383. window.removeEventListener('hashchange', hashchangeHandler, false);
  7384. document.removeEventListener('keydown', manualModeKeyHandler);
  7385. document.removeEventListener('pagetual.next', pagetualNextHandler, false);
  7386. document.removeEventListener('keyup', keyupHandler);
  7387. let loadmoreBtn, loadingMore = true, lastScroll = 0, checkLoadMoreTimes = 0;
  7388. if (ruleParser.curSiteRule.smart) {
  7389. loadingMore = false;
  7390. } else if (ruleParser.curSiteRule.loadMore) {
  7391. loadingMore = false;
  7392. }
  7393. clickMode = typeof ruleParser.curSiteRule.clickMode == 'undefined' ? rulesData.clickMode : ruleParser.curSiteRule.clickMode;
  7394. let clickingNext = false;
  7395. let clickNext = async () => {
  7396. if (clickingNext) return;
  7397. clickingNext = true;
  7398. setTimeout(() => {
  7399. clickingNext = false;
  7400. }, 1500);
  7401. let nextLink = ruleParser.nextLinkHref;
  7402. if (!nextLink) return;
  7403. let isJs = ruleParser.hrefIsJs(nextLink);
  7404. if (isJs) {
  7405. let nextBtn = ruleParser.nextLinkEle;
  7406. if (!nextBtn || !nextBtn.offsetParent) nextBtn = await ruleParser.getNextLink(document, true);
  7407. if (nextBtn) emuClick(nextBtn);
  7408. } else {
  7409. window.location.href = nextLink;
  7410. }
  7411. };
  7412. let checkScrollReach = () => {
  7413. let dist = distToBottom();
  7414. if (clickMode) {
  7415. if (dist < 10) {
  7416. clickNext();
  7417. }
  7418. } else if (dist < bottomGap) {
  7419. nextPage();
  7420. }
  7421. };
  7422. scrollHandler = e => {
  7423. if (urlChanged && !isLoading) {
  7424. ruleParser.initPage(() => {});
  7425. urlChanged = false;
  7426. loadingMore = false;
  7427. return;
  7428. }
  7429. if (isPause) return;
  7430. if (!loadingMore) {
  7431. loadmoreBtn = getLoadMore(document, loadmoreBtn);
  7432. if (loadmoreBtn) {
  7433. if (isInViewPort(loadmoreBtn)) {
  7434. emuClick(loadmoreBtn);
  7435. loadingMore = true;
  7436. setTimeout(() => {loadingMore = false}, 200);
  7437. }
  7438. } else {
  7439. loadingMore = true;
  7440. if (!ruleParser.curSiteRule.smart || checkLoadMoreTimes++ < 3) {
  7441. setTimeout(() => {loadingMore = false}, 200);
  7442. }
  7443. }
  7444. }
  7445. if (!isLoading && !stopScroll) {
  7446. checkScrollReach();
  7447. }
  7448. ruleParser.changeVisibility();
  7449. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  7450. if (ruleParser.curSiteRule.lockScroll) {
  7451. if (isLoading && Math.abs(lastScroll - curScroll) > 350) {
  7452. getBody(document).scrollTop = lastScroll;
  7453. document.documentElement.scrollTop = lastScroll;
  7454. } else {
  7455. lastScroll = curScroll;
  7456. }
  7457. }
  7458. if (targetY >= 0) {
  7459. if (Math.abs(targetY - curScroll) < 100) {
  7460. targetY = -1;
  7461. }
  7462. }
  7463. };
  7464. dblclickHandler = e => {
  7465. if (forceState == 1 || compareNodeName(e.target, ["input", "textarea", "select", "a", "button", "svg", "use", "img", "path"])) return;
  7466. if (!rulesData.dbClick2StopKey) {
  7467. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  7468. (rulesData.dbClick2StopAlt && !e.altKey) ||
  7469. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  7470. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  7471. return;
  7472. }
  7473. }
  7474. if (!compareNodeName(e.target, ["body"]) && !e.target.classList.contains('pagetual_pageBar')) {
  7475. try {
  7476. let selection = window.getSelection();
  7477. let selStr = selection.toString().trim();
  7478. if (!selStr) {
  7479. selection = selection.getRangeAt(0);
  7480. selStr = selection && selection.cloneContents().children[0];
  7481. if (selStr && !compareNodeName(selStr, ["img"])) selStr = false;
  7482. }
  7483. if (selStr) {
  7484. return;
  7485. }
  7486. } catch (e) {}
  7487. }
  7488. if (rulesData.dbClick2Stop && (ruleParser.nextLinkHref || loadmoreBtn)) {
  7489. setTimeout(() => {
  7490. if (rulesData.hideBarButNoStop || rulesData.hideBar) {
  7491. changeHideBar(!isHideBar);
  7492. }
  7493. if (!rulesData.hideBarButNoStop) {
  7494. changeStop(!isPause);
  7495. showTips(i18n(isPause ? "disable" : "enable"));
  7496. }
  7497. if (!isPause) {
  7498. checkScrollReach();
  7499. }
  7500. }, 10);
  7501. }
  7502. };
  7503. document.addEventListener('dblclick', dblclickHandler);
  7504. clickToResetHandler = e => {
  7505. if (!ruleParser.nextLinkHref) isLoading = false;
  7506. };
  7507. document.addEventListener('click', clickToResetHandler);
  7508. if (rulesData.dbClick2StopKey) {
  7509. keydownHandler = e => {
  7510. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  7511. (rulesData.dbClick2StopAlt && !e.altKey) ||
  7512. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  7513. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  7514. return;
  7515. }
  7516. if (document.activeElement &&
  7517. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  7518. document.activeElement.contentEditable == 'true')) {
  7519. return;
  7520. }
  7521. var key = e.key.toLowerCase();
  7522. if (rulesData.dbClick2StopKey.toLowerCase() == key) {
  7523. if (forceState == 1) {
  7524. forceState = 0;
  7525. showTips(i18n("enableSiteTips"));
  7526. changeStop(false);
  7527. } else {
  7528. forceState = 1;
  7529. showTips(i18n("disableSiteTips"));
  7530. changeStop(true);
  7531. sideController.remove();
  7532. }
  7533. if (!ruleParser.curSiteRule.url) {
  7534. setListData("forceState", location.host, forceState);
  7535. setTimeout(() => {
  7536. location.reload();
  7537. }, 500);
  7538. }
  7539. }
  7540. };
  7541. document.addEventListener('keydown', keydownHandler);
  7542. }
  7543. if (ruleParser.curSiteRule.listenHashChange) {
  7544. hashchangeHandler = () => {
  7545. isPause = true;
  7546. ruleParser.urlChanged();
  7547. if (!ruleParser.nextLinkHref) isLoading = false;
  7548. };
  7549. window.addEventListener('hashchange', hashchangeHandler, false);
  7550. }
  7551. let manualMode = typeof ruleParser.curSiteRule.manualMode == 'undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode;
  7552. if (manualMode) {
  7553. manualModeKeyHandler = e => {
  7554. if (document.activeElement &&
  7555. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  7556. document.activeElement.contentEditable == 'true')) {
  7557. return;
  7558. }
  7559. if (e.keyCode == 39) {
  7560. clickNext();
  7561. } else if (e.keyCode == 37) {
  7562. history.back();
  7563. }
  7564. };
  7565. document.addEventListener('keydown', manualModeKeyHandler);
  7566. pagetualNextHandler = () => {
  7567. clickNext();
  7568. };
  7569. document.addEventListener('pagetual.next', pagetualNextHandler, false);
  7570. return;
  7571. }
  7572. if (rulesData.arrowToScroll) {
  7573. keyupHandler = e => {
  7574. if (document.activeElement &&
  7575. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  7576. document.activeElement.contentEditable == 'true')) {
  7577. return;
  7578. }
  7579. if (e.keyCode == 39) {
  7580. let nextPageBar=getPageBar().nextBar;
  7581. if (nextPageBar) {
  7582. scrollToPageBar(nextPageBar);
  7583. } else {
  7584. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  7585. window.scrollTo({ top: scrollTop + (window.innerHeight || document.documentElement.clientHeight), behavior: 'instant'});
  7586. }
  7587. } else if (e.keyCode == 37) {
  7588. let prePageBar = getPageBar().preBar;
  7589. if (prePageBar) {
  7590. scrollToPageBar(prePageBar);
  7591. } else {
  7592. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  7593. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'instant'});
  7594. }
  7595. }
  7596. };
  7597. document.addEventListener('keyup', keyupHandler);
  7598. }
  7599. if (!ruleParser.curSiteRule.wheel) {
  7600. document.addEventListener('scroll', scrollHandler, true);
  7601. }
  7602. document.addEventListener('wheel', scrollHandler, true);
  7603. }
  7604.  
  7605. let hideTipsTimeout;
  7606. function showTips(content, href, time, wordColor, backColor) {
  7607. initView();
  7608. document.documentElement.appendChild(tipsWords);
  7609. tipsWords.style.color = wordColor || 0xFFFFFF;
  7610. tipsWords.style.backgroundColor = backColor || 0x000;
  7611. let _time = 1500;
  7612. if (href) {
  7613. _time = 3500;
  7614. tipsWords.innerHTML = createHTML(`<a href='${href}' target='_blank'>${content}</a>`);
  7615. tipsWords.style.pointerEvents = 'all';
  7616. } else {
  7617. tipsWords.innerHTML = createHTML(content);
  7618. }
  7619. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  7620. setTimeout(() => {
  7621. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  7622. }, 0);
  7623. setTimeout(() => {
  7624. tipsWords.style.opacity = 0.8;
  7625. clearTimeout(hideTipsTimeout);
  7626. hideTipsTimeout = setTimeout(() => {
  7627. tipsWords.style.opacity = 0;
  7628. tipsWords.style.pointerEvents = '';
  7629. }, time || _time);
  7630. }, 1);
  7631. }
  7632.  
  7633. const loadmoreReg = /^\s*((点击)?加载更多|(點擊)?加載更多|load\s*more|もっと読み込む)[.…]*\s*$/i;
  7634. 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";
  7635. function getLoadMore(doc, loadmoreBtn) {
  7636. if (!loadmoreBtn || !getBody(doc).contains(loadmoreBtn) || /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  7637. if (!ruleParser.curSiteRule.smart && !ruleParser.curSiteRule.loadMore) return null;
  7638. if (loadmoreBtn) return loadmoreBtn;
  7639. let btnSel = ruleParser.curSiteRule.loadMore || defaultLoadmoreSel;
  7640. if (btnSel) {
  7641. loadmoreBtn = getElement(btnSel, doc, null, true);
  7642. }
  7643. if (!loadmoreBtn) {
  7644. let buttons = doc.querySelectorAll("input,button,a,div[onclick]");
  7645. for (let i = 0; i < buttons.length; i++) {
  7646. let button = buttons[i];
  7647. if (!button.innerText || button.innerText.length > 20) continue;
  7648. if (button && loadmoreReg.test(button.innerText)) {
  7649. loadmoreBtn = button;
  7650. break;
  7651. }
  7652. }
  7653. }
  7654. if (loadmoreBtn && !ruleParser.curSiteRule.loadMore && loadmoreBtn.dataset.ajax !== "true") {
  7655. let href = loadmoreBtn.getAttribute("href");
  7656. if (href && href != "/" && !ruleParser.hrefIsJs(href)) {
  7657. loadmoreBtn = null;
  7658. }
  7659. }
  7660. if (loadmoreBtn && /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  7661. if (loadmoreBtn) debug(loadmoreBtn, 'Load more button');
  7662. return loadmoreBtn;
  7663. }
  7664.  
  7665. var targetY = -1;
  7666. function scrollToPageBar(bar) {
  7667. if (window.pageYOffset == 0) {
  7668. bar.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" });
  7669. } else {
  7670. let yOffset = -20;
  7671. if (typeof ruleParser.curSiteRule.pageBarTop !== 'undefined') {
  7672. yOffset = -ruleParser.curSiteRule.pageBarTop;
  7673. }
  7674. targetY = bar.getBoundingClientRect().top + window.pageYOffset + yOffset;
  7675. window.scrollTo({ top: targetY, behavior: 'smooth'});
  7676. }
  7677. }
  7678.  
  7679. const pageNumReg=/[&\/\?](p=|page[=\/_-]?)\d+|[_-]\d+\./;
  7680. function createPageBar(url) {
  7681. curPage++;
  7682. sideController.setup();
  7683. let posEle = null;
  7684. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7685. let insert = ruleParser.getInsert();
  7686. if (!insert || !insert.parentNode) return;
  7687. if (forceState == 2) {
  7688. posEle = getBody(document);
  7689. posEle = posEle.children[posEle.children.length - 1];
  7690. } else {
  7691. posEle = insert;
  7692. }
  7693. while (posEle && !posEle.offsetParent) {
  7694. posEle = posEle.previousElementSibling || posEle.parentNode;
  7695. }
  7696. if (posEle) {
  7697. let actualBottom = getElementBottom(posEle);
  7698. bottomGap = scrollH - actualBottom + (window.innerHeight || document.documentElement.clientHeight) * rate;
  7699. if (bottomGap < 100) bottomGap = 100;
  7700. } else {
  7701. bottomGap = 1000;
  7702. }
  7703. if (rulesData.opacity == 0 || ruleParser.curSiteRule.pageBar === 0) return null;
  7704. url = url.replace(/#p{.*/, "");
  7705. let example = (ruleParser.curSiteRule.insertPos == 2 || ruleParser.curSiteRule.insertPos == "in") ? insert.children[0] : (insert.parentNode.children[0] || insert);
  7706. while (example && (compareNodeName(example, ["script", "style"]) || example.className == "pagetual_pageBar")) {
  7707. example = example.nextElementSibling;
  7708. }
  7709. if (!example || !example.parentNode) example = insert;
  7710. if (example.nodeType != 1) {
  7711. example = example.previousElementSibling || example.parentNode;
  7712. if (!example || example.nodeType != 1) return;
  7713. }
  7714. let exampleStyle = _unsafeWindow.getComputedStyle(example);
  7715. let inTable, inLi;
  7716. if (forceState == 2) {
  7717. inTable = inLi = false;
  7718. } else {
  7719. inTable = compareNodeName(example.parentNode, ["table", "tbody"]) ||
  7720. compareNodeName(example, ["tr", "tbody"]) ||
  7721. exampleStyle.display == "table-row" ||
  7722. (example.nextElementSibling && compareNodeName(example.nextElementSibling, ["tr", "tbody"]));
  7723. inLi = compareNodeName(example, ["li"]) || (example.nextElementSibling && compareNodeName(example.nextElementSibling, ["li"]));
  7724. }
  7725. let pageBar = document.createElement(inTable ? "tr" : (inLi ? "li" : "div"));
  7726. let upSpan = document.createElement("span");
  7727. let downSpan = document.createElement("span");
  7728. let pageText = document.createElement("a");
  7729. let pageNum;
  7730. pageBar.className = isHideBar ? "pagetual_pageBar hide" : "pagetual_pageBar";
  7731. pageBar.id = "pagetual_pageBar" + curPage;
  7732. pageBar.setAttribute("translate", "no");
  7733. if (isPause) {
  7734. pageBar.classList.add("stop");
  7735. }
  7736. pageBar.style.cssText = pageBarStyle;
  7737. pageBar.title = i18n(isPause ? "enable" : "disable");
  7738. upSpan.innerHTML = createHTML(upSvg);
  7739. upSpan.children[0].style.cssText = upSvgCSS;
  7740. upSpan.title = i18n("toTop");
  7741. downSpan.innerHTML = createHTML(downSvg);
  7742. downSpan.children[0].style.cssText = downSvgCSS;
  7743. downSpan.title = i18n("toBottom");
  7744. upSpan.style.cssText = initStyle;
  7745. downSpan.style.cssText = initStyle;
  7746. pageText.href = url;
  7747. pageText.style.cssText = pageTextStyle;
  7748. pageText.title = i18n("current");
  7749. if (openInNewTab == 1) pageText.target = "_blank";
  7750. pageBar.appendChild(upSpan);
  7751. pageBar.appendChild(pageText);
  7752. let touched = false;
  7753. let touchBodyHandler = e => {
  7754. touched = false;
  7755. getBody(document).removeEventListener('touchstart', touchBodyHandler, { passive: false, capture: false });
  7756. };
  7757. pageText.addEventListener("touchstart", e => {
  7758. if (touched) return;
  7759. touched = true;
  7760. pageText.style.pointerEvents = 'none';
  7761. setTimeout(() => {
  7762. pageText.style.pointerEvents = 'all';
  7763. }, 250);
  7764. getBody(document).addEventListener("touchstart", touchBodyHandler, { passive: false, capture: false });
  7765. }, { passive: false, capture: false });
  7766. if (ruleParser.nextTitle) {
  7767. pageText.innerHTML = createHTML(ruleParser.nextTitle + " ");
  7768. pageText.title = ruleParser.nextTitle;
  7769. }
  7770. if (ruleParser.curSiteRule.pageNum || pageNumReg.test(url)) {
  7771. pageText.innerHTML = createHTML(pageText.innerHTML + i18n("page"));
  7772. pageNum = document.createElement("span");
  7773. let num = ruleParser.getPageNumFromUrl(url, curPage);
  7774. pageNum.innerHTML = createHTML(num + "<i style='font-size: 0;'>&nbsp;</i>");
  7775. pageNum.className = "pagetual_pageNum";
  7776. pageNum.title = i18n("inputPageNum");
  7777. pageNum.style.cssText = pageTextStyle;
  7778. pageNum.style.cursor = "pointer";
  7779. pageNum.style.color = "";
  7780. pageNum.style.marginLeft = "5px";
  7781. pageNum.addEventListener("click", e => {
  7782. let pageInput = prompt(i18n("inputPageNum"), num || "1");
  7783. if (pageInput) {
  7784. let localPageBar = document.querySelector("#pagetual_pageBar" + pageInput);
  7785. if (localPageBar) {
  7786. scrollToPageBar(localPageBar);
  7787. } else {
  7788. let pageLink = ruleParser.getLinkByPage(url, pageInput);
  7789. if (pageLink) {
  7790. _GM_openInTab(pageLink, {active:true});
  7791. }
  7792. }
  7793. }
  7794. e.preventDefault();
  7795. e.stopPropagation();
  7796. });
  7797. pageBar.appendChild(pageNum);
  7798. } else {
  7799. pageText.innerHTML = createHTML(pageText.innerHTML + i18n("page") + curPage + "<i style='font-size: 0;'>&nbsp;</i>");
  7800. }
  7801. let preBtn = document.createElement("span");
  7802. preBtn.innerHTML = createHTML("∧");
  7803. preBtn.title = i18n("prevPage");
  7804. preBtn.className = "prevScreen";
  7805. 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; ";
  7806. let nextBtn = document.createElement("span");
  7807. nextBtn.innerHTML = createHTML("∨");
  7808. nextBtn.title = i18n("nextPage");
  7809. nextBtn.className = "nextScreen";
  7810. 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; ";
  7811. let localPage = curPage;
  7812. preBtn.addEventListener("click", e => {
  7813. e.stopPropagation();
  7814. e.preventDefault();
  7815. let prePageBar = document.querySelector("#pagetual_pageBar" + (localPage - 1));
  7816. if (prePageBar) {
  7817. scrollToPageBar(prePageBar);
  7818. } else {
  7819. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  7820. targetY = scrollTop - (window.innerHeight || document.documentElement.clientHeight);
  7821. window.scrollTo({ top: targetY, behavior: 'smooth'});
  7822. }
  7823. });
  7824. nextBtn.addEventListener("click", e => {
  7825. e.stopPropagation();
  7826. e.preventDefault();
  7827. let nextPageBar = document.querySelector("#pagetual_pageBar" + (localPage + 1));
  7828. if (nextPageBar) {
  7829. scrollToPageBar(nextPageBar);
  7830. } else {
  7831. scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7832. targetY = scrollH || 9999999;
  7833. window.scrollTo({ top: targetY, behavior: 'smooth'});
  7834. }
  7835. });
  7836. if (!rulesData.hideBarArrow) {
  7837. pageText.insertBefore(preBtn, pageText.firstChild);
  7838. pageText.insertBefore(nextBtn, pageText.firstChild);
  7839. }
  7840. if (curForceIframe) {
  7841. let bgRing = document.createElement("span");
  7842. bgRing.className = "refreshRing";
  7843. bgRing.style.display = "none";
  7844. bgRing.innerHTML = createHTML(upSvg);
  7845. pageText.title = "Refresh";
  7846. pageText.appendChild(bgRing);
  7847. pageText.addEventListener("click", e => {
  7848. e.stopPropagation();
  7849. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  7850. e.preventDefault();
  7851. let nextEle = pageBar && pageBar.nextElementSibling;
  7852. if (nextEle && nextEle.name == 'pagetual-iframe') {
  7853. if (curForceIframe == nextEle) {
  7854. nextEle.setAttribute("loaded", "refresh");
  7855. }
  7856. nextEle.src = nextEle.src;
  7857. }
  7858. });
  7859. } else if (rulesData.pageBarMenu) {
  7860. pageText.addEventListener("click", e => {
  7861. e.stopPropagation();
  7862. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  7863. e.preventDefault();
  7864. picker.start();
  7865. });
  7866. }
  7867. pageBar.appendChild(downSpan);
  7868. if (forceState == 2) {
  7869. pageBar.style.width = "99%";
  7870. } else {
  7871. let parentStyle = _unsafeWindow.getComputedStyle(example.parentNode);
  7872. let parentWidth = example.parentNode.offsetWidth || parseInt(parentStyle.width);
  7873. pageBar.style.width = parentWidth - parseInt(parentStyle.paddingLeft) - parseInt(parentStyle.paddingRight) - 10 + "px";
  7874. pageBar.style.margin = '10px 5px';
  7875. if (parentStyle.display == "grid" || parentStyle.display == "inline-grid") {
  7876. pageBar.style.gridColumn = "1/-1";
  7877. }
  7878. if (inTable) {
  7879. example = compareNodeName(example, ["tr", "tbody"]) ? example : example.nextElementSibling || example;
  7880. if (compareNodeName(example, ["tbody"])) example = example.querySelector("tr");
  7881. let nextTr = example;
  7882. while (nextTr && nextTr.children.length == 0) nextTr = nextTr.nextElementSibling;
  7883. if (nextTr) example = nextTr;
  7884. let tdNum = 0;
  7885. if (exampleStyle.display == "table-row") {
  7886. [].forEach.call(example.children, el => {
  7887. tdNum += el.colSpan || 1;
  7888. });
  7889. } else {
  7890. [].forEach.call(example.children, el => {
  7891. if (compareNodeName(el, ["td", "th"])) {
  7892. tdNum += el.colSpan || 1;
  7893. }
  7894. });
  7895. }
  7896. pageBar.style.cssText = "";
  7897. pageBar.style.display = "table-row";
  7898. pageBar.style.backgroundColor = "unset";
  7899. pageBar.style.lineHeight = "20px";
  7900. pageBar.style.boxShadow = "";
  7901. let td = document.createElement("td");
  7902. td.colSpan = tdNum || 1;
  7903. let inTd = document.createElement("div");
  7904. inTd.style.cssText = pageBarStyle;
  7905. inTd.style.display = "";
  7906. inTd.className = pageBar.className;
  7907. pageBar.className = "";
  7908. inTd.appendChild(upSpan);
  7909. inTd.appendChild(pageText);
  7910. if (pageNum) inTd.appendChild(pageNum);
  7911. inTd.appendChild(downSpan);
  7912. td.appendChild(inTd);
  7913. pageBar.appendChild(td);
  7914. } else if (inLi) {
  7915. example = compareNodeName(example, ["li"]) ? example : example.nextElementSibling || example;
  7916. pageBar.style.opacity = 1;
  7917. pageBar.style.display = getComputedStyle(example).display;
  7918. pageBar.style.backgroundColor = "unset";
  7919. pageBar.style.lineHeight = "20px";
  7920. pageBar.style.boxShadow = "";
  7921. pageBar.style.border = "";
  7922. pageBar.style.width = "";
  7923. pageBar.style.maxWidth = "unset";
  7924. pageBar.style.flex = "auto";
  7925. let inTd = document.createElement("div");
  7926. inTd.style.cssText = pageBarStyle;
  7927. inTd.style.display = "";
  7928. inTd.style.margin = "0"
  7929. inTd.style.padding = "0 0";
  7930. inTd.style.textAlign = "center";
  7931. inTd.style.minWidth = "150px";
  7932. inTd.style.width = 'calc(100% - 20px)';
  7933. inTd.className = pageBar.className;
  7934. pageBar.className = "";
  7935. inTd.appendChild(upSpan);
  7936. inTd.appendChild(pageText);
  7937. if (pageNum) inTd.appendChild(pageNum);
  7938. inTd.appendChild(downSpan);
  7939. if (pageBar.style.display === 'table-row') {
  7940. let td = document.createElement("td");
  7941. td.colSpan = example.children.length;
  7942. td.style.width = '100%';
  7943. td.appendChild(inTd);
  7944. pageBar.appendChild(td);
  7945. } else {
  7946. inTd.style.width = '100%';
  7947. pageBar.appendChild(inTd);
  7948. }
  7949. }
  7950. }
  7951.  
  7952. upSpan.addEventListener("click", e => {
  7953. getBody(document).scrollTop = 0;
  7954. document.documentElement.scrollTop = 0;
  7955. e.preventDefault();
  7956. e.stopPropagation();
  7957. });
  7958. downSpan.addEventListener("click", e => {
  7959. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  7960. changeStop(true);
  7961. }
  7962. pageBar.title = i18n(isPause ? "enable" : "disable");
  7963. scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7964. getBody(document).scrollTop = scrollH || 9999999;
  7965. document.documentElement.scrollTop = scrollH || 9999999;
  7966. e.preventDefault();
  7967. e.stopPropagation();
  7968. });
  7969. pageBar.addEventListener("click", e => {
  7970. changeStop(!isPause);
  7971. pageBar.title = i18n(isPause ? "enable" : "disable");
  7972. });
  7973. ruleParser.insertElement(pageBar);
  7974. ruleParser.runPageBar(pageBar);
  7975.  
  7976. return pageBar;
  7977. }
  7978.  
  7979. async function waitForElement(sel, doc) {
  7980. if (!sel) return null;
  7981. return new Promise((resolve) => {
  7982. let checkInv = setInterval(() => {
  7983. let result = getElement(sel, doc, null, true);
  7984. if (result) {
  7985. clearInterval(checkInv);
  7986. resolve(result);
  7987. }
  7988. }, 100);
  7989. });
  7990. }
  7991.  
  7992. async function clickAction(sel, doc) {
  7993. let btn = await waitForElement(sel, doc);
  7994. emuClick(btn, doc);
  7995. }
  7996.  
  7997. async function enterAction(sel, doc) {
  7998. let btn = await waitForElement(sel, doc);
  7999. let eventParam = { key: "Enter", keyCode: 13, bubbles: true };
  8000. let event = new KeyboardEvent('keydown', eventParam);
  8001. btn.dispatchEvent(event);
  8002. event = new KeyboardEvent('keyup', eventParam);
  8003. btn.dispatchEvent(event);
  8004. event = new KeyboardEvent('keypress', eventParam);
  8005. btn.dispatchEvent(event);
  8006. }
  8007.  
  8008. async function inputAction(sel, v, doc) {
  8009. let input = await waitForElement(sel, doc);
  8010. let event = new Event('focus', { bubbles: true });
  8011. input.dispatchEvent(event);
  8012. let lastValue = input.value;
  8013. if (input.nodeName.toUpperCase() == "INPUT") {
  8014. var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
  8015. nativeInputValueSetter.call(input, v);
  8016. } else if (input.nodeName.toUpperCase() == "TEXTAREA") {
  8017. var nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
  8018. nativeTextareaValueSetter.call(input, v);
  8019. } else {
  8020. input.innerHTML = createHTML(v);
  8021. }
  8022. event = new Event('input', { bubbles: true });
  8023. let tracker = input._valueTracker;
  8024. if (tracker) {
  8025. tracker.setValue(lastValue);
  8026. }
  8027. input.dispatchEvent(event);
  8028. event = new Event('change', { bubbles: true });
  8029. input.dispatchEvent(event);
  8030. debug(input, `input ${sel}`);
  8031. }
  8032.  
  8033. function emuClick(btn, doc) {
  8034. if (!doc) doc = document;
  8035. let curScroll = getBody(doc).scrollTop || doc.documentElement.scrollTop;
  8036. let orgHref = btn.getAttribute('href');
  8037. if (orgHref && orgHref.replace(location.origin + location.pathname, "").indexOf("#") === 0) {
  8038. let hashAction = e => {
  8039. e.preventDefault();
  8040. getBody(doc).scrollTop = curScroll;
  8041. doc.documentElement.scrollTop = curScroll;
  8042. btn.removeEventListener('click', hashAction, false);
  8043. };
  8044. btn.addEventListener('click', hashAction, false);
  8045. }
  8046. if (!PointerEvent) return btn.click();
  8047. let eventParam = {
  8048. isTrusted: true,
  8049. altKey: false,
  8050. azimuthAngle: 0,
  8051. bubbles: true,
  8052. button: 0,
  8053. buttons: 0,
  8054. clientX: 1,
  8055. clientY: 1,
  8056. cancelBubble: false,
  8057. cancelable: true,
  8058. composed: true,
  8059. ctrlKey: false,
  8060. defaultPrevented: false,
  8061. detail: 1,
  8062. eventPhase: 2,
  8063. fromElement: null,
  8064. height: 1,
  8065. isPrimary: false,
  8066. metaKey: false,
  8067. pointerId: 1,
  8068. pointerType: "mouse",
  8069. pressure: 0,
  8070. relatedTarget: null,
  8071. returnValue: true,
  8072. shiftKey: false,
  8073. toElement: null,
  8074. twist: 0,
  8075. which: 1
  8076. };
  8077. let mouseEvent = new PointerEvent("mousedown", eventParam);
  8078. btn.dispatchEvent(mouseEvent);
  8079. mouseEvent = new PointerEvent("mouseup", eventParam);
  8080. btn.dispatchEvent(mouseEvent);
  8081. let dispatchTouchEvent = (ele, type) => {
  8082. let touchEvent;
  8083. try {
  8084. touchEvent = document.createEvent('TouchEvent')
  8085. touchEvent.initTouchEvent(type, true, true)
  8086. } catch (err) {
  8087. try {
  8088. touchEvent = document.createEvent('UIEvent')
  8089. touchEvent.initUIEvent(type, true, true)
  8090. } catch (err) {
  8091. touchEvent = document.createEvent('Event')
  8092. touchEvent.initEvent(type, true, true)
  8093. }
  8094. }
  8095. if (touchEvent) {
  8096. try {
  8097. touchEvent.targetTouches = [{
  8098. pageX: 1,
  8099. pageY: 1,
  8100. clientX: 1,
  8101. clientY: 1,
  8102. target: btn
  8103. }];
  8104. touchEvent.touches = [{
  8105. pageX: 1,
  8106. pageY: 1,
  8107. clientX: 1,
  8108. clientY: 1,
  8109. target: btn
  8110. }];
  8111. touchEvent.changedTouches = [{
  8112. pageX: 1,
  8113. pageY: 1,
  8114. clientX: 1,
  8115. clientY: 1,
  8116. target: btn
  8117. }];
  8118. } catch (err) {}
  8119. ele.dispatchEvent(touchEvent);
  8120. }
  8121. }
  8122. dispatchTouchEvent(btn, "touchstart");
  8123. dispatchTouchEvent(btn, "touchend");
  8124.  
  8125. btn.click();
  8126. }
  8127.  
  8128. function emuInput(input, v) {
  8129. let result = false;
  8130. if (!input) return true;
  8131. let event = new Event('focus', { bubbles: true });
  8132. input.dispatchEvent(event);
  8133. let lastValue = input.value;
  8134. if (input.type == 'file') {
  8135. let file = v;
  8136. let blob = new Blob([file], {
  8137. type: 'text/plain'
  8138. });
  8139. file = new File([blob], 'noname.txt', { type: blob.type });
  8140. let dataTransfer = new DataTransfer();
  8141. dataTransfer.items.add(file);
  8142. input.files = dataTransfer.files;
  8143. v = "c:/fakepath/fakefile";
  8144. } else if (/INPUT/i.test(input.nodeName)) {
  8145. var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
  8146. nativeInputValueSetter.call(input, v);
  8147. } else if (/SELECT/i.test(input.nodeName)) {
  8148. var nativeSelectValueSetter = Object.getOwnPropertyDescriptor(window.HTMLSelectElement.prototype, "value").set;
  8149. nativeSelectValueSetter.call(input, v);
  8150. } else if (input.nodeName.toUpperCase() == "TEXTAREA") {
  8151. var nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
  8152. nativeTextareaValueSetter.call(input, v);
  8153. } else {
  8154. input.innerHTML = createHTML(v);
  8155. }
  8156. event = new Event('input', { bubbles: true });
  8157. let tracker = input._valueTracker;
  8158. if (tracker) {
  8159. tracker.setValue(lastValue);
  8160. }
  8161. input.dispatchEvent(event);
  8162. event = new Event('change', { bubbles: true });
  8163. input.dispatchEvent(event);
  8164. return result;
  8165. }
  8166.  
  8167. var failFromIframe = 0;
  8168. var inCors = false;
  8169. var checkRemoveIntv;
  8170. function requestFromIframe(url, callback){
  8171. if (location.protocol === 'https:' && !/^https:/.test(url)) {
  8172. ruleParser.noValidContent(url);
  8173. }
  8174. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  8175. let iframe = document.createElement('iframe');
  8176. iframe.name = 'pagetual-iframe';
  8177. iframe.width = '100%';
  8178. iframe.height = '1000';
  8179. iframe.frameBorder = '0';
  8180. if (ruleParser.curSiteRule.sandbox != false) {
  8181. iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  8182. }
  8183. 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;';
  8184. let waitTime = 100, checkEval;
  8185. ruleParser.runWait((_checkEval, _waitTime) => {
  8186. if (_checkEval) {
  8187. checkEval = _checkEval;
  8188. }
  8189. if (_waitTime) {
  8190. waitTime = _waitTime;
  8191. }
  8192. });
  8193. if (checkRemoveIntv) clearInterval(checkRemoveIntv);
  8194. checkRemoveIntv = setInterval(() => {
  8195. if (!iframe || !getBody(document).contains(iframe)) {
  8196. clearInterval(checkRemoveIntv);
  8197. loadPageOver();
  8198. }
  8199. }, 500);
  8200. let loadedHandler = async e => {
  8201. if (e.data != 'pagetual-iframe:DOMLoaded' && e.type != 'load') return;
  8202. clearInterval(checkRemoveIntv);
  8203. window.removeEventListener('message', loadedHandler, false);
  8204. iframe.removeEventListener('load', loadedHandler, false);
  8205. let pageEleTryTimes = 0;
  8206. async function checkIframe() {
  8207. if (urlChanged || isPause) {
  8208. return callback(false, false);
  8209. }
  8210. try {
  8211. let doc = iframe.contentDocument || iframe.contentWindow.document;
  8212. if (checkEval && !await checkEval(doc)) {
  8213. setTimeout(() => {
  8214. checkIframe();
  8215. }, waitTime);
  8216. return;
  8217. } else {
  8218. let base = doc.querySelector("base");
  8219. ruleParser.basePath = base ? base.href : url;
  8220. let eles = ruleParser.getPageElement(doc, iframe.contentWindow, pageEleTryTimes < 25);
  8221. if (eles && eles.length > 0) {
  8222. await ruleParser.hookUrl(doc);
  8223. await callback(doc, eles);
  8224. } else if (pageEleTryTimes++ < 100) {
  8225. getBody(doc).scrollTop = 9999999;
  8226. doc.documentElement.scrollTop = 9999999;
  8227. setTimeout(() => {
  8228. checkIframe();
  8229. }, waitTime);
  8230. return;
  8231. } else {
  8232. if (failFromIframe++ > 2) {
  8233. failFromIframe = 0;
  8234. debug("Stop as failFromIframe");
  8235. changeStop(true);
  8236. callback(false, false);
  8237. } else {
  8238. ruleParser.noValidContent(url);
  8239. callback(false, false);
  8240. }
  8241. }
  8242. }
  8243. } catch(e) {
  8244. inCors = true;
  8245. if (forceState === 3) {
  8246. debug("Stop as cors");
  8247. isPause = true;
  8248. }
  8249. if (!ruleParser.curSiteRule.pageElement) {
  8250. ruleParser.curSiteRule.pageElement = allOfBody;
  8251. ruleParser.getInsert(true);
  8252. }
  8253. ruleParser.curSiteRule.action = 0;
  8254. ruleParser.nextLinkHref = url;
  8255. callback(false, false);
  8256. nextPage();
  8257. }
  8258. if (iframe && iframe.parentNode) iframe.parentNode.removeChild(iframe);
  8259. }
  8260. setTimeout(() => {
  8261. checkIframe();
  8262. }, waitTime);
  8263. };
  8264. let code = ruleParser.curSiteRule.iframeInit;
  8265. if (code) {
  8266. let checkReady = setInterval(() => {
  8267. let doc;
  8268. try {
  8269. doc = iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document);
  8270. } catch(e) {
  8271. clearInterval(checkReady);
  8272. return;
  8273. }
  8274. if (doc) {
  8275. clearInterval(checkReady);
  8276. try {
  8277. Function('win', 'iframe', '"use strict";' + code)(iframe.contentWindow, iframe);
  8278. } catch(e) {
  8279. debug(e);
  8280. }
  8281. }
  8282. }, 50);
  8283. }
  8284. window.addEventListener('message', loadedHandler, false);
  8285. iframe.addEventListener('load', loadedHandler, false);
  8286. iframe.src = url;
  8287. try {
  8288. getBody(document).appendChild(iframe);
  8289. } catch (e) {
  8290. return callback(false, false);
  8291. }
  8292. }
  8293.  
  8294. var emuIframe, lastActiveUrl, orgContent, meetCors = false;
  8295. function emuPage(callback) {
  8296. let orgPage = null, preContent = null, iframeDoc, checkTimes = 0, loadmoreBtn, pageEle, nextLink, loadmoreEnd = false, waitTimes = 80, changed = false;
  8297. function returnFalse(log) {
  8298. if (curPage > 1) {
  8299. if (rulesData.lastPageTips) showTips(i18n("lastPage"), "", 800);
  8300. } else {
  8301. sideController.remove();
  8302. }
  8303. debug(log);
  8304. isPause = true;
  8305. callback(false, false);
  8306. if (emuIframe && emuIframe.parentNode) {
  8307. emuIframe.parentNode.removeChild(emuIframe);
  8308. emuIframe = null;
  8309. }
  8310. }
  8311. function cloneStatus() {
  8312. if (!iframeDoc) return;
  8313. let inputs = document.querySelectorAll("input:not([type=button],[type=image],[type=reset],[type=submit])");
  8314. let selectOptions = document.querySelectorAll("select>option");
  8315. [...inputs].forEach(input => {
  8316. let sel = geneSelector(input, true, true);
  8317. let mirrorEle = iframeDoc.querySelector(sel);
  8318. if (!mirrorEle) return;
  8319. emuInput(mirrorEle, input.value);
  8320. });
  8321. [...selectOptions].forEach(option => {
  8322. let sel = geneSelector(option, true, true);
  8323. let mirrorEle = iframeDoc.querySelector(sel);
  8324. if (!mirrorEle) return;
  8325. let selected = option.selected;
  8326. mirrorEle.selected = !!selected;
  8327. mirrorEle.parentNode.dispatchEvent(new Event('change'));
  8328. });
  8329. }
  8330. async function checkPage() {
  8331. if (isPause) return loadPageOver();
  8332. try {
  8333. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  8334. } catch(e) {
  8335. returnFalse("Stop as cors");
  8336. return;
  8337. }
  8338.  
  8339. let waitTime = 200, checkEval;
  8340. ruleParser.runWait((_checkEval, _waitTime) => {
  8341. if (_checkEval) {
  8342. checkEval = _checkEval;
  8343. }
  8344. if (_waitTime) {
  8345. waitTime = _waitTime;
  8346. }
  8347. });
  8348.  
  8349. if (!orgPage) {
  8350. if (!loadmoreEnd) {
  8351. loadmoreBtn = getLoadMore(iframeDoc);
  8352. if (loadmoreBtn && isVisible(loadmoreBtn, emuIframe.contentWindow)) {
  8353. emuClick(loadmoreBtn, iframeDoc);
  8354. let intv = setInterval(() => {
  8355. loadmoreBtn = getLoadMore(iframeDoc);
  8356. if (!loadmoreBtn || !getBody(document).contains(loadmoreBtn) || !isVisible(loadmoreBtn, emuIframe.contentWindow)) {
  8357. clearInterval(intv);
  8358. loadmoreEnd = true;
  8359. setTimeout(() => {
  8360. checkPage();
  8361. }, 500);
  8362. } else if (isInViewPort(loadmoreBtn)) {
  8363. emuClick(loadmoreBtn, iframeDoc);
  8364. }
  8365. }, 200);
  8366. return;
  8367. } else {
  8368. loadmoreEnd = true;
  8369. }
  8370. }
  8371. if (checkEval && !await checkEval(iframeDoc)) {
  8372. waitTimes = 50;
  8373. setTimeout(() => {
  8374. checkPage();
  8375. }, waitTime);
  8376. return;
  8377. } else {
  8378. if (!nextLink || !nextLink.offsetParent) nextLink = await ruleParser.getNextLink(iframeDoc, true);
  8379. if (nextLink) pageEle = ruleParser.getPageElement(iframeDoc, emuIframe.contentWindow, true);
  8380. if (!pageEle || pageEle.length == 0 || !nextLink) {
  8381. getBody(iframeDoc).scrollTop = 9999999;
  8382. iframeDoc.documentElement.scrollTop = 9999999;
  8383. if (waitTimes-- > 0) {
  8384. setTimeout(() => {
  8385. checkPage();
  8386. }, waitTime);
  8387. return;
  8388. }
  8389. }
  8390. }
  8391. if (!pageEle || pageEle.length == 0) {
  8392. returnFalse("Stop as no page when emu");
  8393. return;
  8394. }
  8395. pageEle = [].filter.call(pageEle, ele => {return ele && !compareNodeName(ele, ["style", "script", "meta"])});
  8396. if (compareNodeName(pageEle[0], ["ul"]) || pageEle.length == 1) pageEle = pageEle[0];
  8397. else if (pageEle[0].parentNode == pageEle[1].parentNode) {
  8398. pageEle = pageEle[0].parentNode;
  8399. } else {
  8400. pageEle = pageEle[0];
  8401. }
  8402. if (ruleParser.curSiteRule.smart && orgContent != pageEle.innerHTML) {
  8403. orgContent = pageEle.innerHTML;
  8404. if (waitTimes-- > 0) {
  8405. setTimeout(() => {
  8406. checkPage();
  8407. }, 500);
  8408. return;
  8409. }
  8410. }
  8411. orgPage = pageEle;
  8412. if (nextLink) {
  8413. if (compareNodeName(orgPage, ["img"])) {
  8414. if (!ruleParser.curSiteRule.lazyImgSrc) ruleParser.curSiteRule.lazyImgSrc = "0";
  8415. if (orgPage.src) {
  8416. orgContent = orgPage.src;
  8417. } else {
  8418. setTimeout(() => {
  8419. checkPage();
  8420. }, 500);
  8421. return;
  8422. }
  8423. } else {
  8424. orgContent = orgPage.innerHTML;
  8425. }
  8426. preContent = orgContent;
  8427. if (!isVisible(nextLink, emuIframe.contentWindow)) {
  8428. returnFalse("Stop as next hide when emu");
  8429. } else {
  8430. emuClick(nextLink, iframeDoc);
  8431. setTimeout(() => {
  8432. checkPage();
  8433. }, 500);
  8434. }
  8435. } else {
  8436. returnFalse("Stop as no next when emu");
  8437. }
  8438. return;
  8439. }
  8440. if (!ruleParser.checkStopSign(nextLink, iframeDoc)) {
  8441. return returnFalse("Stop as stopSign");
  8442. }
  8443. if (checkTimes++ > 200) {
  8444. returnFalse("Stop as timeout when emu");
  8445. return;
  8446. }
  8447. if (checkEval && !await checkEval(iframeDoc)) {
  8448. checkTimes = 0;
  8449. setTimeout(() => {
  8450. checkPage();
  8451. }, waitTime);
  8452. return;
  8453. }
  8454. let eles = ruleParser.getPageElement(iframeDoc, emuIframe.contentWindow, true), checkItem;
  8455. if (eles && eles.length > 0) {
  8456. eles = [].filter.call(eles, ele => {return ele && !compareNodeName(ele, ["style", "script", "meta"])});
  8457. if (compareNodeName(eles[0], ["ul"]) || eles.length == 1) checkItem = eles[0];
  8458. else if (eles[0].parentNode == eles[1].parentNode) {
  8459. checkItem = eles[0].parentNode;
  8460. } else {
  8461. checkItem = eles[0];
  8462. }
  8463. }
  8464. if (!checkItem) {
  8465. setTimeout(() => {
  8466. checkPage();
  8467. }, waitTime);
  8468. } else {
  8469. let checkInner;
  8470. if (compareNodeName(checkItem, ["img"])) {
  8471. if (checkItem.src) {
  8472. checkInner = checkItem.src;
  8473. } else {
  8474. setTimeout(() => {
  8475. checkPage();
  8476. }, waitTime);
  8477. return;
  8478. }
  8479. } else {
  8480. checkInner = checkItem.innerHTML;
  8481. }
  8482. if (orgPage != checkItem || checkInner != preContent) {
  8483. changed = true;
  8484. orgPage = checkItem;
  8485. preContent = checkInner;
  8486. setTimeout(() => {
  8487. checkPage();
  8488. }, 500);
  8489. } else if (changed) {
  8490. checkTimes = 0;
  8491. if (orgContent == preContent && (ruleParser.curSiteRule.smart || ruleParser.curSiteRule.stopSame)) {
  8492. returnFalse("Stop as same content");
  8493. } else {
  8494. orgContent = preContent;
  8495. await ruleParser.hookUrl(iframeDoc);
  8496. callback(iframeDoc, eles);
  8497. }
  8498. } else {
  8499. if (checkTimes % 10 === 5) {
  8500. if (!nextLink || !nextLink.offsetParent) {
  8501. nextLink = await ruleParser.getNextLink(iframeDoc, true);
  8502. }
  8503. if (nextLink) {
  8504. emuClick(nextLink, iframeDoc);
  8505. }
  8506. }
  8507. setTimeout(() => {
  8508. checkPage();
  8509. }, waitTime);
  8510. }
  8511. }
  8512. }
  8513. if (!emuIframe) {
  8514. let loaded = false;
  8515. emuIframe = document.createElement('iframe');
  8516. emuIframe.name = 'pagetual-iframe';
  8517. let notSetSandbox = typeof ruleParser.curSiteRule.sandbox == 'undefined';
  8518. if (notSetSandbox || ruleParser.curSiteRule.sandbox == true) {
  8519. emuIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  8520. } else if (ruleParser.curSiteRule.sandbox) {
  8521. emuIframe.sandbox = ruleParser.curSiteRule.sandbox;
  8522. }
  8523. emuIframe.width = '100%';
  8524. emuIframe.height = '100%';
  8525. emuIframe.frameBorder = '0';
  8526. 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;';
  8527. emuIframe.addEventListener("load", e => {
  8528. try {
  8529. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  8530. } catch(e) {
  8531. if (e.message && e.message.indexOf("cross-origin") != -1 && notSetSandbox && emuIframe.hasAttribute("sandbox")) {
  8532. emuIframe.removeAttribute("sandbox");
  8533. meetCors = true;
  8534. callback(false, false);
  8535. if (ruleParser.curSiteRule.smart) {
  8536. ruleParser.findNoNext();
  8537. }
  8538. } else {
  8539. returnFalse("Stop as cors");
  8540. }
  8541. return;
  8542. }
  8543. setTimeout(async () => {
  8544. if (meetCors && ruleParser.curSiteRule.smart) {
  8545. ruleParser.smartRules = ruleParser.smartRules.filter(item => {return item && item.url !== ruleParser.curSiteRule.url;});
  8546. storage.setItem("smartRules", ruleParser.smartRules);
  8547. }
  8548. meetCors = false;
  8549. let code = ruleParser.curSiteRule.init;
  8550. if (code) {
  8551. try {
  8552. 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)});
  8553. } catch(e) {
  8554. debug(e);
  8555. }
  8556. } else {
  8557. let refreshByClickSel = ruleParser.curSiteRule.refreshByClick;
  8558. if (iframeDoc && refreshByClickSel) {
  8559. let clickBtn = await waitForElement(refreshByClickSel, iframeDoc);
  8560. await sleep(500);
  8561. cloneStatus();
  8562. emuClick(clickBtn, iframeDoc);
  8563. await sleep(500);
  8564. }
  8565. }
  8566. if (loaded) return;
  8567. loaded = true;
  8568. checkPage();
  8569. }, 500);
  8570. });
  8571. let code = ruleParser.curSiteRule.iframeInit;
  8572. if (code) {
  8573. let checkReady = setInterval(() => {
  8574. try {
  8575. iframeDoc = emuIframe.contentDocument || (emuIframe.contentWindow && emuIframe.contentWindow.document);
  8576. } catch(e) {
  8577. clearInterval(checkReady);
  8578. return;
  8579. }
  8580. if (iframeDoc) {
  8581. clearInterval(checkReady);
  8582. try {
  8583. Function('win', 'iframe', '"use strict";' + code)(emuIframe.contentWindow, emuIframe);
  8584. } catch(e) {
  8585. debug(e);
  8586. }
  8587. }
  8588. }, 50);
  8589. }
  8590. if (!lastActiveUrl) lastActiveUrl = location.href;
  8591. emuIframe.src = lastActiveUrl;
  8592. getBody(document).appendChild(emuIframe);
  8593. } else {
  8594. if (emuIframe.src != lastActiveUrl || meetCors) {
  8595. emuIframe.src = lastActiveUrl;
  8596. return;
  8597. }
  8598. checkPage();
  8599. }
  8600. }
  8601.  
  8602. var scrollToResizeInited = false;
  8603. var resizePool = [];
  8604. var scrollingToResize = false;
  8605.  
  8606. function isTouchViewPort(element) {
  8607. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  8608. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  8609. const {
  8610. top,
  8611. right,
  8612. bottom,
  8613. left,
  8614. } = element.getBoundingClientRect();
  8615.  
  8616. return (
  8617. top < viewHeight &&
  8618. left < viewWidth &&
  8619. right > 0 &&
  8620. bottom > 0
  8621. );
  8622. }
  8623.  
  8624. function resizeIframe(iframe, frameDoc, pageEle) {
  8625. if (targetY >= 0) {
  8626. window.scrollTo({ top: targetY, behavior: 'instant'});
  8627. targetY = -1;
  8628. }
  8629. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  8630. if (ruleParser.curSiteRule.smart || forceState === 2) {
  8631. let height = (getBody(frameDoc).scrollHeight || getBody(frameDoc).offsetHeight || 500);
  8632. if (!iframe.style.height || parseInt(iframe.style.height) === 0 || height - parseInt(iframe.style.height) > window.innerHeight) {
  8633. iframe.style.height = height + "px";
  8634. iframe.style.minHeight = iframe.style.height;
  8635. }
  8636. iframe.style.width = "100%";
  8637. frameDoc.documentElement.scrollTop = 0;
  8638. frameDoc.documentElement.scrollLeft = 0;
  8639. } else {
  8640. if (pageEle) {
  8641. if (document.body.scrollWidth) frameDoc.documentElement.style.width = document.body.scrollWidth + "px";
  8642. let fitWidth = ruleParser.curSiteRule.fitWidth !== false;
  8643. let targetElement = pageEle[0];
  8644. if (!targetElement) return;
  8645. if (pageEle.length > 1) {
  8646. targetElement = targetElement.parentNode;
  8647. }
  8648. let scrollHeight = targetElement.scrollHeight || targetElement.offsetHeight || 500;
  8649. iframe.style.height = scrollHeight + "px";
  8650. let scrollTop = 0, scrollLeft = 0;
  8651. getBody(frameDoc).scrollTop = 0;
  8652. getBody(frameDoc).scrollLeft = 0;
  8653. while (targetElement && targetElement.offsetParent) {
  8654. targetElement.offsetParent.scrollTop = targetElement.offsetTop;
  8655. if (targetElement.offsetParent.scrollTop == 0) {
  8656. scrollTop += targetElement.offsetTop;
  8657. }
  8658. if (fitWidth) {
  8659. targetElement.offsetParent.scrollLeft = targetElement.offsetLeft;
  8660. if (targetElement.offsetParent.scrollLeft == 0) {
  8661. scrollLeft += targetElement.offsetLeft;
  8662. }
  8663. }
  8664. targetElement = targetElement.offsetParent;
  8665. }
  8666. frameDoc.documentElement.scrollTop = scrollTop;
  8667. frameDoc.documentElement.scrollLeft = scrollLeft;
  8668. if (frameDoc.documentElement.scrollTop == 0 && frameDoc.documentElement.scrollLeft == 0) {
  8669. getBody(frameDoc).scrollTop += scrollTop;
  8670. getBody(frameDoc).scrollLeft += scrollLeft;
  8671. }
  8672. if (!fitWidth && iframe.style.marginLeft == '0px') {
  8673. iframe.style.width = "100vw";
  8674. iframe.style.maxWidth = "100vw";
  8675. iframe.style.minWidth = "100vw";
  8676. var cWidth = document.body.clientWidth || document.documentElement.clientWidth;
  8677. var iWidth = window.innerWidth;
  8678. iframe.style.marginLeft = -iframe.getBoundingClientRect().left - (iWidth - cWidth) / 2 + "px";
  8679. }
  8680. }
  8681. }
  8682. let newScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  8683. if (newScroll != curScroll) {
  8684. getBody(document).scrollTop = curScroll;
  8685. document.documentElement.scrollTop = curScroll;
  8686. }
  8687. }
  8688.  
  8689. function scrollToResize(e) {
  8690. if (scrollingToResize) return;
  8691. else {
  8692. scrollingToResize = true;
  8693. let resizeHandler = () => {
  8694. let touched = 0;
  8695. for (let i = 0; i < resizePool.length; i++) {
  8696. let resizeArr = resizePool[i];
  8697. let iframe = resizeArr[1]();
  8698. if (isTouchViewPort(iframe)) {
  8699. touched++;
  8700. let pageEle = resizeArr[0]();
  8701. let frameDoc = resizeArr[2]();
  8702. resizeIframe(iframe, frameDoc, pageEle);
  8703. } else if (touched) {
  8704. if (touched == 1) {
  8705. let pageEle = resizeArr[0]();
  8706. let frameDoc = resizeArr[2]();
  8707. resizeIframe(iframe, frameDoc, pageEle);
  8708. }
  8709. break;
  8710. } else if (!iframe.parentNode) {
  8711. resizePool.splice(i, 1);
  8712. break;
  8713. }
  8714. }
  8715. };
  8716. setTimeout(() => {
  8717. scrollingToResize = false;
  8718. }, 300);
  8719. resizeHandler();
  8720. }
  8721. }
  8722.  
  8723. var curForceIframe;
  8724. function forceIframe(url, callback) {
  8725. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  8726. let curIframe = document.createElement('iframe'), iframeDoc, pageElement = null, inAction = true;
  8727. let loadedHandler = () => {
  8728. let getPageEle = () => {
  8729. if (ruleParser.curSiteRule.smart) {
  8730. return null;
  8731. } else {
  8732. if (!pageElement || pageElement.length === 0 || !pageElement[0].offsetParent) {
  8733. pageElement = ruleParser.getPageElement(iframeDoc, curIframe.contentWindow);
  8734. }
  8735. return pageElement;
  8736. }
  8737. };
  8738. resizeIframe(curIframe, iframeDoc, getPageEle());
  8739. let loaded = curIframe.getAttribute("loaded");
  8740. if (loaded == "true") {
  8741. return;
  8742. }
  8743. curIframe.setAttribute("loaded", "true");
  8744. let getIframe = () => {
  8745. return curIframe;
  8746. };
  8747. let getFrameDoc = () => {
  8748. return iframeDoc;
  8749. };
  8750. ruleParser.insertPage(iframeDoc, [], url, ele => {
  8751. callback(curIframe, loaded == "refresh");
  8752. inAction = false;
  8753. }, true);
  8754. if (!loaded) {
  8755. resizePool.push([getPageEle, getIframe, getFrameDoc]);
  8756. }
  8757. };
  8758. let checkIframeTimer = setInterval(() => {
  8759. if (!curIframe.parentNode) {
  8760. clearInterval(checkIframeTimer);
  8761. return curIframe.getAttribute("loaded") == "true" || callback(false);
  8762. }
  8763. }, 500);
  8764. let code = ruleParser.curSiteRule.iframeInit;
  8765. if (code) {
  8766. let checkReady = setInterval(() => {
  8767. try {
  8768. iframeDoc = curIframe.contentDocument || (curIframe.contentWindow && curIframe.contentWindow.document);
  8769. } catch(e) {
  8770. clearInterval(checkReady);
  8771. return;
  8772. }
  8773. if (iframeDoc) {
  8774. clearInterval(checkReady);
  8775. try {
  8776. Function('win', 'iframe', '"use strict";' + code)(curIframe.contentWindow, curIframe);
  8777. } catch(e) {
  8778. debug(e);
  8779. }
  8780. }
  8781. }, 50);
  8782. }
  8783. let waitTime = 300, checkEval;
  8784. ruleParser.runWait((_checkEval, _waitTime) => {
  8785. if (_checkEval) {
  8786. checkEval = _checkEval;
  8787. }
  8788. if (_waitTime) {
  8789. waitTime = _waitTime;
  8790. }
  8791. });
  8792. async function checkIframe() {
  8793. if (checkEval && !await checkEval(iframeDoc)) {
  8794. setTimeout(() => {
  8795. checkIframe();
  8796. }, waitTime);
  8797. return;
  8798. }
  8799. loadedHandler();
  8800. }
  8801. curIframe.name = 'pagetual-iframe';
  8802. curIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  8803. curIframe.frameBorder = '0';
  8804. curIframe.scrolling = "no";
  8805. 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;';
  8806. curIframe.addEventListener("load", async e => {
  8807. clearInterval(checkIframeTimer);
  8808. if (isPause) return callback(false);
  8809. try {
  8810. iframeDoc = curIframe.contentDocument || curIframe.contentWindow.document;
  8811. } catch(e) {
  8812. debug("Stop as cors");
  8813. isPause = true;
  8814. callback(false);
  8815. return;
  8816. }
  8817. let css = ruleParser.curSiteRule.css || rulesData.customCss;
  8818. if (css) {
  8819. let cssArr = css.split("inIframe:");
  8820. if (cssArr && cssArr.length > 1) {
  8821. let styleEle = iframeDoc.createElement("style");
  8822. styleEle.innerHTML = cssArr[1];
  8823. iframeDoc.head.appendChild(styleEle);
  8824. }
  8825. }
  8826. checkIframe();
  8827. iframeDoc.addEventListener('wheel', e => {
  8828. document.dispatchEvent(new Event('wheel'));
  8829. }, true);
  8830. });
  8831. let checkTimes = 0, findPageEle = false;
  8832. let forceRefresh = e => {
  8833. if (inAction || !iframeDoc) return;
  8834. inAction = true;
  8835. let foundNext = () => {
  8836. document.removeEventListener("scroll", forceRefresh);
  8837. }
  8838. setTimeout(async () => {
  8839. inAction = false;
  8840. if (!ruleParser.nextLinkHref && !isPause) {
  8841. checkTimes++;
  8842. await ruleParser.getNextLink(iframeDoc, true);
  8843. if (ruleParser.nextLinkHref) {
  8844. foundNext();
  8845. if (isLoading) isLoading = false;
  8846. } else if (checkTimes >= 10) {
  8847. foundNext();
  8848. } else if (checkTimes >= 3 && !findPageEle) {
  8849. if (!pageElement) pageElement = ruleParser.getPageElement(iframeDoc, curIframe.contentWindow);
  8850. if (!pageElement) {
  8851. inAction = true;
  8852. curIframe.contentWindow.location.reload();
  8853. } else {
  8854. findPageEle = true;
  8855. }
  8856. }
  8857. } else {
  8858. foundNext();
  8859. }
  8860. }, 100);
  8861. };
  8862. document.addEventListener("scroll", forceRefresh);
  8863. curIframe.src = url;
  8864. curForceIframe = curIframe;
  8865. let insert = ruleParser.getInsert();
  8866. let body = getBody(document);
  8867. let curScroll = body.scrollTop || document.documentElement.scrollTop;
  8868. if (forceState == 2) {
  8869. document.documentElement.appendChild(loadingDiv);
  8870. body.appendChild(curIframe);
  8871. let bodyStyle = getComputedStyle(body);
  8872. if (bodyStyle.display == "flex" || bodyStyle.display == "inline-flex") {
  8873. body.style.flexDirection = "column";
  8874. }
  8875. } else {
  8876. ruleParser.insertElement(curIframe);
  8877. }
  8878. body.scrollTop = curScroll;
  8879. document.documentElement.scrollTop = curScroll;
  8880.  
  8881. if (!scrollToResizeInited) {
  8882. scrollToResizeInited = true;
  8883. document.addEventListener("scroll", scrollToResize);
  8884. }
  8885. return curIframe;
  8886. }
  8887.  
  8888. function loadPageOver() {
  8889. isLoading = false;
  8890. stopScroll = true;
  8891. setTimeout(() => {stopScroll = false;}, 300);
  8892. if (loadingDiv.parentNode) {
  8893. loadingDiv.parentNode.removeChild(loadingDiv);
  8894. }
  8895. if (rate !== 1 && !clickMode) {
  8896. setTimeout(() => {
  8897. if (distToBottom() < bottomGap) {
  8898. nextPage();
  8899. }
  8900. }, 1);
  8901. }
  8902. }
  8903.  
  8904. function checkAutoLoadNum() {
  8905. if (autoLoadNum >= 0) {
  8906. if (autoLoadNum !== 0 && --autoLoadNum === 0) {
  8907. autoLoadNum = -1;
  8908. } else {
  8909. setTimeout(() => nextPage(), 1);
  8910. }
  8911. }
  8912. }
  8913.  
  8914. async function nextPage() {
  8915. if (isPause || isLoading || forceState === 1) return;
  8916. if (ruleParser.curSiteRule.delay) {
  8917. try {
  8918. let checkDelay = ((typeof ruleParser.curSiteRule.delay === 'function') ? ruleParser.curSiteRule.delay : Function('"use strict";' + ruleParser.curSiteRule.delay))();
  8919. if (!checkDelay) return;
  8920. } catch(e) {
  8921. debug(e);
  8922. }
  8923. }
  8924. let nextLink = ruleParser.nextLinkHref;
  8925. if (!nextLink) {
  8926. isLoading = true;
  8927. if (curPage === 1) {
  8928. await ruleParser.getNextLink(document, true);
  8929. nextLink = ruleParser.nextLinkHref;
  8930. }
  8931. if (!nextLink) {
  8932. if (curPage === 1) {
  8933. if (ruleParser.curSiteRule.pinUrl) {
  8934. setTimeout(() => {isLoading = false;}, 500);
  8935. } else if (tryTimes++ < 5) {
  8936. setTimeout(() => {isLoading = false;}, 1000);
  8937. } else {
  8938. ruleParser.findNoNext();
  8939. }
  8940. } else if (rulesData.lastPageTips && !showedLastPageTips) {
  8941. showTips(i18n("lastPage"), "", 800);
  8942. showedLastPageTips = true;
  8943. }
  8944. return;
  8945. }
  8946. isLoading = false;
  8947. }
  8948. showedLastPageTips = false;
  8949. let pvGallery = document.querySelector("span.pv-gallery-container");
  8950. if (pvGallery && pvGallery.style.display !== "none") return;
  8951. let insert = ruleParser.getInsert();
  8952. if (insert) {
  8953. if (curPage === 1) initView();
  8954. /*if (curPage == 1) {
  8955. window.postMessage({
  8956. command: 'pagetual.insert'
  8957. }, '*');
  8958. }*/
  8959. let isJs = ruleParser.curSiteRule.action == 3 || ruleParser.hrefIsJs(nextLink);
  8960. if (!isJs) {
  8961. emuIframe = null;
  8962. lastActiveUrl = nextLink;
  8963. if (location.protocol === "https:" && /^http:/.test(nextLink)) {
  8964. nextLink = nextLink.replace(/^http/, "https");
  8965. }
  8966. }
  8967. isLoading = true;
  8968. if (curPage !== 1 || !isJs || !ruleParser.curSiteRule.smart) {
  8969. ruleParser.beginLoading(loadingDiv);
  8970. }
  8971. let sleep = ruleParser.curSiteRule.sleep || 0;
  8972. setTimeout(() => {
  8973. if (ruleParser.curSiteRule.pageElementByJs) {
  8974. var over = eles => {
  8975. if (urlChanged || isPause) {
  8976. loadPageOver();
  8977. return;
  8978. }
  8979. if (eles) {
  8980. ruleParser.insertPage(document, eles, nextLink, () => {
  8981. createPageBar(nextLink);
  8982. checkAutoLoadNum();
  8983. }, true);
  8984. } else {
  8985. debug("Stop as no page when get by js");
  8986. isPause = true;
  8987. loadPageOver();
  8988. }
  8989. };
  8990. try {
  8991. ((typeof ruleParser.curSiteRule.pageElementByJs === 'function') ? ruleParser.curSiteRule.pageElementByJs : Function("over", "pageNum",'"use strict";' + ruleParser.curSiteRule.pageElementByJs))(over, curPage);
  8992. } catch(e) {
  8993. debug(e);
  8994. }
  8995. } else if ((forceState === 2 || ruleParser.curSiteRule.action == 2) && !isJs) {
  8996. forceIframe(nextLink, (iframe, refresh) => {
  8997. if (urlChanged || isPause) {
  8998. loadPageOver();
  8999. return;
  9000. }
  9001. if (!refresh) {
  9002. let pageBar = createPageBar(nextLink);
  9003. if (pageBar && iframe && iframe.parentNode) iframe.parentNode.insertBefore(pageBar, iframe);
  9004. }
  9005. loadPageOver();
  9006. checkAutoLoadNum();
  9007. });
  9008. } else if ((forceState === 3 || ruleParser.curSiteRule.action == 1) && !isJs) {
  9009. requestFromIframe(nextLink, async (doc, eles) => {
  9010. if (urlChanged || isPause) {
  9011. loadPageOver();
  9012. return;
  9013. }
  9014. if (eles) {
  9015. await ruleParser.insertPage(doc, eles, nextLink, () => {
  9016. createPageBar(nextLink);
  9017. checkAutoLoadNum();
  9018. }, true);
  9019. } else loadPageOver();
  9020. });
  9021. } else {
  9022. if (!isJs) {
  9023. requestDoc(nextLink, (eles) => {
  9024. if (urlChanged || isPause) {
  9025. loadPageOver();
  9026. return;
  9027. }
  9028. if (eles) {
  9029. createPageBar(nextLink);
  9030. checkAutoLoadNum();
  9031. } else loadPageOver();
  9032. });
  9033. } else {
  9034. emuPage((doc, eles) => {
  9035. if (urlChanged || isPause) {
  9036. loadPageOver();
  9037. return;
  9038. }
  9039. if (eles) {
  9040. ruleParser.insertPage(doc, eles, "", () => {
  9041. createPageBar(nextLink);
  9042. checkAutoLoadNum();
  9043. }, true);
  9044. } else loadPageOver();
  9045. });
  9046. }
  9047. }
  9048. }, sleep);
  9049. }
  9050. }
  9051.  
  9052. function init() {
  9053. if (document.readyState === 'loading' || document.readyState === 'uninitialized') {
  9054. let domReady = e => {
  9055. initRules(() => {
  9056. initPage();
  9057. });
  9058. document.removeEventListener("DOMContentLoaded", domReady, false);
  9059. };
  9060. document.addEventListener("DOMContentLoaded", domReady, false);
  9061. } else {
  9062. initRules(() => {
  9063. initPage();
  9064. });
  9065. }
  9066. }
  9067.  
  9068. function visibilitychangeHandler() {
  9069. document.removeEventListener('visibilitychange', visibilitychangeHandler);
  9070. init();
  9071. }
  9072.  
  9073. setTimeout(() => {
  9074. if (document.hidden) {
  9075. document.addEventListener('visibilitychange', visibilitychangeHandler);
  9076. } else {
  9077. init();
  9078. }
  9079. }, 300);
  9080. })();