东方永页机

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

当前为 2023-10-03 提交的版本,查看 最新版本

  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.36.60
  14. // @description Perpetual pages - powerful auto-pager script. Auto loading next paginated web pages and inserting into current page. 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. // ==/UserScript==
  56.  
  57. (function() {
  58. 'use strict';
  59.  
  60. const pauseVideo = () => {
  61. setTimeout(() => {
  62. [].forEach.call(document.querySelectorAll("video"), video => {
  63. video.removeAttribute && video.removeAttribute("autoplay");
  64. video.pause && video.pause();
  65. });
  66. }, 1000);
  67. };
  68. if (window.name === 'pagetual-iframe' || (window.frameElement && window.frameElement.name === 'pagetual-iframe')) {
  69. var domloaded = function() {
  70. window.parent.postMessage('pagetual-iframe:DOMLoaded', '*');
  71. pauseVideo();
  72. };
  73. if (window.opera) {
  74. document.addEventListener('DOMContentLoaded', domloaded, false);
  75. } else {
  76. domloaded();
  77. }
  78. if (getComputedStyle(document.documentElement).display == 'none') document.documentElement.style.display = 'block';
  79. if (document.body && getComputedStyle(document.body).display == 'none') document.body.style.display = 'block';
  80. return;
  81. }
  82.  
  83. if (window.top != window.self) {
  84. try {
  85. if (window.self.innerWidth < 300 || window.self.innerHeight < 300) {
  86. return;
  87. }
  88. if (document.readystate == 'complete') {
  89. pauseVideo();
  90. } else {
  91. window.addEventListener('load', e => {
  92. pauseVideo();
  93. }, false);
  94. }
  95. } catch(e) {
  96. return;
  97. }
  98. }
  99.  
  100. const noRuleTest = false;
  101. const lang = navigator.appName == "Netscape" ? navigator.language : navigator.userLanguage;
  102. const langData = [
  103. {
  104. name: "English",
  105. match: ["en"],
  106. lang: {
  107. enableDebug: "Enable debug output",
  108. disable: "Disable",
  109. disableSite: "Toggle disabled state",
  110. disableSiteTips: "Disabled on this site",
  111. enableSiteTips: "Enabled on this site",
  112. enable: "Enable",
  113. toTop: "To Top",
  114. toBottom: "To Bottom",
  115. current: "Current Page",
  116. forceIframe: "Force to join next page",
  117. cancelForceIframe: "Cancel Force join",
  118. configure: "Configure",
  119. firstUpdate: "Click here to initialize the rules",
  120. update: "Update online rules",
  121. click2update: "Click to update rules from url now",
  122. loadNow: "Load next page manually",
  123. loadConfirm: "How much pages do you want to load? (0 means infinite)",
  124. noNext: "No next link found, please create a new rule",
  125. passSec: "Updated #t# seconds ago",
  126. passMin: "Updated #t# minutes ago",
  127. passHour: "Updated #t# hours ago",
  128. passDay: "Updated #t# days ago",
  129. cantDel: "Can't delete buildin rules",
  130. confirmDel: "Are you sure you want to delete this rule?",
  131. updateSucc: "Update succeeded",
  132. beginUpdate: "Begin update, wait a minute please",
  133. customUrls: "Import Pagetual or AutoPagerize rule url, One url per line",
  134. customRules: "Input custom rules with [Pagetual] format. <a href='#t#'>Contribute rules</a>",
  135. save: "Save",
  136. loadingText: "Shojo Now Loading...",
  137. opacity: "Opacity",
  138. opacityPlaceholder: "0: hide spacer",
  139. hideBar: "Hide the paging spacer",
  140. hideBarButNoStop: "Hide but not stop",
  141. dbClick2Stop: "Double-click on the blank space to pause",
  142. sortTitle: "Sorting takes effect after the next rule update",
  143. autoRun: "Auto run (black list mode)",
  144. autoLoadNum: "Amount for preload pages",
  145. turnRate: "Turn the next page when it's less than 【X】 times page height from the footer",
  146. inputPageNum: "Enter page number to jump",
  147. enableHistory: "Write history after page turning",
  148. enableHistoryAfterInsert: "Write history immediately after splicing, otherwise write after browsing",
  149. contentVisibility: "Automatically switch contentVisibility to improve rendering performance",
  150. initRun: "Turn pages immediately after opening",
  151. preload: "Preload next page for speeding up",
  152. click2ImportRule: "Click to import base rules link, then wait until the update is complete: ",
  153. forceAllBody: "Join full body of page?",
  154. openInNewTab: "Open urls of additions in new tab",
  155. importSucc: "Import completed",
  156. import: "Import",
  157. editCurrent: "Edit rule for current",
  158. editBlacklist: "Edit the blacklist urls, line by line, Support ? * for wildcard",
  159. upBtnImg: "Icon of back to top",
  160. downBtnImg: "Icon of go to footer",
  161. sideControllerIcon: "Icon of sidebar",
  162. loadingTextTitle: "Loading text",
  163. dbClick2StopCtrl: "Ctrl key",
  164. dbClick2StopAlt: "Alt key",
  165. dbClick2StopShift: "Shift key",
  166. dbClick2StopMeta: "Meta key",
  167. dbClick2StopKey: "Shortcut key",
  168. pageElementCss: "Custom style for main page elements",
  169. customCss: "Custom complete css",
  170. firstAlert: "You have not imported the base rule, please select the appropriate rule to import",
  171. picker: "Pagetual page element picker",
  172. closePicker: "Close Pagetual picker",
  173. pickerPlaceholder: "Element selector, Leave empty if you have no idea",
  174. pickerCheck: "Check selector and copy",
  175. switchSelector: "Click to switch element",
  176. gotoEdit: "Go to edit rule with current selector",
  177. manualMode: "Disable splicing, manually turn pages with the right arrow keys (or dispatch event 'pagetual.next')",
  178. clickMode: "Disable splicing, automatically click the next page when scrolling to the end of the page",
  179. pageBarMenu: "Click the middle of the page bar to open the menu",
  180. nextSwitch: "Switch next link",
  181. arrowToScroll: "Press left arrow key to scroll prev and right arrow key to scroll next",
  182. sideController: "Display the paging control bar in the sidebar",
  183. hideLoadingIcon: "Hide loading animation",
  184. hideBarArrow: "Hide arrow for page bar",
  185. duplicate: "Duplicate Pagetual have been installed, check your script manager!",
  186. forceStateIframe: "Embed full page as iframe",
  187. forceStateDynamic: "Load dynamic content via iframe",
  188. forceStateDisable: "Disable page turning on this site",
  189. autoScrollRate: "Scroll speed (1~1000)",
  190. disableAutoScroll: "Stop Auto Scroll",
  191. enableAutoScroll: "Enable Auto Scroll",
  192. toggleAutoScroll: "Toggle Auto Scroll",
  193. page: "Page ",
  194. prevPage: "Prev page",
  195. nextPage: "Next page",
  196. errorRulesMustBeArray: "Rules must be a Array!",
  197. errorJson: "JSON error, check again!",
  198. editSuccess: "Edit successfully",
  199. errorWrongUrl: "Wrong url, check again!",
  200. errorAlreadyExists: "Already exists!",
  201. settingsSaved: "The settings are saved, refresh to view",
  202. iframe: "Iframe",
  203. dynamic: "Dynamic",
  204. reloadPage: "Edit completed, reload page now?",
  205. copied: "Copied",
  206. noValidContent: "No valid content detected, Captcha action may be required, click to view",
  207. outOfDate: "The script is outdated, update to the latest version in time!",
  208. hideBarTips: "Hide the pagination bar, toggle immersive experience",
  209. setConfigPage: "Set current page as the default configuration page",
  210. wedata2github: "Change the wedate address to the mirror address in the github repository",
  211. addOtherProp: "Add rule property",
  212. addNextSelector: "Add selector content as nextLink",
  213. addPageSelector: "Add selector content as pageElement",
  214. propName: "Enter rule property name",
  215. propValue: "Enter rule property value",
  216. customFirst: "Ignore cache for local custom rules",
  217. rulesExample: "Rules Example",
  218. lastPage: "Reached the last page",
  219. lastPageTips: "Show tips when reaching the last page"
  220. }
  221. },
  222. {
  223. name: "简体中文",
  224. match: ["zh-CN", "zh-SG"],
  225. lang: {
  226. enableDebug: "调试模式,输出信息至控制台",
  227. disable: "暂时禁用",
  228. disableSite: "站点禁用开关",
  229. disableSiteTips: "已在此站禁用",
  230. enableSiteTips: "已在此站启用",
  231. enable: "启用自动翻页",
  232. toTop: "回到顶部",
  233. toBottom: "前往页尾",
  234. current: "当前页",
  235. forceIframe: "强制拼接",
  236. cancelForceIframe: "取消强制拼接",
  237. configure: "打开配置页面",
  238. firstUpdate: "点击此处初始化规则",
  239. update: "更新在线规则",
  240. click2update: "点击立即更新规则",
  241. loadNow: "立即翻页",
  242. loadConfirm: "要翻几页?(0为不间断)",
  243. noNext: "没有找到下一页,请新建规则",
  244. passSec: "更新于 #t# 秒前",
  245. passMin: "更新于 #t# 分钟前",
  246. passHour: "更新于 #t# 小时前",
  247. passDay: "更新于 #t# 天前",
  248. cantDel: "无法删除内置规则",
  249. confirmDel: "是否确认要删除此规则?",
  250. updateSucc: "更新成功",
  251. beginUpdate: "正在更新,请耐心等待,不要关闭页面",
  252. customUrls: "导入 Pagetual 或 AutoPagerize 规则 url,一行一条",
  253. customRules: "输入【东方永页机】格式的自定义规则 <a href='#t#'>贡献规则</a>",
  254. save: "保存设置",
  255. loadingText: "少女祈祷中...",
  256. opacity: "不透明值",
  257. opacityPlaceholder: "0: 隐藏分隔条",
  258. hideBar: "隐藏分页隔条",
  259. hideBarButNoStop: "隐藏但不停止",
  260. dbClick2Stop: "空白处双击暂停翻页",
  261. sortTitle: "排序在下次更新规则后生效",
  262. autoRun: "自动启用,否则为白名单模式",
  263. autoLoadNum: "自动加载指定页数",
  264. turnRate: "距离页尾【X】倍页面高度时就开始翻页",
  265. inputPageNum: "输入页码跳转",
  266. enableHistory: "翻页后写入历史记录",
  267. enableHistoryAfterInsert: "拼接后立即写入历史记录,否则浏览完毕后再行写入",
  268. contentVisibility: "自动切换 contentVisibility,提升渲染性能",
  269. initRun: "打开页面后立即尝试翻页,否则滚动至页尾再翻页",
  270. preload: "翻页前预读下一页,加速浏览",
  271. click2ImportRule: "点击下方添加特殊规则库,并静待更新成功:",
  272. forceAllBody: "是否拼接整个页面?",
  273. openInNewTab: "使拼接页面的内容在新页面打开",
  274. importSucc: "导入成功",
  275. import: "导入",
  276. editCurrent: "编辑此站规则",
  277. editBlacklist: "编辑黑名单网址,一行一条,支持? *通配符与正则",
  278. upBtnImg: "回到页首图标",
  279. downBtnImg: "前往页尾图标",
  280. sideControllerIcon: "侧边栏图标",
  281. loadingTextTitle: "加载中文字",
  282. dbClick2StopCtrl: "Ctrl 键",
  283. dbClick2StopAlt: "Alt 键",
  284. dbClick2StopShift: "Shift 键",
  285. dbClick2StopMeta: "Meta 键",
  286. dbClick2StopKey: "快捷键",
  287. pageElementCss: "页面主体框架的样式",
  288. customCss: "自定义 css",
  289. firstAlert: "你还未导入规则库,请选择合适的规则库导入哦",
  290. picker: "东方永页机主体元素抓取器",
  291. closePicker: "关闭东方永页机抓取器",
  292. pickerPlaceholder: "元素选择器,没想法建议留空",
  293. pickerCheck: "检查你编辑的选择器并复制",
  294. switchSelector: "点击切换元素",
  295. gotoEdit: "使用当前的选择器前往编辑规则",
  296. manualMode: "禁用拼接,手动用右方向键翻页,可使用左方向键返回",
  297. clickMode: "禁用拼接,滚动至页尾时自动点击下一页",
  298. pageBarMenu: "点击分隔条中间弹出菜单",
  299. nextSwitch: "切换其他页码",
  300. arrowToScroll: "左方向键滚动至上一页,右方向键滚动至下一页",
  301. sideController: "在侧边显示翻页控制栏",
  302. hideLoadingIcon: "隐藏加载动画",
  303. hideBarArrow: "隐藏分隔条定位箭头",
  304. duplicate: "检测到永页机重复安装,请删除其他脚本管理器中的永页机!",
  305. forceStateIframe: "以 iframe 嵌入整页",
  306. forceStateDynamic: "通过 iframe 加载动态内容后取出",
  307. forceStateDisable: "在此站禁用",
  308. autoScrollRate: "滚动速度(1~1000)",
  309. disableAutoScroll: "停止自动滚动",
  310. enableAutoScroll: "开启自动滚动",
  311. toggleAutoScroll: "自动滚动开关",
  312. page: "Page ",
  313. prevPage: "上一页",
  314. nextPage: "下一页",
  315. errorRulesMustBeArray: "规则必须为数组形式!",
  316. errorJson: "JSON 格式有错,请重新检查!",
  317. editSuccess: "编辑成功",
  318. errorWrongUrl: "URL 错误, 请重新检查!",
  319. errorAlreadyExists: "已经存在!",
  320. settingsSaved: "设置已保存,刷新后生效",
  321. iframe: "强制拼接",
  322. dynamic: "动态加载",
  323. reloadPage: "编辑完成,是否立即刷新页面?",
  324. copied: "已复制",
  325. noValidContent: "没有检测到有效内容,可能需要人机校验,点击查看",
  326. outOfDate: "脚本已过时,请及时更新到最新版本!",
  327. hideBarTips: "隐藏分页隔条,沉浸式体验",
  328. setConfigPage: "将当前页面设为默认配置页",
  329. wedata2github: "将 wedata 地址更改为 github 仓库内的镜像地址",
  330. addOtherProp: "添加规则属性",
  331. addNextSelector: "添加选择器内容为 nextLink",
  332. addPageSelector: "添加选择器内容为 pageElement",
  333. propName: "输入规则属性名",
  334. propValue: "输入规则属性值",
  335. customFirst: "为本地自定义规则忽略缓存",
  336. rulesExample: "自定义规则详解",
  337. lastPage: "已到达最后一页",
  338. lastPageTips: "到达最后一页时进行提示"
  339. }
  340. },
  341. {
  342. name: "正體中文",
  343. match: ["zh-TW", "zh-HK"],
  344. lang: {
  345. enableDebug: "調試模式,輸出信息至控制台",
  346. disable: "暫時禁用",
  347. disableSite: "站點禁用開關",
  348. disableSiteTips: "已在此站禁用",
  349. enableSiteTips: "已在此站啟用",
  350. enable: "啟用自動翻頁",
  351. toTop: "回到頂部",
  352. toBottom: "前往頁尾",
  353. current: "當前頁",
  354. forceIframe: "強制拼接",
  355. cancelForceIframe: "取消强制拼接",
  356. configure: "打開配置頁面",
  357. firstUpdate: "點擊此處初始化規則",
  358. update: "更新在綫規則",
  359. click2update: "點擊立即更新規則",
  360. loadNow: "立即翻頁",
  361. loadConfirm: "要翻几頁?(0為不間斷)",
  362. noNext: "沒有找到下一頁,請新建規則",
  363. passSec: "更新于 #t# 秒前",
  364. passMin: "更新于 #t# 分鐘前",
  365. passHour: "更新于 #t# 小時前",
  366. passDay: "更新于 #t# 天前",
  367. cantDel: "無法刪除内置規則",
  368. confirmDel: "是否確認要刪除此規則?",
  369. updateSucc: "更新成功",
  370. beginUpdate: "正在更新,請稍候",
  371. customUrls: "導入 Pagetual 或 AutoPagerize 規則 url,一行一條",
  372. customRules: "輸入【東方永頁機】格式的自定義規則 <a href='#t#'>貢獻規則</a>",
  373. save: "存儲設置",
  374. loadingText: "少女祈禱中...",
  375. opacity: "不透明值",
  376. opacityPlaceholder: "0: 隱藏分隔條",
  377. hideBar: "隱藏分頁隔條",
  378. hideBarButNoStop: "隱藏但不停止",
  379. dbClick2Stop: "空白處雙擊暫停翻頁",
  380. sortTitle: "排序在下次更新規則後生效",
  381. autoRun: "自動啓用,否則為白名單模式",
  382. autoLoadNum: "自動加載指定頁數",
  383. turnRate: "距離頁尾【X】倍頁面高度時就開始翻頁",
  384. inputPageNum: "輸入頁碼跳轉",
  385. enableHistory: "翻頁后寫入歷史記錄",
  386. enableHistoryAfterInsert: "拼接後立即寫入歷史記錄,否則瀏覽完畢後再行寫入",
  387. contentVisibility: "自動切換 contentVisibility,提升渲染性能",
  388. initRun: "打開頁面后立即嘗試翻頁,否則滾動至頁尾再翻頁",
  389. preload: "翻頁前預讀下一頁,加速瀏覽",
  390. click2ImportRule: "點擊下方添加特殊規則庫,并靜待更新成功:",
  391. forceAllBody: "是否拼接整個頁面?",
  392. openInNewTab: "使拼接頁面的内容在新頁面打開",
  393. importSucc: "導入成功",
  394. import: "導入",
  395. editCurrent: "編輯此站規則",
  396. editBlacklist: "編輯黑名單網址,一行一條,支持? *通配符與正則",
  397. upBtnImg: "回到頁首圖標",
  398. downBtnImg: "前往頁尾圖標",
  399. sideControllerIcon: "側邊欄圖標",
  400. loadingTextTitle: "加載中文字",
  401. dbClick2StopCtrl: "Ctrl 鍵",
  402. dbClick2StopAlt: "Alt 鍵",
  403. dbClick2StopShift: "Shift 鍵",
  404. dbClick2StopMeta: "Meta 鍵",
  405. dbClick2StopKey: "快捷鍵",
  406. pageElementCss: "頁面主體框架的樣式",
  407. customCss: "自定義 css",
  408. firstAlert: "你還未導入規則庫,請選擇合適的規則庫導入哦",
  409. picker: "東方永頁機主體元素抓取器",
  410. closePicker: "關閉東方永頁機抓取器",
  411. pickerPlaceholder: "元素選擇器,沒想法建議留空",
  412. pickerCheck: "檢查你編輯的選擇器並複製",
  413. switchSelector: "點擊切換元素",
  414. gotoEdit: "使用當前的選擇器前往編輯規則",
  415. manualMode: "禁用拼接,手動用右方向鍵翻頁,左方向鍵返回",
  416. clickMode: "禁用拼接,滾動至頁尾時自動點擊下一頁",
  417. pageBarMenu: "點擊分隔條中間彈出菜單",
  418. nextSwitch: "切換其他頁碼",
  419. arrowToScroll: "左方向鍵滾動至上一頁,右方向鍵滾動至下一頁",
  420. sideController: "在側邊顯示翻頁控制欄",
  421. hideLoadingIcon: "隱藏加載動畫",
  422. hideBarArrow: "隱藏分隔條定位箭頭",
  423. duplicate: "檢測到永頁機重複安裝,請刪除其他腳本管理器中的永頁機!",
  424. forceStateIframe: "以 iframe 嵌入整頁",
  425. forceStateDynamic: "通過 iframe 加載動態內容後取出",
  426. forceStateDisable: "在此站禁用",
  427. autoScrollRate: "滾動速度(1~1000)",
  428. disableAutoScroll: "停止自動滾動",
  429. enableAutoScroll: "開啟自動滾動",
  430. toggleAutoScroll: "自動滾動開關",
  431. page: "Page ",
  432. prevPage: "上一頁",
  433. nextPage: "下一頁",
  434. errorRulesMustBeArray: "規則必須為陣列形式!",
  435. errorJson: "JSON 格式有錯,請重新檢查!",
  436. editSuccess: "編輯成功",
  437. errorWrongUrl: "URL 錯誤, 請重新檢查!",
  438. errorAlreadyExists: "已經存在!",
  439. settingsSaved: "設置已保存,刷新後生效",
  440. iframe: "強制拼接",
  441. dynamic: "動態加載",
  442. reloadPage: "編輯完成,是否立即刷新頁面?",
  443. copied: "已復制",
  444. noValidContent: "沒有檢測到有效内容,可能需要人機校驗,點擊查看",
  445. outOfDate: "脚本已過時,請及時更新到最新版本!",
  446. hideBarTips: "隱藏分頁隔條,沉浸式體驗",
  447. setConfigPage: "將當前頁面設為默認配置頁",
  448. wedata2github: "將 wedata 地址更改為 github 倉庫內的鏡像地址",
  449. addOtherProp: "添加規則屬性",
  450. addNextSelector: "添加選擇器內容為 nextLink",
  451. addPageSelector: "添加選擇器內容為 pageElement",
  452. propName: "輸入規則屬性名",
  453. propValue: "輸入規則屬性值",
  454. customFirst: "為本地自定義規則忽略緩存",
  455. rulesExample: "自定義規則詳解",
  456. lastPage: "已到達最後一頁",
  457. lastPageTips: "到達最後一頁時進行提示"
  458. }
  459. },
  460. {
  461. name: "日本語",
  462. match: ["ja"],
  463. lang: {
  464. enableDebug: "デバッグモード",
  465. disable: "一時的に無効",
  466. disableSite: "無効状態の切り替え",
  467. disableSiteTips: "このサイトで既に無効になっています",
  468. enableSiteTips: "このサイトで既に有効になっています",
  469. enable: "ページめくりを有効にする",
  470. toTop: "トップに戻る",
  471. toBottom: "ページの下部に移動",
  472. current: "現在のページ",
  473. forceIframe: "強制ステッチ",
  474. cancelForceIframe: "強制ステッチをキャンセル",
  475. configure: "設定ページを開く",
  476. firstUpdate: "ここをクリックしてルールを初期化します",
  477. update: "更新ルール",
  478. click2update: "今すぐルールを更新してください",
  479. loadNow: "今すぐページをめくる",
  480. loadConfirm: "数ページめくりたいですか?(0は途切れない)",
  481. noNext: "次のページが見つかりません、新しいルールを作成してください",
  482. passSec: "#t#秒前に更新",
  483. passMin: "#t#分前に更新",
  484. passHour: "#t#時間前に更新",
  485. passDay: "#t#日前に更新",
  486. cantDel: "組み込みルールを削除できません",
  487. confirmDel: "このルールを削除してもよろしいですか?",
  488. updateSucc: "更新に成功しました",
  489. beginUpdate: "更新中、お待ちください",
  490. customUrls: "インポートルールのURL、1行に1つ",
  491. customRules: "【東方永頁機】の形式でカスタムルールを入力してください <a href='#t#'>寄稿ルール</a>",
  492. save: "設定を保存",
  493. loadingText: "少女祈祷中...",
  494. opacity: "不透明値",
  495. opacityPlaceholder: "0: 隠す",
  496. hideBar: "ページ区切り文字を非表示にします",
  497. hideBarButNoStop: "非表示にするが停止しない",
  498. dbClick2Stop: "空白部分をダブルクリックしてページめくりを一時停止します",
  499. sortTitle: "並べ替えは、次のルールの更新後に有効になります",
  500. autoRun: "自動的に有効",
  501. autoLoadNum: "指定したページ数を自動的に読み込みます",
  502. turnRate: "ページの端からページの高さの【X】倍になったらページをめくる",
  503. inputPageNum: "ジャンプするページ番号を入力",
  504. enableHistory: "ページめくり後の履歴を書く",
  505. enableHistoryAfterInsert: "スプライシングの直後に履歴レコードを書き込みます。それ以外の場合は、閲覧後に書き込みます",
  506. contentVisibility: "contentVisibility を自動的に切り替えてレンダリング パフォーマンスを向上させる",
  507. initRun: "Webページを開いた直後にページをめくる",
  508. preload: "事前に次のページを読む",
  509. click2ImportRule: "以下をクリックして、ルールベースを追加します:",
  510. forceAllBody: "フルページ埋め込み?",
  511. openInNewTab: "スプライスされたページのコンテンツを新しいページで開きます",
  512. importSucc: "インポート完了",
  513. import: "インポート",
  514. editCurrent: "現在のルールの編集",
  515. editBlacklist: "ブラックリストのURLを編集し、1行ずつ、サポート? *ワイルドカード",
  516. upBtnImg: "トップアイコンに戻る",
  517. downBtnImg: "フッターアイコンに移動",
  518. sideControllerIcon: "サイドバー アイコン",
  519. loadingTextTitle: "テキストをロード",
  520. dbClick2StopCtrl: "Ctrlキー",
  521. dbClick2StopAlt: "Altキー",
  522. dbClick2StopShift: "Shiftキー",
  523. dbClick2StopMeta: "Metaキー",
  524. dbClick2StopKey: "Shortcutキー",
  525. pageElementCss: "ページ本文フレームの STYLE",
  526. customCss: "カスタム css",
  527. firstAlert: "ルールベースをインポートしていないため、インポートする適切なルールベースを選択してください",
  528. picker: "Pagetualページ要素ピッカー",
  529. closePicker: "Pagetualピッカーを閉じる",
  530. pickerPlaceholder: "わからない場合は空のままにしてください",
  531. pickerCheck: "セレクターをチェックしてコピー",
  532. switchSelector: "クリックして要素を切り替えます",
  533. gotoEdit: "現在のセレクターでルールを編集する",
  534. manualMode: "スプライシングを無効にします。手動で右の矢印キーを使用してページをめくります",
  535. clickMode: "スティッチングを無効にします。ページの最後までスクロールすると、次のページが自動的にクリックされます",
  536. pageBarMenu: "ページバーの中央をクリックしてメニューをポップアップ表示",
  537. nextSwitch: "次のページに切り替え",
  538. arrowToScroll: "左矢印キーで前へ、右矢印キーで次へ",
  539. sideController: "サイドバーにページング コントロール バーを表示する",
  540. hideLoadingIcon: "読み込み中のアニメーションを隠す",
  541. hideBarArrow: "分割線の位置矢印を隠す",
  542. duplicate: "Pagetual の重複インストールが検出されました。他のスクリプト マネージャで永続的なページ マシンを削除してください!",
  543. forceStateIframe: "iframe にページ全体を埋め込む",
  544. forceStateDynamic: "iframe 経由で動的コンテンツを読み込む",
  545. forceStateDisable: "このステーションでのページめくりを無効にする",
  546. autoScrollRate: "スクロール速度 (1~1000)",
  547. disableAutoScroll: "自動スクロールを停止します",
  548. EnableAutoScroll: "自動スクロールを有効にする",
  549. toggleAutoScroll: "自動スクロールの切り替え",
  550. page: "Page ",
  551. prevPage: "Prev page",
  552. nextPage: "Next page",
  553. errorRulesMustBeArray: "Rules must be a Array!",
  554. errorJson: "JSON error, check again!",
  555. editSuccess: "Edit successfully",
  556. errorWrongUrl: "Wrong url, check again!",
  557. errorAlreadyExists: "Already exists!",
  558. settingsSaved: "The settings are saved, refresh to view",
  559. iframe: "Iframe",
  560. dynamic: "Dynamic",
  561. reloadPage: "Edit completed, reload page now?",
  562. copied: "Copied",
  563. noValidContent: "有効なコンテンツが検出されませんでした。クリックして表示",
  564. outOfDate: "スクリプトが古くなっています。最新バージョンに更新してください。",
  565. hideBarTips: "ページネーション バーを非表示にします。没入型エクスペリエンス",
  566. setConfigPage: "現在のページをデフォルト設定ページとして設定",
  567. wedata2github: "wedata アドレスを github ウェアハウスのミラー アドレスに変更",
  568. addOtherProp: "ルールプロパティを追加",
  569. addNextSelector: "セレクターのコンテンツを nextLink として追加",
  570. addPageSelector: "セレクタ コンテンツを pageElement として追加",
  571. propName: "ルールのプロパティ名を入力してください",
  572. propValue: "ルールのプロパティ値を入力してください",
  573. customFirst: "ローカルカスタムルールのキャッシュを無視する",
  574. rulesExample: "カスタムルールの詳しい説明",
  575. lastPage: "最後のページに到達しました",
  576. lastPageTips: "最後のページに到達した時にヒントを表示する"
  577. }
  578. },
  579. {
  580. name: "Русский",
  581. match: ["ru", "ru-RU"],
  582. lang: {
  583. enableDebug: "Включить отладку",
  584. disable: "Выключить",
  585. disableSite: "Включить/выключить на сайте",
  586. disableSiteTips: "Выключено для этого сайта",
  587. enableSiteTips: "Включено для этого сайта",
  588. enable: "Включить",
  589. toTop: "Наверх",
  590. toBottom: "Вниз",
  591. current: "Текущая страница",
  592. forceIframe: "Подгрузить ещё страницу",
  593. cancelForceIframe: "Отменить подгрузку",
  594. configure: "Настройки",
  595. firstUpdate: "Нажмите здесь, чтобы инициализировать правила",
  596. update: "Обновить правила",
  597. click2update: "Нажмите, чтобы обновить правила",
  598. loadNow: "Загрузить следующую страницу",
  599. loadConfirm: "Сколько страниц вы хотите загрузить? (0 означает бесконечность)",
  600. noNext: "Ссылка на следующую страницу не найдена. Пожалуйста, создайте новое правило",
  601. passSec: "Обновлено #t# секунд назад",
  602. passMin: "Обновлено #t# минут назад",
  603. passHour: "Обновлено #t# часов назад",
  604. passDay: "Обновлено #t# дней назад",
  605. cantDel: "Нельзя удалить правила по умолчанию",
  606. confirmDel: "Вы уверены, что хотите удалить эту ссылку?",
  607. updateSucc: "Правила обновлены",
  608. beginUpdate: "Обновление. Пожалуйста, немного подождите",
  609. customUrls: "Ссылки с правилами для импорта. Одна ссылка на строку",
  610. customRules: "Введите пользовательские правила в формате Pagetual. <a href='#t#'>Улучшить встроенные правила</a>",
  611. save: "Сохранить настройки",
  612. loadingText: "Следующая страница подгружается…",
  613. opacity: "Прозрачность",
  614. opacityPlaceholder: "0 - скрыть",
  615. hideBar: "Скрыть разделитель страниц",
  616. hideBarButNoStop: "Скрыть, но не останавливать",
  617. dbClick2Stop: "Двойной клик на странице для выключения",
  618. sortTitle: "Правило сортировки применится после следующего обновления правил",
  619. autoRun: "Автозапуск (режим черного списка)",
  620. autoLoadNum: "Количество страниц для предзагрузки",
  621. turnRate: "Подгрузить страницу, когда она будет в 【X】 раз больше высоты страницы от конца страницы",
  622. inputPageNum: "Введите номер страницы для перехода",
  623. enableHistory: "Записать историю после переключения страниц",
  624. enableHistoryAfterInsert: "Записать запись истории сразу после вставки, иначе записать после просмотра",
  625. contentVisibility: "Автоматически переключать contentVisibility для повышения производительности рендеринга",
  626. initRun: "Подгружать страницы сразу после открытия",
  627. preload: "Предзагрузка следующей страницы",
  628. click2ImportRule: "Нажмите, чтобы импортировать базовые правила: ",
  629. forceAllBody: "Присоединить страницу целиком?",
  630. openInNewTab: "Открыть дополнительные ссылки в новой вкладке",
  631. importSucc: "Импорт завершен",
  632. import: "Импорт",
  633. editCurrent: "Изменить правило для текущего сайта",
  634. editBlacklist: "Изменить черный список. Одна ссылка на строку. Поддерживаются метасимволы: ? и *",
  635. upBtnImg: "Иконка перехода к началу",
  636. downBtnImg: "Иконка перехода к концу",
  637. sideControllerIcon: "Значок боковой панели",
  638. loadingTextTitle: "Текст во время загрузки",
  639. dbClick2StopCtrl: "Ctrl",
  640. dbClick2StopAlt: "Alt",
  641. dbClick2StopShift: "Shift",
  642. dbClick2StopMeta: "Meta",
  643. dbClick2StopKey: "Клавиша",
  644. pageElementCss: "Пользовательский стиль для основных элементов страницы",
  645. customCss: "Полный пользовательский CSS",
  646. firstAlert: "Вы не импортировали базовое правило. Пожалуйста, выберите соответствующее правило для импорта",
  647. picker: "Pagetual: выбор элемента страницы",
  648. closePicker: "Закрыть окно Pagetual",
  649. pickerPlaceholder: "Если не знаете, что тут писать — оставьте поле пустым",
  650. pickerCheck: "Проверить и скопировать селектор",
  651. switchSelector: "Нажмите для выбора элемента",
  652. gotoEdit: "Перейти к редактированию правила с текущим селектором",
  653. manualMode: "Отключить автоматическую загрузку страниц. Загружать вручную с помощью стрелки вправо (или вызова события 'pagetual.next')",
  654. clickMode: "Отключить \"сшивание\" страниц. При прокрутке до конца автоматически переходить на следующую страницу",
  655. pageBarMenu: "Открывать меню кликом на середину панели страниц",
  656. nextSwitch: "Переключить ссылку на следующую страницу",
  657. arrowToScroll: "Листать страницы клавишами со стрелками влево и вправо",
  658. sideController: "Показать справа панель перемещения по вкладке",
  659. hideLoadingIcon: "Скрыть анимацию загрузки",
  660. hideBarArrow: "Скрыть кнопки перемещения на разделителе",
  661. duplicate: "Похоже, Pagetual установлен несколько раз. Пожалуйста, удалите Pagetual из других менеджеров скриптов!",
  662. forceStateIframe: "Вставить полную страницу как iframe",
  663. forceStateDynamic: "Загружать динамический контент через iframe",
  664. forceStateDisable: "Отключить перелистывание страниц на этой станции",
  665. autoScrollRate: "Скорость прокрутки (1~1000)",
  666. disableAutoScroll: "Остановить автоматическую прокрутку",
  667. enableAutoScroll: "Включить автопрокрутку",
  668. toggleAutoScroll: "Переключить автопрокрутку",
  669. page: "Страница ",
  670. prevPage: "Предыдущая страница",
  671. nextPage: "Следующая страница",
  672. errorRulesMustBeArray: "Правила должны быть массивом!",
  673. errorJson: "Ошибка разбора JSON. Пожалуйста, исправьте его",
  674. editSuccess: "Редактирование успешно",
  675. errorWrongUrl: "Ссылка некорректна. Пожалуйста, исправьте её",
  676. errorAlreadyExists: "Уже существует!",
  677. settingsSaved: "Настройки сохранены. Обновите страницы",
  678. iframe: "iframe",
  679. dynamic: "Динамически",
  680. reloadPage: "Редактирование завершено. Обновить страницу?",
  681. copied: "Скопировано",
  682. noValidContent: "Действительный контент не обнаружен, нажмите для просмотра",
  683. outOfDate: "Скрипт устарел, своевременно обновляйте до последней версии!",
  684. hideBarTips: "Скрыть панель разбиения на страницы, иммерсивный опыт",
  685. setConfigPage: "Установить текущую страницу в качестве страницы конфигурации по умолчанию",
  686. wedata2github: "Изменить адрес wedata на зеркальный адрес на складе github",
  687. addOtherProp: "Добавить свойство правила",
  688. addNextSelector: "Добавить содержимое селектора как nextLink",
  689. addPageSelector: "Добавить содержимое селектора как pageElement",
  690. propName: "Введите имя свойства правила",
  691. propValue: "Введите значение свойства правила",
  692. customFirst: "Игнорировать кеш для локальных пользовательских правил",
  693. rulesExample: "Подробное объяснение настраиваемых правил",
  694. lastPage: "Достигнута последняя страница",
  695. lastPageTips: "Показывать подсказки при достижении последней страницы"
  696. }
  697. }
  698. ];
  699. var langList = {};
  700. langData.forEach(lang => {
  701. langList[lang.match[0]] = lang.name;
  702. });
  703. var i18nData = langData[0].lang;
  704. function setLang(la) {
  705. for (let i = 0; i < langData.length; i++) {
  706. let lang = langData[i];
  707. if (lang && lang.match.indexOf(la) !== -1) {
  708. i18nData = lang.lang;
  709. break;
  710. }
  711. }
  712. }
  713. setLang(lang);
  714.  
  715. var enableDebug = true;
  716. function i18n(name, param) {
  717. return i18nData[name] ? i18nData[name].replace("#t#", param) : name;
  718. };
  719.  
  720. function debug(str, title) {
  721. if (enableDebug) {
  722. console.log(
  723. `%cPagetual v.${_GM_info.script.version}】 ${title ? title : 'debug'}:`,
  724. 'color: yellow;font-size: large;font-weight: bold;background-color: darkblue;',
  725. str
  726. );
  727. }
  728. };
  729.  
  730. var _GM_xmlhttpRequest, _GM_registerMenuCommand, _GM_notification, _GM_addStyle, _GM_openInTab, _GM_info, _GM_setClipboard;
  731. if (typeof GM_xmlhttpRequest != 'undefined') {
  732. _GM_xmlhttpRequest = GM_xmlhttpRequest;
  733. } else if (typeof GM != 'undefined' && typeof GM.xmlHttpRequest != 'undefined') {
  734. _GM_xmlhttpRequest = GM.xmlHttpRequest;
  735. } else {
  736. _GM_xmlhttpRequest = (f) => {fetch(f.url).then(response => response.text()).then(data => {let res = {response:data}; f.onload(res)}).catch(e => f.onerror(e))};
  737. }
  738. if (typeof GM_registerMenuCommand != 'undefined') {
  739. _GM_registerMenuCommand = GM_registerMenuCommand;
  740. } else if (typeof GM != 'undefined' && typeof GM.registerMenuCommand != 'undefined') {
  741. _GM_registerMenuCommand = GM.registerMenuCommand;
  742. } else {
  743. _GM_registerMenuCommand = (s, f) => {};
  744. }
  745. if (typeof GM_info != 'undefined') {
  746. _GM_info = GM_info;
  747. } else if (typeof GM != 'undefined' && typeof GM.info != 'undefined') {
  748. _GM_info = GM.info;
  749. } else {
  750. _GM_info = {script: {}};
  751. }
  752. if (typeof GM_notification != 'undefined') {
  753. _GM_notification = GM_notification;
  754. } else if (typeof GM != 'undefined' && typeof GM.notification != 'undefined') {
  755. _GM_notification = GM.notification;
  756. } else {
  757. _GM_notification = (s) => {showTips(s)};
  758. }
  759. if (typeof GM_openInTab != 'undefined') {
  760. _GM_openInTab = GM_openInTab;
  761. } else if (typeof GM != 'undefined' && typeof GM.openInTab != 'undefined') {
  762. _GM_openInTab = GM.openInTab;
  763. } else {
  764. _GM_openInTab = (s,t) => {window.open(s)};
  765. }
  766. if (typeof GM_addStyle != 'undefined') {
  767. _GM_addStyle = GM_addStyle;
  768. } else if (typeof GM != 'undefined' && typeof GM.addStyle != 'undefined') {
  769. _GM_addStyle = GM.addStyle;
  770. } else {
  771. _GM_addStyle = cssStr => {
  772. let styleEle = document.createElement("style");
  773. styleEle.innerHTML = cssStr;
  774. document.head.appendChild(styleEle);
  775. return styleEle;
  776. };
  777. }
  778. if (typeof GM_setClipboard != 'undefined') {
  779. _GM_setClipboard = GM_setClipboard;
  780. } else if (typeof GM != 'undefined' && typeof GM.setClipboard != 'undefined') {
  781. _GM_setClipboard = GM.setClipboard;
  782. } else {
  783. _GM_setClipboard = (s, i) => {};
  784. }
  785. const _unsafeWindow = (typeof unsafeWindow == 'undefined') ? window : unsafeWindow;//兼容 ios userscripts 的寫法
  786. const storage = {
  787. supportGM: typeof GM_getValue == 'function' && typeof GM_getValue('a', 'b') != 'undefined',
  788. supportGMPromise: typeof GM != 'undefined' && typeof GM.getValue == 'function' && typeof GM.getValue('a', 'b') != 'undefined' && typeof GM.getValue('a', 'b').then == 'function',
  789. supportCrossSave: function() {
  790. return this.supportGM || this.supportGMPromise;
  791. },
  792. mxAppStorage: (function() {
  793. try {
  794. return window.external.mxGetRuntime().storage;
  795. } catch(e) {
  796. }
  797. })(),
  798. operaUJSStorage: (function() {
  799. try {
  800. return window.opera.scriptStorage;
  801. } catch(e) {
  802. }
  803. })(),
  804. setItem: function(key, value) {
  805. if (this.supportGMPromise) {
  806. GM.setValue(key, value);
  807. if (value === "" && typeof GM != 'undefined' && typeof GM.deleteValue != 'undefined') {
  808. GM.deleteValue(key);
  809. }
  810. } else if (this.supportGM) {
  811. GM_setValue(key, value);
  812. if (value === "" && typeof GM_deleteValue != 'undefined') {
  813. GM_deleteValue(key);
  814. }
  815. } else if (this.operaUJSStorage) {
  816. this.operaUJSStorage.setItem(key, value);
  817. } else if (this.mxAppStorage) {
  818. this.mxAppStorage.setConfig(key, value);
  819. } else if (window.localStorage) {
  820. window.localStorage.setItem(key, value);
  821. }
  822. },
  823. getItem: function(key, cb) {
  824. var value;
  825. if (this.supportGMPromise) {
  826. value = GM.getValue(key).then(v => {cb(v)});
  827. return;
  828. } else if (this.supportGM) {
  829. value = GM_getValue(key);
  830. } else if (this.operaUJSStorage) {
  831. value = this.operaUJSStorage.getItem(key);
  832. } else if (this.mxAppStorage) {
  833. value = this.mxAppStorage.getConfig(key);
  834. } else if (window.localStorage) {
  835. value = window.localStorage.getItem(key);
  836. };
  837. cb(value);
  838. }
  839. };
  840. var rulesData = {uninited: true}, ruleUrls, updateDate;
  841. const configPage = ["https://github.com/hoothin/UserScripts/tree/master/Pagetual",
  842. "https://hoothin.github.io/UserScripts/Pagetual/"];
  843. const guidePage = /^https?:\/\/.*pagetual.*rule\.html/i;
  844. const ruleImportUrlReg = /greasyfork\.org\/.*scripts\/438684(\-[^\/]*)?(\/discussions|\/?$|\/feedback)|github\.com\/hoothin\/UserScripts\/(tree\/master\/Pagetual|issues)/i;
  845. const allOfBody = "body>*";
  846. const mainSel = "article,.article,[role=main],main,.main,#main";
  847. 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\u0020\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Вперед", "i");
  848. const nextTextReg2 = new RegExp("\u005e\u0028\u005b\u4e0b\u540e\u5f8c\u6b21\u005d\u005b\u4e00\u30fc\u0031\u005d\u003f\u005b\u7ae0\u8bdd\u8a71\u8282\u7bc0\u4e2a\u500b\u5e45\u005d\u007c\u006e\u0065\u0078\u0074\u002e\u003f\u0063\u0068\u0061\u0070\u0074\u0065\u0072\u0029\u0028\u005b\u003a\uff1a\u005c\u005c\u002d\u005f\u2014\u0020\u005c\u005c\u002e\u3002\u003e\u0023\u00b7\u005c\u005c\u005b\u3010\u3001\uff08\u005c\u005c\u0028\u002f\u002c\uff0c\uff1b\u003b\u2192\u005d\u007c\u0024\u0029", "i");
  849. const lazyImgAttr = ["data-lazy-src", "data-lazy", "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"];
  850.  
  851. function getBody(doc) {
  852. return doc.body || doc.querySelector('body') || doc;
  853. }
  854.  
  855. function getElementByXpath(xpath, doc, contextNode) {
  856. doc = doc || document;
  857. contextNode = contextNode || doc;
  858. try {
  859. let result = doc.evaluate(xpath, contextNode, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  860. return result.singleNodeValue && result.singleNodeValue.nodeType === 1 && result.singleNodeValue;
  861. } catch (err) {
  862. debug(`Invalid xpath: ${xpath}`);
  863. }
  864. return null;
  865. }
  866.  
  867. function getAllElementsByXpath(xpath, contextNode, doc) {
  868. doc = doc || document;
  869. contextNode = contextNode || doc;
  870. var result = [];
  871. try {
  872. var query = doc.evaluate(xpath, contextNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  873. for (var i = 0; i < query.snapshotLength; i++) {
  874. var node = query.snapshotItem(i);
  875. if (node.nodeType === 1) result.push(node);
  876. }
  877. } catch (err) {
  878. debug(`Invalid xpath: ${xpath}`);
  879. }
  880. return result;
  881. }
  882.  
  883. function isXPath(xpath) {
  884. if (!xpath) return false;
  885. return /^\(*(descendant::|\.\/|\/|id\()/.test(xpath);
  886. }
  887.  
  888. function getAllElements(sel, doc, contextNode) {
  889. try {
  890. if (!isXPath(sel)) {
  891. return doc.querySelectorAll(sel);
  892. }
  893. } catch(e) {
  894. debug(e, 'Error selector');
  895. }
  896. return getAllElementsByXpath(sel, contextNode, doc);
  897. }
  898.  
  899. function getElement(sel, doc, contextNode, bySort) {
  900. try {
  901. if (!isXPath(sel)) {
  902. if (!bySort) {
  903. return doc.querySelector(sel);
  904. } else {
  905. let selArr = sel.split(",");
  906. try {
  907. for (let i = 0; i < selArr.length; i++) {
  908. let ele = doc.querySelector(selArr[i].trim());
  909. if (ele) return ele;
  910. }
  911. } catch(e) {
  912. return doc.querySelector(sel);
  913. }
  914. return null;
  915. }
  916. }
  917. } catch(e) {
  918. debug(e, 'Error selector');
  919. }
  920. return getElementByXpath(sel, doc, contextNode);
  921. }
  922.  
  923. function geneSelector(ele, addID) {
  924. let selector = ele.nodeName.toLowerCase();
  925. //Google id class都是隨機。百度更過分,style script順序都是隨機的
  926. if (selector != "html" && selector != "body") {
  927. let hasId = false;
  928. if (addID && ele.id && /^[a-z_][\w\-_]*$/i.test(ele.id)) {
  929. if (ele.ownerDocument && ele.ownerDocument.querySelectorAll("#" + ele.id).length == 1) {
  930. hasId = true;
  931. selector = '#' + ele.id;
  932. }
  933. }
  934. if (!hasId) {
  935. let className = "";
  936. if (ele.className) {
  937. let classList = ele.classList, i = 0;
  938. for (let i = 0; i < classList.length; i++) {
  939. let c = classList[i];
  940. if (/^[\w\-_]+$/.test(c) && !/\d{4,}/.test(c)) {
  941. className += '.' + c;
  942. }
  943. }
  944. selector += className;
  945. }
  946. let parent = ele.parentElement;
  947. if (parent) {
  948. selector = geneSelector(parent, addID) + ' > ' + selector;
  949. if (!className && !hasId && parent.children.length > 1 && !/^HTML$/i.test(parent.nodeName)) {
  950. let i, nth = 0, all = 0;
  951. for (i = 0; i < parent.children.length; i++) {
  952. if (parent.children[i].nodeName == ele.nodeName) {
  953. all++;
  954. if (parent.children[i] == ele) {
  955. nth = all;
  956. }
  957. if (nth > 0 && all > 1) break;
  958. }
  959. }
  960. selector += (all == 1 ? "" : `:nth-of-type(${nth})`);
  961. }
  962. }
  963. }
  964. }
  965. return selector;
  966. }
  967.  
  968. function createXPathFromElement(elm) {
  969. let allNodes = document.getElementsByTagName('*'), segs;
  970. for (segs = []; elm && elm.nodeType == 1; elm = elm.parentNode) {
  971. if (/^(BODY|HTML)$/i.test(elm.nodeName)) {
  972. segs.unshift(elm.localName.toLowerCase());
  973. continue;
  974. }
  975. if (elm.hasAttribute && elm.hasAttribute('id')) {
  976. var uniqueIdCount = 0;
  977. for (var n = 0; n < allNodes.length; n++) {
  978. if (allNodes[n].hasAttribute('id') && allNodes[n].id == elm.id) uniqueIdCount++;
  979. if (uniqueIdCount > 1) break;
  980. }
  981. if ( uniqueIdCount == 1) {
  982. segs.unshift('id("' + elm.getAttribute('id') + '")');
  983. return segs.join('/');
  984. } else {
  985. segs.unshift(elm.localName.toLowerCase() + '[@id="' + elm.getAttribute('id') + '"]');
  986. }
  987. } else if (elm.hasAttribute && elm.hasAttribute('class')) {
  988. segs.unshift(elm.localName.toLowerCase() + '[@class="' + elm.getAttribute('class') + '"]');
  989. } else {
  990. let i, sib;
  991. for (i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling) {
  992. if (sib.localName == elm.localName) i++;
  993. }
  994. segs.unshift(elm.localName.toLowerCase() + '[' + i + ']');
  995. }
  996. }
  997. return segs.length ? '/' + segs.join('/') : null;
  998. }
  999.  
  1000. const escapeHTMLPolicy = (_unsafeWindow.trustedTypes && _unsafeWindow.trustedTypes.createPolicy) ? _unsafeWindow.trustedTypes.createPolicy('pagetual_default', {
  1001. createHTML: (string, sink) => string
  1002. }) : null;
  1003.  
  1004. function createHTML(html) {
  1005. return escapeHTMLPolicy ? escapeHTMLPolicy.createHTML(html) : html;
  1006. }
  1007.  
  1008. const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
  1009.  
  1010. async function sleep(time) {
  1011. await new Promise((resolve) => {
  1012. setTimeout(() => {
  1013. resolve();
  1014. }, time);
  1015. })
  1016. }
  1017.  
  1018. class RuleParser {
  1019. constructor() {
  1020. this.hpRules = [];
  1021. this.smartRules = [];
  1022. this.customRules = [];
  1023. this.rules = [];
  1024. this.pageDoc = document;
  1025. this.nextLinkHref = null;
  1026. this.nextTitle = "";
  1027. this.oldUrl = "";
  1028. this.curUrl = location.href;
  1029. this.curSiteRule = {};
  1030. }
  1031.  
  1032. initSavedRules(callback) {
  1033. var self = this;
  1034. storage.getItem("smartRules", smartRules => {
  1035. if (smartRules) self.smartRules = smartRules;
  1036. storage.getItem("hpRules", hpRules => {
  1037. if (hpRules) self.hpRules = hpRules;
  1038. storage.getItem("customRules", customRules => {
  1039. if (customRules) self.customRules = customRules;
  1040. storage.getItem("rules", rules => {
  1041. if (rules) self.rules = rules;
  1042. callback();
  1043. });
  1044. });
  1045. });
  1046. });
  1047. }
  1048.  
  1049. saveCurSiteRule() {
  1050. /*if(!this.curSiteRule || !this.curSiteRule.url || this.curSiteRule.singleUrl || this.curSiteRule.url.length<13)return;
  1051. this.hpRules=this.hpRules.filter(item=>{return item&&item.url!=this.curSiteRule.url});
  1052. this.hpRules.unshift(this.curSiteRule);
  1053. if(this.hpRules.length>30){
  1054. this.hpRules.pop();
  1055. }
  1056. storage.setItem("hpRules", this.hpRules);*/
  1057. }
  1058.  
  1059. requestJSON(url, callback) {
  1060. _GM_xmlhttpRequest({
  1061. url: url,
  1062. method: 'GET',
  1063. timeout: 20000,
  1064. onload: function(res) {
  1065. let json = null;
  1066. try {
  1067. json = JSON.parse(res.response || res.responseText);
  1068. } catch(e) {
  1069. debug(e, 'Error json');
  1070. }
  1071. callback(json);
  1072. },
  1073. onerror: function(e) {
  1074. callback(null, e);
  1075. },
  1076. ontimeout: function(e) {
  1077. callback(null, e);
  1078. }
  1079. });
  1080. }
  1081.  
  1082. formatRule(item, from) {
  1083. if (item.data && item.data.url) {
  1084. let result = {
  1085. name: item.name,
  1086. from: from,
  1087. action: item.data.forceIframe=="true"?1:undefined,
  1088. url: item.data.url,
  1089. pageElement: item.data.pageElement,
  1090. nextLink: item.data.nextLink,
  1091. insert: item.data.insertBefore||undefined,
  1092. updatedAt: item.updated_at
  1093. };
  1094. let _css = (item.data.Stylus || '') + (item.data.CSS || '');
  1095. if (_css) result.css = _css;
  1096. if (item.data.bookmarklet) result.pageAction = item.data.bookmarklet;
  1097. return result;
  1098. } else {
  1099. item.from = from;
  1100. return item;
  1101. }
  1102. return null;
  1103. }
  1104.  
  1105. addRuleByUrl(url, from, callback) {
  1106. if (url.indexOf("?") == -1) {
  1107. url = url + "?" + Date.now();
  1108. } else {
  1109. url = url + "&" + Date.now();
  1110. }
  1111. this.requestJSON(url, (json,err) => {
  1112. if (!json) {
  1113. debug(err, "Failed to update " + url + " rules!");
  1114. }
  1115. this.addRules(json, from);
  1116. callback(json, err);
  1117. });
  1118. }
  1119.  
  1120. addRules(rules, from) {
  1121. if (rules && rules.length > 0) {
  1122. let first = -1;
  1123. this.rules = this.rules.filter((item, i) => {
  1124. if (item.from == from) {
  1125. if (first == -1) first = i;
  1126. return false;
  1127. } else return true;
  1128. });
  1129. if (first == -1) first = 0;
  1130. rules.forEach(item => {
  1131. let rule = this.formatRule(item, from);
  1132. if (rule) {
  1133. this.rules.splice(first, 0, rule)
  1134. }
  1135. });
  1136. }
  1137. }
  1138.  
  1139. ruleMatchPre(r) {
  1140. if (r.include) {
  1141. let include;
  1142. if (Array && Array.isArray && Array.isArray(r.include)) {
  1143. include = r.include.every((sel, i) => {
  1144. let ele = getElement(sel, document);
  1145. return !!ele;
  1146. });
  1147. } else include = getElement(r.include, document);
  1148. if (!include) return false;
  1149. }
  1150. if (r.exclude) {
  1151. let exclude;
  1152. if (Array && Array.isArray && Array.isArray(r.exclude)) {
  1153. exclude = !r.exclude.every((sel, i) => {
  1154. let ele = getElement(sel, document);
  1155. return !ele;
  1156. });
  1157. } else exclude = getElement(r.exclude, document);
  1158. if (exclude) return false;
  1159. }
  1160. return true;
  1161. }
  1162.  
  1163. ruleMatchReady(r) {
  1164. let findIndex = 0;
  1165. if (r.nextLink && r.nextLink != 0) {
  1166. let nextLinkSel = r.nextLink, nextLink;
  1167. if (Array && Array.isArray && Array.isArray(nextLinkSel)) {
  1168. nextLink = !nextLinkSel.every((sel, i) => {
  1169. let ele = getElement(sel, document);
  1170. if (ele) findIndex = i;
  1171. return !ele;
  1172. });
  1173. } else nextLink = getElement(nextLinkSel, document);
  1174. if (!nextLink) return false;
  1175. }
  1176. if (r.pageElement) {
  1177. let pageElementSel = r.pageElement, pageElement;
  1178. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  1179. pageElementSel = pageElementSel[findIndex];
  1180. }
  1181. pageElement = getElement(pageElementSel, document);
  1182. if (!pageElement) return false;
  1183. }
  1184. if (r.insert) {
  1185. let insertSel = r.insert, insert;
  1186. if (Array && Array.isArray && Array.isArray(insertSel)) {
  1187. insertSel = insertSel[findIndex];
  1188. }
  1189. insert = getElement(insertSel, document);
  1190. if (!insert) return false;
  1191. }
  1192. //if (findIndex !== 0) nextIndex = findIndex;
  1193. return true;
  1194. }
  1195.  
  1196. ruleMatch(r) {
  1197. return this.ruleMatchPre(r) && this.ruleMatchReady(r);
  1198. }
  1199.  
  1200. scrollToShow(sel, doc) {
  1201. let exclude = getElement(sel, doc);
  1202. if (exclude) {
  1203. var actualTop = exclude.offsetTop;
  1204. var current = exclude.offsetParent;
  1205. while (current !== null) {
  1206. actualTop += current.offsetTop;
  1207. current = current.offsetParent;
  1208. }
  1209. getBody(doc).scrollTop = 0;
  1210. doc.documentElement.scrollTop = 0;
  1211. let maxHeight = Math.max(getBody(doc).scrollHeight, doc.documentElement.scrollHeight);
  1212. getBody(doc).scrollTop = actualTop - 10;
  1213. doc.documentElement.scrollTop = actualTop - 10;
  1214. setTimeout(() => {
  1215. while (actualTop < maxHeight) {
  1216. actualTop += 200;
  1217. getBody(doc).scrollTop = actualTop;
  1218. doc.documentElement.scrollTop = actualTop;
  1219. }
  1220. }, 0);
  1221. return false;
  1222. }
  1223. return true;
  1224. }
  1225.  
  1226. waitElement(doc, selArr) {
  1227. if (!selArr) selArr = this.curSiteRule.waitElement;
  1228. if (!Array.isArray(selArr)) {
  1229. selArr = [selArr];
  1230. }
  1231. let includeSel = selArr[0].trim(), excludeSel;
  1232. if (selArr.length == 2) {
  1233. excludeSel = selArr[1].trim().replace(/^!/, '');
  1234. } else if (includeSel.indexOf('!') == 0) {
  1235. excludeSel = includeSel.replace(/^!/, '');
  1236. includeSel = '';
  1237. }
  1238. if (includeSel) {
  1239. let include = getElement(includeSel, doc);
  1240. if (!include) {
  1241. return false;
  1242. }
  1243. }
  1244. if (doc === document) return true;
  1245. if (excludeSel) {
  1246. if (!this.scrollToShow(excludeSel, doc)) {
  1247. if (!loadingDiv.offsetParent && this.insert.parentNode) {
  1248. this.insertElement(loadingDiv);
  1249. }
  1250. return false;
  1251. }
  1252. }
  1253. return true;
  1254. }
  1255.  
  1256. getRule(callback) {
  1257. if(noRuleTest) {
  1258. this.curSiteRule = {};
  1259. this.curSiteRule.url = location.origin + location.pathname;
  1260. this.curSiteRule.singleUrl = true;
  1261. callback();
  1262. return;
  1263. }
  1264. var href = location.href.slice(0, 500);
  1265. if (this.curSiteRule && this.curSiteRule.url && !this.curSiteRule.singleUrl) {
  1266. let urlReg = new RegExp(this.curSiteRule.url, "i");
  1267. if (urlReg.test(href) && this.ruleMatch(this.curSiteRule)) {
  1268. return callback();
  1269. }
  1270. }
  1271. if (this.possibleRule) {
  1272. let urlReg = new RegExp(this.possibleRule.url, "i");
  1273. if (urlReg.test(href) && this.ruleMatch(this.possibleRule)) {
  1274. this.curSiteRule = this.possibleRule;
  1275. return callback();
  1276. }
  1277. return;
  1278. }
  1279. this.curSiteRule = {};
  1280. var self = this;
  1281.  
  1282. function setRule(r) {
  1283. if (self.preSiteRule) {
  1284. href = location.href.slice(0, 500);
  1285. let urlReg = new RegExp(self.preSiteRule.url, "i");
  1286. if (urlReg.test(href) && self.ruleMatch(self.preSiteRule)) {
  1287. self.curSiteRule = self.preSiteRule;
  1288. return callback();
  1289. }
  1290. }
  1291. if (!r.singleUrl) {
  1292. self.insert = null;
  1293. self.curSiteRule = r;
  1294. self.preSiteRule = r;
  1295. if (r.enable !== 0) debug(r, 'Match rule');
  1296. } else if (!self.curSiteRule || !self.curSiteRule.singleUrl) self.curSiteRule = r;
  1297. callback();
  1298. }
  1299.  
  1300. function checkRule(r) {
  1301. if (r.from == 1 && r.url.length <= 13) return false;
  1302. let urlReg = new RegExp(r.url, "i");
  1303. if (urlReg.test(href)) {
  1304. if (!self.ruleMatchPre(r)) return false;
  1305. if (r.url.length > 15) {
  1306. self.possibleRule = r;
  1307. }
  1308. if (r.waitElement) {
  1309. let waitTime = 500;
  1310. let checkReady = () => {
  1311. setTimeout(() => {
  1312. if (!self.waitElement(document, r.waitElement) || !self.ruleMatchReady(r)) {
  1313. checkReady();
  1314. } else {
  1315. setRule(r);
  1316. }
  1317. }, parseInt(waitTime));
  1318. };
  1319. checkReady();
  1320. debug(r, 'Wait for rule');
  1321. return true;
  1322. } else if (r.wait) {
  1323. let waitTime = 500, checkEval, maxCheckTimes = 50;
  1324. if (isNaN(r.wait)) {
  1325. try {
  1326. checkEval = (typeof _unsafeWindow.pagetualWait == 'undefined') ? Function("doc",'"use strict";' + r.wait) : _unsafeWindow.pagetualWait;
  1327. } catch(e) {
  1328. debug(e, 'Error when checkeval');
  1329. }
  1330. } else {
  1331. waitTime = r.wait;
  1332. }
  1333. let checkReady = () => {
  1334. if (maxCheckTimes-- <= 0) {
  1335. debug("Wait for rule ready but failed");
  1336. setRule(r);
  1337. return;
  1338. }
  1339. setTimeout(() => {
  1340. if (!self.ruleMatchReady(r) || (checkEval && !checkEval(document))) {
  1341. checkReady();
  1342. } else {
  1343. setRule(r);
  1344. }
  1345. }, parseInt(waitTime));
  1346. };
  1347. checkReady();
  1348. debug(r, 'Wait for rule');
  1349. return true;
  1350. }
  1351. if (r.pinUrl) {
  1352. setRule(r);
  1353. return true;
  1354. }
  1355. if (!self.ruleMatchReady(r)) {
  1356. return false;
  1357. }
  1358. setRule(r);
  1359. return true;
  1360. }
  1361. return false;
  1362. }
  1363.  
  1364. function checkHpRules() {
  1365. for (let i in self.hpRules) {
  1366. let rule = self.hpRules[i];
  1367. if (!rule || !rule.url) continue;
  1368. if (rule.singleUrl) {
  1369. continue;
  1370. }
  1371. if (checkRule(rule)) return true;
  1372. }
  1373. return false;
  1374. }
  1375.  
  1376. function checkCustomRules() {
  1377. for (let i in self.customRules) {
  1378. let rule = self.customRules[i];
  1379. if (!rule || !rule.url) continue;
  1380. if (checkRule(rule)) return true;
  1381. }
  1382. return false;
  1383. }
  1384.  
  1385. if (rulesData.customFirst) {
  1386. if (checkCustomRules()) return;
  1387. if (checkHpRules()) return;
  1388. } else {
  1389. if (checkHpRules()) return;
  1390. if (checkCustomRules()) return;
  1391. }
  1392. for (let i in this.smartRules) {
  1393. let rule = this.smartRules[i];
  1394. if (!rule || !rule.url) continue;
  1395. if (rule.singleUrl) {
  1396. let singleUrl = location.origin + location.pathname;
  1397. if (singleUrl == rule.url) {
  1398. setRule(rule);
  1399. callback = () => {
  1400. if (self.curSiteRule && !self.curSiteRule.singleUrl) {
  1401. self.smartRules = self.smartRules.filter(item => {return item && item.url != singleUrl});
  1402. storage.setItem("smartRules", self.smartRules);
  1403. if (self.curSiteRule.url.length > 13) {
  1404. self.addToHpRules();
  1405. }
  1406. }
  1407. };
  1408. break;
  1409. }
  1410. continue;
  1411. }
  1412. }
  1413. let r = 0;
  1414. function searchByTime() {
  1415. setTimeout(() => {
  1416. let end = r + 20;
  1417. end = end > self.rules.length ? self.rules.length : end;
  1418. for (; r < end; r++) {
  1419. let rule = self.rules[r];
  1420. if (rule.from == 2) {
  1421. delete rule.autoLoadNum;
  1422. delete rule.history;
  1423. delete rule.sideController;
  1424. if (rule.pageBar == 0) delete rule.pageBar;
  1425. }
  1426. if (checkRule(rule)) return;
  1427. }
  1428. if (end >= self.rules.length) {
  1429. setRule({url: location.origin + location.pathname, singleUrl: true});
  1430. return;
  1431. } else {
  1432. searchByTime();
  1433. }
  1434. }, 1);
  1435. }
  1436. searchByTime();
  1437. }
  1438.  
  1439. addToHpRules(instead) {
  1440. try {
  1441. if (!this.hpRules) this.hpRules = [];
  1442. let url = this.curSiteRule && this.curSiteRule.url, self = this;
  1443. let href = location.href.slice(0, 500);
  1444. let matchedRules = this.hpRules.filter(rule => rule != self.curSiteRule && new RegExp(rule.url, "i").test(href) && self.ruleMatch(rule));
  1445. if (url) matchedRules.push(this.curSiteRule);
  1446. matchedRules.sort((a, b) => {
  1447. if ((a.include || a.exclude) && (!b.include && !b.exclude)) {
  1448. return -1;
  1449. } else if ((b.include || b.exclude) && (!a.include && !a.exclude)) {
  1450. return 1;
  1451. } else {
  1452. if ((a.nextLink || a.pageElement) && (!b.nextLink && !b.pageElement)) {
  1453. return -1;
  1454. } else if ((b.nextLink || b.pageElement) && (!a.nextLink && !a.pageElement)) {
  1455. return 1;
  1456. } else {
  1457. if (a.url.length > b.url.length) {
  1458. return -1;
  1459. } else if (a.url.length < b.url.length) {
  1460. return 1;
  1461. } else {
  1462. return 0;
  1463. }
  1464. }
  1465. }
  1466. });
  1467. this.hpRules = this.hpRules.filter(item => {
  1468. return item && !matchedRules.find(rule => item.url == rule.url && JSON.stringify(item) == JSON.stringify(rule));
  1469. });
  1470. if (instead) {
  1471. if (url) this.hpRules.unshift(this.curSiteRule);
  1472. } else {
  1473. this.hpRules = matchedRules.concat(this.hpRules);
  1474. }
  1475. if (matchedRules && matchedRules.length) this.curSiteRule = matchedRules[0];
  1476. if (this.hpRules.length > 30) {
  1477. this.hpRules.pop();
  1478. }
  1479. storage.setItem("hpRules", this.hpRules);
  1480. } catch (e) {
  1481. debug(e);
  1482. }
  1483. }
  1484.  
  1485. replaceElement(doc) {
  1486. if (!doc || doc === document) return;
  1487. let replaceElementSel = this.curSiteRule.replaceElement;
  1488. if (replaceElementSel) {
  1489. if (!Array.isArray(replaceElementSel)) {
  1490. replaceElementSel = [replaceElementSel];
  1491. }
  1492. replaceElementSel.forEach(sel => {
  1493. let pageEles = getAllElements(sel, document);
  1494. let replaceEles = getAllElements(sel, doc);
  1495. for (let i = 0; i < pageEles.length; i++) {
  1496. let replaceEle = replaceEles[i];
  1497. let pageEle = pageEles[i];
  1498. if (replaceEle) {
  1499. pageEle.parentNode.replaceChild(replaceEle.cloneNode(true), pageEle);
  1500. } else break;
  1501. }
  1502. });
  1503. }
  1504. }
  1505.  
  1506. refreshByClick() {
  1507. let refreshByClickSel = this.curSiteRule.refreshByClick;
  1508. if (refreshByClickSel) {
  1509. let self = this;
  1510. document.addEventListener("click", e => {
  1511. if (!self.refreshing) {
  1512. self.refreshing = true;
  1513. setTimeout(() => {
  1514. self.refreshing = false;
  1515. let checkEles = getAllElements(refreshByClickSel, document);
  1516. for (let i = 0; i < checkEles.length; i++) {
  1517. if (checkEles[i] === e.target) {
  1518. urlChanged = true;
  1519. isPause = true;
  1520. if (!ruleParser.nextLinkHref) isLoading = false;
  1521. break;
  1522. }
  1523. }
  1524. }, 300);
  1525. }
  1526. });
  1527. }
  1528. }
  1529.  
  1530. getValidHeight(ele, win) {
  1531. if (!ele.offsetParent) return 0;
  1532. let h = ele.scrollHeight;
  1533. if (win && win.getComputedStyle(ele).overflow == "hidden") {
  1534. h = ele.offsetHeight;
  1535. }
  1536. if (h === 0 && ele.parentNode && ele.parentNode.children.length === 1) {
  1537. h = ele.parentNode.scrollHeight;
  1538. }
  1539. if (h === 0 && ele.children && ele.children.length === 1) {
  1540. h = ele.children[0].scrollHeight;
  1541. }
  1542. const maxNum = 2147483647;
  1543. let moreChild = ele.children[0], minOffsetTop = maxNum;
  1544. while (moreChild) {
  1545. if ((moreChild.offsetParent == ele || moreChild.offsetParent == ele.offsetParent) && moreChild.offsetTop < minOffsetTop) {
  1546. minOffsetTop = moreChild.offsetTop;
  1547. }
  1548. moreChild = moreChild.nextElementSibling;
  1549. }
  1550. if (minOffsetTop != maxNum && minOffsetTop > 0) {
  1551. h -= minOffsetTop;
  1552. }
  1553. return h;
  1554. }
  1555.  
  1556. getPageElement(doc, curWin, dontFind) {
  1557. if (doc == document && this.docPageElement) {
  1558. let parent = this.docPageElement && this.docPageElement[0];
  1559. while (parent && !/^BODY$/i.test(parent.nodeName)) {
  1560. parent = parent.parentNode;
  1561. }
  1562. if (parent && /^BODY$/i.test(parent.nodeName)) {
  1563. return this.docPageElement;
  1564. }
  1565. }
  1566. let pageElement = null;
  1567. let self = this;
  1568. let body = getBody(doc);
  1569. if (this.curSiteRule.pageElement) {
  1570. let pageElementSel = this.curSiteRule.pageElement;
  1571. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  1572. pageElementSel = pageElementSel[nextIndex < pageElementSel.length ? nextIndex : 0];
  1573. }
  1574. pageElement = getAllElements(pageElementSel, doc);
  1575. if (this.curSiteRule.singleUrl && (!pageElement || pageElement.length == 0)) {
  1576. const childSelMatch = />\s*\*$/;
  1577. const targetChild = childSelMatch.test(pageElementSel);
  1578. if (targetChild) pageElementSel = pageElementSel.replace(childSelMatch, "");
  1579. let pageElementSelSplit = pageElementSel.split(">");
  1580. while(pageElementSelSplit && pageElementSelSplit.length > 5) {
  1581. pageElementSelSplit.shift();
  1582. let tempSel = pageElementSelSplit.join(">");
  1583. pageElement = getAllElements(tempSel, doc);
  1584. if (pageElement && pageElement.length == 1) {
  1585. if (targetChild) {
  1586. pageElement = pageElement.children;
  1587. }
  1588. this.curSiteRule.pageElement = tempSel + (targetChild ? ">*" : "");
  1589. break;
  1590. }
  1591. }
  1592. if (!pageElement || pageElement.length == 0) {
  1593. pageElementSel = pageElementSel.replace(/:nth-of-type\(\d+\)/g, "");
  1594. pageElement = getAllElements(pageElementSel, doc);
  1595. if (pageElement && pageElement.length == 1) {
  1596. if (targetChild) {
  1597. pageElement = pageElement.children;
  1598. }
  1599. this.curSiteRule.pageElement = pageElementSel + (targetChild ? ">*" : "");
  1600. }
  1601. }
  1602. }
  1603. if (this.curSiteRule.singleUrl && pageElement && pageElement.length && curWin && curWin != _unsafeWindow) {
  1604. let parent = pageElement[0].parentNode;
  1605. let loading = parent.querySelector('[class*=loading]');
  1606. if (loading && loading.offsetParent && loading.offsetHeight > parent.offsetHeight>>2) {
  1607. pageElement = null;
  1608. }
  1609. }
  1610. }
  1611. if (pageElement && pageElement.length === 1 && pageElement[0].style.display === 'none') {
  1612. pageElement = [body];
  1613. }
  1614. if (this.curSiteRule.singleUrl && pageElement && pageElement.length > 0 && /^TR$/i.test(pageElement[0].nodeName)) {
  1615. let mainTr = this.insert.parentNode.querySelectorAll('tr'), mainTdNum = 0, newTdNum = 0;
  1616. mainTr = mainTr[mainTr.length - 1];
  1617. [].forEach.call(mainTr.children, el => {
  1618. if (/^(TD|TH)$/i.test(el.nodeName)) {
  1619. mainTdNum += el.colSpan || 1;
  1620. }
  1621. });
  1622. [].forEach.call(pageElement[0].children, el => {
  1623. if (/^(TD|TH)$/i.test(el.nodeName)) {
  1624. newTdNum += el.colSpan || 1;
  1625. }
  1626. });
  1627. if (mainTdNum != newTdNum) {
  1628. this.curSiteRule.pageElement = this.curSiteRule.pageElement.replace(/> *table.*/, ">table");
  1629. this.getInsert(true);
  1630. return this.getPageElement(doc, curWin, dontFind);
  1631. }
  1632. }
  1633. if ((this.curSiteRule.singleUrl || !this.curSiteRule.pageElement) && (!pageElement || pageElement.length == 0) && curWin && !dontFind) {
  1634. if (!body) return null;
  1635. let bodyHeight = parseInt(body.offsetHeight || body.scrollHeight);
  1636. let curHeight = bodyHeight, curWidth = 0;
  1637. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  1638. let needCheckNext = (doc == document && this.initNext), nextLeftPos = 0;
  1639. if (needCheckNext && this.initNext.getBoundingClientRect) {
  1640. nextLeftPos = this.initNext.getBoundingClientRect().left;
  1641. }
  1642. function checkElement(ele) {
  1643. if (/^(PRE|CODE)$/i.test(ele.nodeName)) {
  1644. self.curSiteRule.pageElement = geneSelector(ele.parentNode);
  1645. debug(self.curSiteRule.pageElement, 'Page element');
  1646. return [ele.parentNode];
  1647. }
  1648. if (ele.children && ele.children.length == 1) {
  1649. let hasText = false;
  1650. for (let i in ele.childNodes) {
  1651. let child = ele.childNodes[i];
  1652. if (child.nodeType == 3 && child.nodeValue.trim() !== '') {
  1653. hasText = true;
  1654. break;
  1655. }
  1656. }
  1657. if (!hasText) {
  1658. ele = ele.children[0];
  1659. curHeight = self.getValidHeight(ele, curWin);
  1660. curWidth = parseInt(ele.offsetWidth || ele.scrollWidth);
  1661. }
  1662. }
  1663. if (/^PICTURE$/i.test(ele.nodeName) || !ele.innerText || ele.innerText.trim() == '') {
  1664. self.curSiteRule.pageElement = geneSelector(ele.parentNode) + ">" + ele.nodeName.toLowerCase();
  1665. debug(self.curSiteRule.pageElement, 'Page element');
  1666. let eles = [];
  1667. for (let i = 0; i < ele.parentNode.children.length; i++) {
  1668. let curNode = ele.parentNode.children[i];
  1669. if (curNode.nodeName == ele.nodeName && curNode.id == ele.id && curNode.className == ele.className) {
  1670. eles.push(curNode);
  1671. }
  1672. }
  1673. return eles;
  1674. }
  1675. if (curHeight / bodyHeight <= 0.22) {
  1676. let article = doc.querySelectorAll(mainSel);
  1677. if (article && article.length == 1) {
  1678. article = article[0];
  1679. self.curSiteRule.pageElement = article.nodeName.toLowerCase() + (article.id ? "#" + article.id : "") + (article.className ? "." + article.className.replace(/ /g, ".") : "") + ">*";
  1680. debug(self.curSiteRule.pageElement, 'Page element');
  1681. return article.children;
  1682. }
  1683. self.curSiteRule.pageElement = allOfBody;
  1684. debug(self.curSiteRule.pageElement, 'Page element');
  1685. return [body];
  1686. }
  1687. if (/^FORM$/i.test(ele.nodeName) && ele.parentNode != getBody(document)) {
  1688. self.curSiteRule.pageElement = geneSelector(ele) + ">*";
  1689. debug(self.curSiteRule.pageElement, 'Page element');
  1690. return ele.children;
  1691. }
  1692. if (ele.children.length == 0 && !self.curSiteRule.pageElement) {
  1693. if (/^P$/i.test(ele.parentNode.nodeName)) ele = ele.parentNode;
  1694. self.curSiteRule.pageElement = geneSelector(ele.parentNode) + ">" + ele.nodeName.toLowerCase();
  1695. debug(self.curSiteRule.pageElement, 'Page element');
  1696. return getAllElements(self.curSiteRule.pageElement, doc);
  1697. }
  1698. let i, minHeight = curHeight * 0.52, curMaxEle = null, curMaxArea = 0, minWidth = Math.min(curWidth * 0.38, 500);
  1699. let isHori, preOffsetTop = -1;
  1700. let articleNum = 0;
  1701. for (i = 0; i < ele.children.length; i++) {
  1702. let curNode = ele.children[i];
  1703. if (/^(CANVAS|NAV)$/i.test(curNode.nodeName)) continue;
  1704. if (!curNode.offsetParent) continue;
  1705. if (!/^IMG$/i.test(curNode.nodeName) && curNode.querySelector('img') == null && /^\s*$/.test(curNode.innerText)) continue;
  1706. if (needCheckNext && !curNode.contains(self.initNext) && getElementTop(curNode) > windowHeight) {
  1707. continue;
  1708. }
  1709. if (/^ARTICLE$/i.test(curNode.nodeName)) articleNum++;
  1710. let h = self.getValidHeight(curNode, curWin);
  1711. let w = curNode.scrollWidth;
  1712. if (isNaN(h) || isNaN(w)) continue;
  1713. isHori = Math.abs(preOffsetTop - curNode.offsetTop) <= 20 ? true : (preOffsetTop == -1 && curNode.nextElementSibling && curNode.nextElementSibling.offsetTop == curNode.offsetTop);
  1714. if (isHori && h <= 50) continue;
  1715. if (isHori && nextLeftPos && curMaxEle && curWidth > 500 && curHeight > 500) {
  1716. let curRect = curNode.getBoundingClientRect();
  1717. if (curRect.left <= nextLeftPos && curRect.right > nextLeftPos) {
  1718. continue;
  1719. }
  1720. }
  1721. let a = h * w, moreChild = curNode.children[0];
  1722. while (moreChild) {
  1723. let ch = self.getValidHeight(moreChild, curWin);
  1724. let cw = moreChild.scrollWidth;
  1725. if (h < ch) {
  1726. h = ch;
  1727. }
  1728. if (moreChild.innerText != "" && ch && cw) {
  1729. a += ch * cw;
  1730. }
  1731. moreChild = moreChild.nextElementSibling;
  1732. }
  1733. let isMax = false;
  1734. if (isHori) {
  1735. if (curMaxEle) {
  1736. if (curWidth < w) {
  1737. isMax = true;
  1738. } else if (curWidth < w + 300 && curMaxArea < a) {
  1739. isMax = true;
  1740. }
  1741. }
  1742. } else {
  1743. if (curMaxEle && curMaxEle.offsetParent == curNode.offsetParent && curMaxEle.offsetTop == curNode.offsetTop) {
  1744. if (curMaxArea * 2 > a) continue;
  1745. }
  1746. isMax = curMaxArea < a;
  1747. }
  1748. if (curMaxEle == null || isMax) {
  1749. if (isHori) {
  1750. if (w < minWidth) {
  1751. continue;
  1752. }
  1753. }
  1754. if (h < minHeight) {
  1755. if (!needCheckNext || h < (windowHeight>>2) || !ele.contains(self.initNext)) {
  1756. continue;
  1757. }
  1758. }
  1759. curHeight = h;
  1760. curMaxArea = a;
  1761. curWidth = w;
  1762. curMaxEle = curNode;
  1763. preOffsetTop = curNode.offsetTop;
  1764. }
  1765. }
  1766. if (curMaxEle) {
  1767. let sameClassNum = 0, hasDifferent = false;
  1768. if (curMaxEle.className) {
  1769. for(i = 0; i < ele.children.length; i++) {
  1770. let curNode = ele.children[i];
  1771. if (curMaxEle != curNode && curNode.style.display !== 'none' && curMaxEle.className == curNode.className && curMaxEle.nodeName == curNode.nodeName){
  1772. sameClassNum++;
  1773. } else if (curMaxEle.className != curNode.className) {
  1774. hasDifferent = true;
  1775. }
  1776. }
  1777. }
  1778. if (sameClassNum < 2 || (sameClassNum < 5 && hasDifferent)) {
  1779. return checkElement(curMaxEle);
  1780. }
  1781. }
  1782. if (ele.parentNode.children.length == 1 && curWin.getComputedStyle(ele.parentNode).float == 'none') ele = ele.parentNode;
  1783. else if (/^(P|BR|TD)$/i.test(ele.nodeName)) ele = ele.parentNode;
  1784. else if (/^TBODY$/i.test(ele.nodeName)) {
  1785. self.curSiteRule.pageElement = geneSelector(ele) + ">*";
  1786. if (ele.children.length > 0 && ele.children[0].querySelector("th")) {
  1787. self.curSiteRule.pageElement += ":not(:first-child)";
  1788. }
  1789. debug(self.curSiteRule.pageElement, 'Page element');
  1790. return ele.children;
  1791. }
  1792. let imgs = ele.querySelectorAll('img');
  1793. if (imgs.length == 1) {
  1794. let img = imgs[0];
  1795. if (img.offsetWidth > ele.offsetWidth / 3 * 2 && img.offsetHeight > ele.offsetHeight / 2) {
  1796. ele = img;
  1797. }
  1798. }
  1799. self.curSiteRule.pageElement = geneSelector(ele);
  1800. let pf = false;
  1801. if (ele.parentNode) {
  1802. let paStyle = curWin.getComputedStyle(ele.parentNode);
  1803. let paDisplay = paStyle.display;
  1804. let paOverflow = paStyle.overflow;
  1805. pf = paDisplay.indexOf('flex') !== -1 || paDisplay.indexOf('grid') !== -1 || paOverflow == "hidden";
  1806. }
  1807. let curStyle = curWin.getComputedStyle(ele);
  1808. if (ele.children.length > 1) {
  1809. if (articleNum > 1) {
  1810. self.curSiteRule.pageElement += ">article";
  1811. ele = ele.children;
  1812. } else {
  1813. let hasText = false;
  1814. for (let i in ele.childNodes) {
  1815. let child = ele.childNodes[i];
  1816. if (child.nodeType == 3 && child.nodeValue.trim() !== '') {
  1817. hasText = true;
  1818. ele = [ele];
  1819. break;
  1820. }
  1821. }
  1822. if (!hasText) {
  1823. let gridArea = curStyle.gridArea;
  1824. if (gridArea && gridArea != "auto / auto / auto / auto") {
  1825. self.curSiteRule.pageElement += ">*";
  1826. ele = ele.children;
  1827. } else {
  1828. let middleChild = ele.children[parseInt(ele.children.length / 2)];
  1829. if (curStyle.display === 'flex' || (rulesData.opacity != 0 && !pf)) {
  1830. ele = [ele];
  1831. } else if ((middleChild.style && middleChild.style.position === "absolute" && middleChild.style.left && middleChild.style.top) || /^UL$/i.test(ele.nodeName) || curHeight == 0) {
  1832. ele = [ele];
  1833. } else {
  1834. self.curSiteRule.pageElement += ">*";
  1835. ele = ele.children;
  1836. }
  1837. }
  1838. }
  1839. }
  1840. } else if (pf || curStyle.position === "absolute") {
  1841. self.curSiteRule.pageElement += ">*";
  1842. ele = ele.children;
  1843. } else {
  1844. ele = [ele];
  1845. }
  1846. debug(self.curSiteRule.pageElement, 'Page element');
  1847. return ele;
  1848. }
  1849. pageElement = checkElement(body);
  1850. if (pageElement && pageElement.length > 0 && self.initNext) {
  1851. let lastBottom = getElementBottom(pageElement[pageElement.length - 1]);
  1852. if (lastBottom && getElementTop(self.initNext) - lastBottom > 1000) {
  1853. debug("Stop as too long between next & page element");
  1854. isPause = true;
  1855. pageElement = [];
  1856. } else {
  1857. if (pageElement.length == 1 && /^IMG$/i.test(pageElement[0].nodeName)) {
  1858. self.curSiteRule.pageBar = 0;
  1859. }
  1860. }
  1861. }
  1862. //if(pageElement)this.saveCurSiteRule();
  1863. }
  1864.  
  1865. if (doc !== document) {
  1866. this.setPageElementCss(pageElement);
  1867. this.lazyImgAction(pageElement);
  1868. this.filterEles(doc, pageElement);
  1869. } else if (!this.docPageElement) {
  1870. this.setPageElementCss(pageElement, true);
  1871. this.docPageElement = pageElement;
  1872. this.filterEles(doc, pageElement);
  1873. if (this.nextLinkHref) {
  1874. this.openInNewTab(pageElement);
  1875. }
  1876. }
  1877. /*
  1878. if (this.curSiteRule.singleUrl && pageElement && pageElement.length > 0) {
  1879. let targetEle = pageElement.length > 1 ? pageElement[0].parentNode : pageElement[0];
  1880. let video = targetEle.querySelector("video,iframe[id*=play],[id*=play]>iframe,iframe[src*=player],iframe[src*=m3u8]");
  1881. if (video && doc == document) {
  1882. if (video.offsetParent && video.name != 'pagetual-iframe') {
  1883. let scrollWidth = video.scrollWidth || video.offsetWidth;
  1884. let scrollHeight = video.scrollHeight || video.offsetHeight;
  1885. if (/IFRAME/i.test(video.nodeName)) {
  1886. } else if (scrollWidth > 100 && scrollHeight > 100) {
  1887. let winWidth = window.innerWidth || document.documentElement.clientWidth;
  1888. let winHeight = window.innerHeight || document.documentElement.clientHeight;
  1889. if (scrollWidth > winWidth>>1 && scrollHeight > winHeight>>1) {
  1890. debug("Disable when large media found");
  1891. } else {
  1892. video = null;
  1893. }
  1894. } else {
  1895. video = null;
  1896. }
  1897. } else {
  1898. video = null;
  1899. }
  1900. }
  1901. if (video) {
  1902. isPause = true;
  1903. this.clearAddedElements();
  1904. return null;
  1905. }
  1906. }
  1907. */
  1908. return pageElement;
  1909. }
  1910.  
  1911. showAddedElements() {
  1912. if (!this.addedElementsIsHide) return;
  1913. if (this.addedElePool && this.addedElePool.length) {
  1914. this.addedElePool.forEach(ele => {
  1915. ele.classList && ele.classList.remove("pagetual-hide");
  1916. });
  1917. }
  1918. this.addedElementsIsHide = false;
  1919. }
  1920.  
  1921. hideAddedElements() {
  1922. if (this.addedElePool && this.addedElePool.length) {
  1923. this.addedElePool.forEach(ele => {
  1924. ele.classList && ele.classList.add("pagetual-hide");
  1925. });
  1926. }
  1927. this.addedElementsIsHide = true;
  1928. }
  1929.  
  1930. toggleAddedElements() {
  1931. if (this.addedElementsIsHide) {
  1932. this.showAddedElements();
  1933. } else {
  1934. this.hideAddedElements();
  1935. }
  1936. }
  1937.  
  1938. changeVisibility() {
  1939. let contentVisibility = this.curSiteRule.contentVisibility || rulesData.contentVisibility;
  1940. if (!contentVisibility) return;
  1941. if (!this.changingVisibility) {
  1942. clearTimeout(this.changeVisibilityTimer);
  1943. this.changeVisibilityTimer = setTimeout(() => {
  1944. this.changingVisibility = true;
  1945. this.changeVisibility();
  1946. }, 300);
  1947. return;
  1948. }
  1949. this.changingVisibility = false;
  1950. if (!this.visibilityItems || !this.visibilityItems.length || this.visibleIndex < 0) return;
  1951. let tempIndex = this.visibleIndex, findVisible = false, lastVisible = 0;
  1952. let viewPortHeight = window.innerHeight || document.documentElement.clientHeight || getBody(document).clientHeight;
  1953. let checkItem = this.visibilityItems[tempIndex];
  1954. while(checkItem) {
  1955. if (checkItem.offsetParent) {
  1956. if (!checkItem.style.containIntrinsicSize) return;
  1957. let clientRect = checkItem.getBoundingClientRect();
  1958. let top = clientRect && clientRect.top;
  1959. let bottom = clientRect && clientRect.bottom;
  1960. if (bottom > 0 && top < viewPortHeight) {
  1961. if (!findVisible) {
  1962. findVisible = true;
  1963. lastVisible = tempIndex;
  1964. }
  1965. checkItem.style.contentVisibility = "visible";
  1966. } else {
  1967. if (top < viewPortHeight && checkItem.style.contentVisibility == "auto") {
  1968. break;
  1969. } else checkItem.style.contentVisibility = "auto";
  1970. }
  1971. }
  1972. if (tempIndex == 0) break;
  1973. tempIndex--;
  1974. checkItem = this.visibilityItems[tempIndex];
  1975. }
  1976. tempIndex = this.visibleIndex + 1;
  1977. if (findVisible) {
  1978. this.visibleIndex = lastVisible;
  1979. }
  1980. checkItem = this.visibilityItems[tempIndex];
  1981. while(checkItem) {
  1982. if (checkItem.offsetParent) {
  1983. if (!checkItem.style.containIntrinsicSize) return;
  1984. let clientRect = checkItem.getBoundingClientRect();
  1985. let top = clientRect && clientRect.top;
  1986. let bottom = clientRect && clientRect.bottom;
  1987. if (bottom > 0 && top < viewPortHeight) {
  1988. findVisible = true;
  1989. lastVisible = tempIndex;
  1990. checkItem.style.contentVisibility = "visible";
  1991. } else {
  1992. if (findVisible && checkItem.style.contentVisibility == "auto") {
  1993. break;
  1994. } else checkItem.style.contentVisibility = "auto";
  1995. }
  1996. }
  1997. if (tempIndex == this.visibilityItems.length - 1) break;
  1998. tempIndex++;
  1999. checkItem = this.visibilityItems[tempIndex];
  2000. }
  2001. if (findVisible) {
  2002. this.visibleIndex = lastVisible;
  2003. }
  2004. }
  2005.  
  2006. setPageElementCss(pageElement, init) {
  2007. let self = this;
  2008. if (pageElement && pageElement.length > 0) {
  2009. let pageElementCss = this.curSiteRule.pageElementCss || rulesData.pageElementCss;
  2010. if (!pageElementCss && init && !this.nextLinkHref) return;
  2011. let contentVisibility = this.curSiteRule.contentVisibility || rulesData.contentVisibility;
  2012. if (!contentVisibility && !pageElementCss) return;
  2013. [].forEach.call(pageElement, (ele, i) => {
  2014. if (!/LINK|META|STYLE|SCRIPT/i.test(ele.nodeName)) {
  2015. if (pageElementCss) {
  2016. if (pageElementCss !== '0' && !ele.dataset.pagetualPageElement) {
  2017. ele.style.cssText = (ele.style.cssText || '') + pageElementCss;
  2018. ele.dataset.pagetualPageElement = 1;
  2019. }
  2020. }
  2021. if (contentVisibility) {
  2022. ele.style.containIntrinsicSize = `auto ${ele.offsetHeight || self.preVisibleHeight || 100}px`;
  2023. if (ele.style.containIntrinsicSize) {
  2024. if (ele.offsetHeight) self.preVisibleHeight = ele.offsetHeight;
  2025. if (init) {
  2026. ele.style.contentVisibility = "visible";
  2027. self.visibilityItems.push(ele);
  2028. self.visibleIndex++;
  2029. } else {
  2030. ele.style.contentVisibility = emuIframe ? "visible" : "auto";
  2031. }
  2032. }
  2033. }
  2034. }
  2035. });
  2036. }
  2037. }
  2038.  
  2039. clearAddedElements() {
  2040. if (this.addedElePool && this.addedElePool.length) {
  2041. this.addedElePool.forEach(ele => {
  2042. if (ele.parentNode) ele.parentNode.removeChild(ele);
  2043. });
  2044. }
  2045. this.addedElePool = [];
  2046. sideController.remove();
  2047. }
  2048.  
  2049. linkHasNoHref(link) {
  2050. return !link.href || !link.href.replace || this.hrefIsJs(link.href);
  2051. }
  2052.  
  2053. hrefIsJs(href) {
  2054. return /^(javascript|#)/.test(href.replace("#p{", "").replace(location.href, ""))
  2055. }
  2056.  
  2057. async querySelectorList(source, list) {
  2058. for (let i = 0; i < list.length; i++) {
  2059. await sleep(1);
  2060. let sel = list[i];
  2061. let result = source.querySelector(sel);
  2062. if (result) return result;
  2063. }
  2064. return null;
  2065. }
  2066.  
  2067. async getPage(doc, exist) {
  2068. if (document.documentElement.className.indexOf('discourse') != -1) return {};
  2069. let body = getBody(doc);
  2070. let canSave = false;//發現頁碼選擇器在其他頁對不上,還是別保存了
  2071. let url = this.curUrl.slice(0, 250).replace("index.php?", "?");
  2072. let _url = url.replace(/\.s?html?$/i, "").toLowerCase();
  2073. let pageNum = 1, preStr = "", afterStr = "";
  2074. let pageTwoReg = /^[\/\?&]?[_-]?(p|page)?=?\/?2(\/[^\/]*$|\?|&|$)/i;
  2075. let pageMatch1 = url.match(/(.*[\?&]p(?:age)?=)(\d+)($|[#&].*)/i);
  2076. let doubtTextReg = /^\s*(»|>>)\s*$/;
  2077. if (pageMatch1) {
  2078. preStr = pageMatch1[1];
  2079. pageNum = parseInt(pageMatch1[2]);
  2080. afterStr = pageMatch1[3];
  2081. } else {
  2082. let pageMatch2 = url.match(/(.*[a-z\/\-_](?:p|page)?\/?)(\d+)(\.s?html?$|\/?$)/i);
  2083. if (pageMatch2) {
  2084. preStr = pageMatch2[1];
  2085. pageNum = parseInt(pageMatch2[2]);
  2086. afterStr = pageMatch2[3];
  2087. if (/^\/?$/.test(afterStr) && !/(p(age)?|_|\-|\/)$/.test(preStr)) {
  2088. preStr = "";
  2089. afterStr = "";
  2090. }
  2091. }
  2092. }
  2093. if (pageNum > 999) {
  2094. pageNum = 1;
  2095. preStr = "";
  2096. afterStr = "";
  2097. }
  2098. let curPage = doc, i, cur, jsNext;
  2099. let next1, next2, next3, next4, nextJs1, nextJs2, nextJs3;
  2100. let selectorList = [
  2101. ".page-next>a",
  2102. "a.next_page",
  2103. "#next_page",
  2104. ".nextPage",
  2105. ".pagination-next>a",
  2106. "a[data-pagination=next]",
  2107. ".pagination li.active~li>a",
  2108. "[class^=pag] .current+a",
  2109. ".pageButtonsCurrent+a",
  2110. "a[class*=nextpage]",
  2111. "li.page-current+li>a",
  2112. "[class^=pag] a[rel=next]",
  2113. "[class^=Pag] [aria-label=next]",
  2114. "[aria-label='Next page']",
  2115. ".pagination-nav__item--next>a",
  2116. "a.pageright",
  2117. ".page-numbers.current+a",
  2118. ".page_current+a",
  2119. "input[value='next']",
  2120. "input[value='Next page']",
  2121. "input[value='下一页']",
  2122. "input[value='下一頁']",
  2123. "a#pb_next",
  2124. "a#rightFix",
  2125. "a#btnPreGn",
  2126. "a.page-next",
  2127. "a.pages-next",
  2128. "a.page.right",
  2129. "a#next",
  2130. ".next>a",
  2131. ".next>button",
  2132. "a[alt=next]",
  2133. ".pg_area>em+a",
  2134. "button.next:not([disabled])",
  2135. ".btn_next:not([disabled])",
  2136. ".btn-next:not([disabled])",
  2137. "a#linkNext",
  2138. "a[class*=page__next]"
  2139. ];
  2140. let next = await this.querySelectorList(body, selectorList);
  2141. if (!next) {
  2142. await sleep(1);
  2143. let nexts = body.querySelectorAll("a.next");
  2144. for (i = 0; i < nexts.length; i++) {
  2145. if (nexts[i].style.display !== "none" &&
  2146. nexts[i].parentNode.style.display !== "none" &&
  2147. !this.linkHasNoHref(nexts[i]) &&
  2148. !/^\s*([上前首尾]|previous)/i.test(nexts[i].innerText.trim())) {
  2149. next = nexts[i];
  2150. break;
  2151. }
  2152. }
  2153. }
  2154. if (next && this.linkHasNoHref(next)) {
  2155. jsNext = next;
  2156. next = null;
  2157. }
  2158. if (!next) {
  2159. await sleep(1);
  2160. next = body.querySelectorAll("[aria-label='Next page']");
  2161. if (next && next.length == 1) {
  2162. next = next[0];
  2163. if (this.linkHasNoHref(next)) {
  2164. if (!jsNext) jsNext = next;
  2165. next = null;
  2166. }
  2167. } else {
  2168. next = null;
  2169. }
  2170. }
  2171. if (jsNext) {
  2172. if (jsNext.className) {
  2173. if (/slick|slide|gallery/i.test(jsNext.className)) jsNext = null;
  2174. else if (jsNext.classList && jsNext.classList.contains('disabled')) jsNext = null;
  2175. }
  2176. if (jsNext) {
  2177. let ariaLabel = jsNext.getAttribute("aria-label");
  2178. if (ariaLabel && /slick|slide|gallery/i.test(ariaLabel)) jsNext = null;
  2179. }
  2180. }
  2181. if (next && nextTextReg2.test(next.innerText.trim())) {
  2182. next2 = next;
  2183. next = null;
  2184. }
  2185. if (!next) {
  2186. await sleep(1);
  2187. next = body.querySelector("a.curr+a") ||
  2188. body.querySelector("div.wp-pagenavi>span.current+a,div.page-nav>span.current+a,div.article-paging>span+a") ||
  2189. body.querySelector(".number>ul>li.active+li>a");;
  2190. }
  2191. if (!next) {
  2192. await sleep(1);
  2193. let pageDiv = body.querySelector("div.pages>ul");
  2194. if (pageDiv) {
  2195. cur = pageDiv.querySelector("li>b");
  2196. if (cur) next = cur.parentNode.nextElementSibling;
  2197. if (next) next = next.querySelector("a");
  2198. }
  2199. }
  2200. if (!next) {
  2201. await sleep(1);
  2202. next = body.querySelector(".pages>a[href='javascript:;']+a");
  2203. if (next && (next.href == "javascript:;" || next.getAttribute("href") == "#")) next = null;
  2204. }
  2205. if (!next) {
  2206. await sleep(1);
  2207. let pageDiv = body.querySelector(".pagination");
  2208. if (pageDiv) {
  2209. cur = pageDiv.querySelector("[class*=current]");
  2210. if (cur) next = cur.parentNode.nextElementSibling;
  2211. if (next) next = next.querySelector("a");
  2212. }
  2213. }
  2214. if (!next) {
  2215. await sleep(1);
  2216. let pageDivs = body.querySelectorAll("[class*=pagination],[class*=Pagination]");
  2217. if (pageDivs && pageDivs.length) {
  2218. for (let i = 0; i < pageDivs.length; i++) {
  2219. let p = pageDivs[i];
  2220. if (/(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)/i.test(p.title || p.value || '')) {
  2221. next = p;
  2222. break;
  2223. } else if (/^(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)$/i.test((p.innerText || '').trim())) {
  2224. next = p;
  2225. break;
  2226. }
  2227. }
  2228. }
  2229. }
  2230. if (!next) {
  2231. let aTags = body.querySelectorAll("a,button,[type='button']");
  2232. for (i = aTags.length - 1; i >= 0; i--) {
  2233. if (next1) break;
  2234. if (i % 100 == 0) {
  2235. await sleep(1);
  2236. }
  2237. let aTag = aTags[i];
  2238. if (aTag.style.display == "none") continue;
  2239. let innerText = (aTag.innerText || aTag.value || aTag.title || '');
  2240. if (innerText) {
  2241. if (innerText == "§") continue;
  2242. innerText = innerText.trim();
  2243. if (innerText.length > 80) continue;
  2244. }
  2245. let availableHref = aTag.href && aTag.href.length < 250 && /^http/.test(aTag.href);
  2246. if (availableHref && /next\-?(page)?$/i.test(aTag.href)) continue;
  2247. if (aTag.className) {
  2248. if (/slick|slide|gallery/i.test(aTag.className)) continue;
  2249. if (aTag.classList && aTag.classList.contains('disabled')) continue;
  2250. }
  2251. if (aTag.dataset && aTag.dataset.preview) continue;
  2252. let ariaLabel = aTag.getAttribute("aria-label");
  2253. if (ariaLabel && /slick|slide|gallery/i.test(ariaLabel)) continue;
  2254. if (aTag.parentNode) {
  2255. if (aTag.parentNode.className && /slick|slide|gallery/i.test(aTag.parentNode.className)) continue;
  2256. if (aTag.parentNode.parentNode) {
  2257. if (/slick|slide|gallery/i.test(aTag.parentNode.parentNode.className)) continue;
  2258. if (aTag.parentNode.parentNode.parentNode && /slick|slide|gallery/i.test(aTag.parentNode.parentNode.parentNode.className)) continue;
  2259. }
  2260. if (aTag.parentNode.classList && aTag.parentNode.classList.contains('disabled')) continue;
  2261. if (aTag.parentNode.classList && aTag.parentNode.classList.contains('active')) continue;
  2262. if (/^BLOCKQUOTE$/i.test(aTag.parentNode.nodeName)) continue;
  2263. }
  2264. if (aTag.previousElementSibling && /\b(play|volume)\b/.test(aTag.previousElementSibling.className)) continue;
  2265. if (aTag.nextElementSibling && /\b(play|volume)\b/.test(aTag.nextElementSibling.className)) continue;
  2266. let isJs = this.linkHasNoHref(aTag);
  2267. if (exist && isJs && !aTag.offsetParent) continue;
  2268. if (innerText) {
  2269. innerText = innerText.split(/\n/)[0].replace(/ /g, '');
  2270. if (isJs && /^(»|>>|>|›|→|❯)$/.test(innerText)) continue;
  2271. if (innerText && innerText.length <= 25) {
  2272. if (!next1) {
  2273. if (nextTextReg1.test(innerText)) {
  2274. if (isJs) {
  2275. if (!nextJs1) nextJs1 = aTag;
  2276. } else {
  2277. next1 = aTag;
  2278. }
  2279. }
  2280. }
  2281. if (!next4) {
  2282. if (!next2) {
  2283. if (nextTextReg2.test(innerText) || /nextpage|pager\-older/i.test(aTag.className) || /^(»|>>)$/.test(innerText)) {
  2284. if (isJs) {
  2285. if (!nextJs2) nextJs2 = aTag;
  2286. } else {
  2287. next2 = aTag;
  2288. }
  2289. }
  2290. }
  2291. if (!next3) {
  2292. if (/^(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)$/i.test(innerText)) {
  2293. if (isJs) {
  2294. if (!nextJs3) nextJs3 = aTag;
  2295. } else {
  2296. next3 = aTag;
  2297. }
  2298. }
  2299. }
  2300. }
  2301. }
  2302. }
  2303. if (isJs) continue;
  2304. if (!next4) {
  2305. let prevEle = aTag.previousElementSibling;
  2306. if (prevEle && (/^(B|SPAN|STRONG)$/i.test(prevEle.nodeName))) {
  2307. if (/^\d+$/.test(aTag.innerText.trim()) && /^\d+$/.test(prevEle.innerText.trim()) && parseInt(aTag.innerText) == parseInt(prevEle.innerText) + 1) {
  2308. next4 = aTag;
  2309. }
  2310. }
  2311. }
  2312. if (!next4 && availableHref) {
  2313. if (aTag.href.indexOf(location.hostname) === -1) continue;
  2314. let _aHref = aTag.href.replace("?&", "?").replace("index.php?", "?").toLowerCase();
  2315. if (preStr || afterStr) {
  2316. let _aHrefTrim = _aHref;
  2317. if (preStr) _aHrefTrim = _aHrefTrim.replace(preStr, "");
  2318. if (afterStr) _aHrefTrim = _aHrefTrim.replace(afterStr, "");
  2319. if (_aHrefTrim == pageNum + 1) {
  2320. next4 = aTag;
  2321. }
  2322. } else if (this.curUrl != aTag.href) {
  2323. _aHref = _aHref.replace(/\.s?html?$/i, "");
  2324. if (_aHref.indexOf(_url) != -1) {
  2325. let pageTwoMatch = _aHref.replace(_url, "").match(pageTwoReg);
  2326. if (pageTwoMatch) {
  2327. afterStr = pageTwoMatch[2];
  2328. next4 = aTag;
  2329. }
  2330. }
  2331. }
  2332. if (next4 && !/page/.test(next4.href)) {
  2333. let curHref = next4.getAttribute("href");
  2334. let curPageReg = new RegExp("(.*)" + (pageNum + 1) + afterStr.replace(/([\.\?])/g, '\\$1'));
  2335. let otherPageHref = curHref.replace(curPageReg, `$1${pageNum}${afterStr}`);
  2336. let otherPageEle = body.querySelector(`a[href='${otherPageHref}']`);
  2337. if (!otherPageEle) {
  2338. otherPageHref = curHref.replace(curPageReg, `$1${pageNum + 2}${afterStr}`);
  2339. otherPageEle = body.querySelector(`a[href='${otherPageHref}']`);
  2340. }
  2341. if (otherPageEle) {
  2342. let parent = otherPageEle.parentNode;
  2343. if (parent && parent.parentNode) {
  2344. parent = parent.parentNode;
  2345. if (parent.parentNode) {
  2346. parent = parent.parentNode;
  2347. }
  2348. }
  2349. if (parent && parent.contains(otherPageEle) && !/^\d+$/.test(otherPageEle.innerText.trim())) {
  2350. next4 = null;
  2351. }
  2352. }
  2353. }
  2354. }
  2355. }
  2356. if (next2 && doubtTextReg.test(next2.innerText)) {
  2357. next2 = this.verifyNext(next2, doc);
  2358. }
  2359. if (nextJs2 && doubtTextReg.test(nextJs2.innerText)) {
  2360. nextJs2 = this.verifyNext(nextJs2, doc);
  2361. }
  2362. if (next3) {
  2363. next3 = this.verifyNext(next3, doc);
  2364. }
  2365. if (nextJs3) {
  2366. nextJs3 = this.verifyNext(nextJs3, doc);
  2367. }
  2368. }
  2369. if (!next) next = next1 || next4 || next3 || next2;
  2370. if (!next) {
  2371. next = jsNext || nextJs1 || nextJs3 || nextJs2;
  2372. if (next && next.parentNode.className.indexOf('tab') != -1) next = null;
  2373. }
  2374. if (next && next.classList && (next.classList.contains("results-more") || next.classList.contains("no"))) next = null;
  2375. if (next && next.hasAttribute && next.hasAttribute("disabled")) next = null;
  2376. return {next:next, canSave:canSave};
  2377. }
  2378.  
  2379. verifyNext(next, doc) {
  2380. if (!next) return null;
  2381. if (next.previousElementSibling && /^BR$/i.test(next.previousElementSibling.nodeName)) return null;
  2382. let eles = getAllElements(`//${next.nodeName}[text()='${next.innerText}']`, doc);
  2383. if (eles.length >= 2 && eles[0].href != eles[1].href) {
  2384. next = null;
  2385. } else if (doc == document) {
  2386. let left = getElementLeft(next);
  2387. if (left < 20 || (document.documentElement.scrollWidth > 500 && left < 250)) {
  2388. next = null;
  2389. } else {
  2390. let top = getElementTop(next);
  2391. if (top < 20) {
  2392. next = null;
  2393. } else {
  2394. let bottom = top + next.offsetHeight || 0;
  2395. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  2396. if (scrollH - bottom < 10) next = null;
  2397. }
  2398. }
  2399. }
  2400. return next;
  2401. }
  2402.  
  2403. canonicalUri(src) {
  2404. if (!src) {
  2405. return "";
  2406. }
  2407. if (src.charAt(0) == "#") return this.curUrl + src;
  2408. if (src.charAt(0) == "?") return this.curUrl.replace(/^([^\?#]+).*/, "$1" + src);
  2409. let origin = location.protocol + '//' + location.host;
  2410. let url = this.basePath || origin;
  2411. url = url.replace(/(\?|#).*/, "");
  2412. if (/https?:\/\/[^\/]+$/.test(url)) url = url + '/';
  2413. if (url.indexOf("http") !== 0) url = origin + url;
  2414. var root_page = /^[^\?#]*\//.exec(url)[0],
  2415. root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  2416. absolute_regex = /^\w+\:\/\//;
  2417. this.updateUrl = false;
  2418. while (src.indexOf("../") === 0) {
  2419. src = src.substr(3);
  2420. root_page = root_page.replace(/\/[^\/]+\/$/, "/");
  2421. this.updateUrl = true;
  2422. }
  2423. src = src.replace(/\.\//, "");
  2424. if (/^\/\/\/?/.test(src)) {
  2425. src = location.protocol + src;
  2426. }
  2427. return (absolute_regex.test(src) ? src : ((src.charAt(0) == "/" ? root_domain : root_page) + src));
  2428. }
  2429.  
  2430. getLinkByPage(url, pageNum) {
  2431. if (!url) return null;
  2432. if (this.curSiteRule.pageNum) {
  2433. let result = this.curSiteRule.pageNum;
  2434. let strMatch = result.match(/\{.*?}/);
  2435. if (!strMatch) return null;
  2436. let urlReg = new RegExp("(" + result.replace(strMatch[0], ")\\d+(") + ")", "i");
  2437. let code = strMatch[0].replace(/^{/, "").replace(/}$/, "").replace(/\$p/g, pageNum);
  2438. if (code == pageNum) {
  2439. result = url.replace(urlReg, "$1" + code + "$2");
  2440. } else {
  2441. try {
  2442. code = Function('"use strict";return ' + code)();
  2443. if (code && code % 1 == 0) {
  2444. result = url.replace(urlReg, "$1" + code + "$2");
  2445. } else return null;
  2446. } catch(e) {
  2447. debug(e);
  2448. }
  2449. }
  2450. if (result != url) {
  2451. return result;
  2452. }
  2453. }
  2454. return url.replace(/([&\/\?](p=|page[=\/_-]?))\d+/i, "$1" + pageNum).replace(/([_-])\d+\./i, "$1" + pageNum + ".");
  2455. }
  2456.  
  2457. getPageNumFromUrl(url, defaultPage) {
  2458. if (!url) return defaultPage;
  2459. if (this.curSiteRule.pageNum) {
  2460. let result = this.curSiteRule.pageNum;
  2461. let strMatch = result.match(/\{.*?}/);
  2462. if (!strMatch) return defaultPage;
  2463. let urlReg = new RegExp(".*" + result.replace(strMatch[0], "(\\d+)") + ".*", "i");
  2464. let curShowNum = url.replace(urlReg, "$1");
  2465. if (curShowNum != url) {
  2466. let code = strMatch[0].replace(/^{/, "").replace(/}$/, "");
  2467. if (code == "$p") {
  2468. return curShowNum;
  2469. } else {
  2470. try {
  2471. let page1 = parseInt(Function('"use strict";return ' + code.replace("$p", "0"))());
  2472. let page2 = parseInt(Function('"use strict";return ' + code.replace("$p", "1"))());
  2473. let numGap = page2 - page1;
  2474. let _page = (parseInt(curShowNum) - page1) / numGap;
  2475. if (_page && _page % 1 == 0) return _page;
  2476. else {
  2477. this.curSiteRule.pageNum = null;
  2478. return defaultPage;
  2479. }
  2480. } catch(e) {
  2481. debug(e);
  2482. }
  2483. }
  2484. } else {
  2485. return defaultPage;
  2486. }
  2487. }
  2488. let pageNum = url.replace(/.*[&\/\?](p=|page[=\/_-]?)(\d+).*/i, "$2");
  2489. return pageNum == url ? defaultPage : (pageNum.length > 4 ? defaultPage : pageNum);
  2490. }
  2491.  
  2492. async getNextLink(doc, exist) {
  2493. let nextLink = null, page, href;
  2494. let getNextLinkByForm = (form, submitBtn, n) => {
  2495. let params = [];
  2496. let formData = new FormData(form);
  2497. if (submitBtn && submitBtn.getAttribute) {
  2498. let btnValue, btnName;
  2499. btnName = submitBtn.getAttribute("name");
  2500. btnValue = submitBtn.getAttribute("value");
  2501. if (btnName && btnValue) params = [btnName + "=" + encodeURIComponent(btnValue)];
  2502. }
  2503. for (let [key, value] of formData) {
  2504. if (n && /^(p|page)$/i.test(key)) {
  2505. params.push(key + '=' + n);
  2506. } else {
  2507. params.push(key + '=' + encodeURIComponent(value));
  2508. }
  2509. }
  2510. params = params.join('&');
  2511. return form.action + (form.action.indexOf('?') == -1 ? '?' : '&') + params + (form.method == 'post' ? '#p{' + params + '}' : '');
  2512. };
  2513. if (this.curSiteRule.pageElementByJs) {
  2514. this.nextLinkHref = "#";
  2515. return true;
  2516. } else if (this.curSiteRule.nextLinkByJs) {
  2517. try {
  2518. let over = _url => {
  2519. };
  2520. let targetUrl = await ((typeof _unsafeWindow.pagetualNextLinkByJs == 'undefined') ? new AsyncFunction("doc", '"use strict";' + this.curSiteRule.nextLinkByJs) : _unsafeWindow.pagetualNextLinkByJs)(doc);
  2521. if (targetUrl) nextLink = {href: targetUrl};
  2522. } catch(e) {
  2523. debug(e);
  2524. }
  2525. } else if (this.curSiteRule.nextLinkByUrl) {
  2526. let targetUrl = this.curUrl.replace(new RegExp(this.curSiteRule.nextLinkByUrl[0], "i"), this.curSiteRule.nextLinkByUrl[1]);
  2527. if (targetUrl != this.curUrl) {
  2528. let includeSel = this.curSiteRule.nextLinkByUrl[2];
  2529. let excludeSel = this.curSiteRule.nextLinkByUrl[3];
  2530. if (includeSel) {
  2531. includeSel = includeSel.trim();
  2532. if (!getElement(includeSel, doc)) {
  2533. this.nextLinkHref=false;
  2534. return null;
  2535. }
  2536. }
  2537. if (excludeSel) {
  2538. excludeSel = excludeSel.trim();
  2539. if (getElement(excludeSel, doc)) {
  2540. this.nextLinkHref=false;
  2541. return null;
  2542. }
  2543. }
  2544. let reps = targetUrl.match(/{.*?}/g);
  2545. if (reps) {
  2546. reps.forEach(rep => {
  2547. let code = rep.replace("{", "").replace("}", "").replace(/\(\)/g, "0");
  2548. let result = code.match(/^(\d*)\+1$/);
  2549. if (result) {
  2550. result = parseInt(result[1] || 1) + 1;
  2551. } else {
  2552. try {
  2553. result = Function('"use strict";return ' + code)();
  2554. } catch(e) {
  2555. debug(e);
  2556. }
  2557. }
  2558. targetUrl = targetUrl.replace(rep, result);
  2559. });
  2560. }
  2561. }
  2562. nextLink = {href: targetUrl};
  2563. } else if (typeof this.curSiteRule.nextLink != 'undefined') {
  2564. let nextLinkSel = this.curSiteRule.nextLink;
  2565. if (nextLinkSel != 0) {
  2566. if (Array && Array.isArray && Array.isArray(nextLinkSel)) {
  2567. nextLink = getElement(nextLinkSel[nextIndex], doc, null, true);
  2568. if (!nextLink && curPage == 1 && nextIndex != 0) {
  2569. nextIndex = 0;
  2570. nextLink = getElement(nextLinkSel[nextIndex], doc, null, true);
  2571. }
  2572. } else nextLink = getElement(nextLinkSel, doc, null, true);
  2573. }
  2574. if (nextLink && (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2)) {
  2575. let form = doc.querySelector('#search-form');
  2576. if (!nextLink.href && nextLink.hasAttribute && nextLink.hasAttribute("onclick") && form) {
  2577. if (/^\d+$/.test(nextLink.innerText)) {
  2578. nextLink.href = getNextLinkByForm(form, nextLink, nextLink.innerText);
  2579. }
  2580. } else if (/^INPUT$/i.test(nextLink.nodeName) || nextLink.type == "submit") {
  2581. form = nextLink.parentNode;
  2582. while (form) {
  2583. if (/^FORM$/i.test(form.nodeName)) break;
  2584. else form = form.parentNode;
  2585. }
  2586. if (form) {
  2587. nextLink.href = getNextLinkByForm(form, nextLink);
  2588. }
  2589. }
  2590. if (nextLink.href && this.curSiteRule.action != 0) {
  2591. nextLink.href = nextLink.href.replace(/#p{.*/, "");
  2592. }
  2593. }
  2594. } else {
  2595. page = await this.getPage(doc, exist);
  2596. nextLink = page.next;
  2597. if (nextLink) {
  2598. if (/^INPUT$/i.test(nextLink.nodeName) || nextLink.type == "submit") {
  2599. if (!/next/i.test(nextLink.getAttribute("onclick"))) {
  2600. let form = nextLink.parentNode;
  2601. while (form) {
  2602. if (/^FORM$/i.test(form.nodeName)) break;
  2603. else form = form.parentNode;
  2604. }
  2605. if (form) {
  2606. nextLink.href = getNextLinkByForm(form, nextLink);
  2607. }
  2608. }
  2609. }
  2610. let parent = nextLink;
  2611. while (parent && !/^BODY$/i.test(parent.nodeName)) {
  2612. if (parent.hasAttribute && parent.hasAttribute("disabled")) {
  2613. this.nextLinkHref = false;
  2614. return null;
  2615. }
  2616. if (parent.className && parent.classList) {
  2617. if (parent.classList.contains("noClick") || parent.classList.contains("no-pages") || parent.classList.contains("disabled")) {
  2618. this.nextLinkHref = false;
  2619. return null;
  2620. }
  2621. }
  2622. if (parent.style && parent.style.display === "none") {
  2623. this.nextLinkHref = false;
  2624. return null;
  2625. }
  2626. parent = parent.parentNode;
  2627. }
  2628. if (doc == document) {
  2629. if (this.linkHasNoHref(nextLink) && !isVisible(nextLink, _unsafeWindow)) {
  2630. this.nextLinkHref = false;
  2631. return null;
  2632. } else {
  2633. let nextLinkCs = _unsafeWindow.getComputedStyle(nextLink);
  2634. if (nextLinkCs.cursor == "not-allowed") {
  2635. this.nextLinkHref = false;
  2636. return null;
  2637. }
  2638. this.initNext = nextLink;
  2639. }
  2640. }
  2641. let form = doc.querySelector('#search-form');
  2642. if (!nextLink.href && nextLink.hasAttribute("onclick") && form) {
  2643. if (form && /^\d+$/.test(nextLink.innerText)) {
  2644. href = getNextLinkByForm(form, nextLink, nextLink.innerText);
  2645. }
  2646. }
  2647. }
  2648. }
  2649. if (nextLink) {
  2650. if (!this.checkStopSign(nextLink, doc)) {
  2651. if (curPage > 1 && rulesData.lastPageTips) showTips(i18n("lastPage"));
  2652. return null;
  2653. }
  2654. if (this.curSiteRule.action == 3) {
  2655. if (doc == document) debug(nextLink, 'Next link');
  2656. this.nextLinkHref = '#';
  2657. } else {
  2658. let needUrl = (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2);
  2659. if (!href) href = nextLink.href;
  2660. if (href && nextLink.getAttribute) {
  2661. let _href = nextLink.getAttribute("href");
  2662. if (_href) {
  2663. if (_href.charAt(0) == "#" || _href == "?"){
  2664. href = "#";
  2665. } else {
  2666. href = _href;
  2667. }
  2668. } else if (_href === "") {
  2669. href = _href;
  2670. }
  2671. }
  2672.  
  2673. if (needUrl && (href === "" || href === null)) {
  2674. this.nextLinkHref = false;
  2675. } else if (needUrl && /^(javascript:|#)/.test(href)) {
  2676. this.nextLinkHref = false;
  2677. } else {
  2678. this.nextLinkHref = (href && !/^(javascript:|#)/.test(href)) ? this.canonicalUri(href) : "#";
  2679. let tempUrl = this.nextLinkHref;
  2680. 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 + "#"))) {
  2681. this.nextLinkHref = false;
  2682. } else if (doc == document) {
  2683. debug(nextLink, 'Next link');
  2684. }
  2685. }
  2686. }
  2687. } else {
  2688. this.nextLinkHref = false;
  2689. }
  2690. this.nextLinkEle = nextLink;
  2691. this.preload();
  2692. return nextLink;
  2693. }
  2694.  
  2695. compareUrl(url1, url2) {
  2696. if (url1 == url2) return true;
  2697. if (!url1 || !url2) return false;
  2698. let url1Arr = url1.split("?");
  2699. let url2Arr = url2.split("?");
  2700. if (url1Arr[0] != url2Arr[0]) return false;
  2701. if (!url1Arr[1] || !url2Arr[1]) return false;
  2702. url1Arr = url1Arr[1].split("&").sort().join("&");
  2703. url2Arr = url2Arr[1].split("&").sort().join("&");
  2704. return url1Arr == url2Arr;
  2705. }
  2706.  
  2707. filterEles(doc, eles) {
  2708. let filter = this.curSiteRule.filter;
  2709. if (!filter || !eles || eles.length === 0) return;
  2710. if (eles.length === 1) {
  2711. eles = eles[0].children;
  2712. if (eles.length === 1) {
  2713. eles = eles[0].children;
  2714. }
  2715. }
  2716. if (typeof filter == "string") {
  2717. if (/^\d+$/.test(filter)) {
  2718. filter = {count: parseInt(filter)};
  2719. } else filter = {words: filter};
  2720. }
  2721. [].forEach.call(eles, ele => {
  2722. if (!ele.parentNode) return;
  2723. let canKeep = (() => {
  2724. let innerText = (ele.innerText && ele.innerText.trim()) || "";
  2725. if (filter.count) {
  2726. if (innerText.length < filter.count) return false;
  2727. }
  2728. if (filter.words) {
  2729. let wordsRegExp = new RegExp(filter.words, "i");
  2730. if (innerText && wordsRegExp.test(innerText)) return false;
  2731. }
  2732. if (filter.link) {
  2733. let linkRegExp = new RegExp(filter.link, "i");
  2734. if (/^A$/i.test(ele.nodeName) && linkRegExp.test(ele.href)) return false;
  2735. let aChildren = ele.querySelectorAll("a");
  2736. for (let i = 0; i < aChildren.length; i++) {
  2737. let child = aChildren[i];
  2738. if (linkRegExp.test(child.href)) return false;
  2739. }
  2740. }
  2741. if (filter.selector) {
  2742. if (getElement(filter.selector, doc, ele)) return false;
  2743. }
  2744. return true;
  2745. })();
  2746. if (!canKeep) {
  2747. ele.parentNode.removeChild(ele);
  2748. }
  2749. });
  2750. }
  2751.  
  2752. checkStopSign(nextLink, doc) {
  2753. if (this.curSiteRule.stopSign) {
  2754. let typeArray = Array && Array.isArray && Array.isArray(this.curSiteRule.stopSign);
  2755. let typeObject = !typeArray && (this.curSiteRule.stopSign.include || this.curSiteRule.stopSign.exclude || this.curSiteRule.stopSign.pageNum);
  2756. if (typeArray || typeObject) {
  2757. let includeSel, excludeSel, curSign, maxSign;
  2758. if (typeArray) {
  2759. includeSel = this.curSiteRule.stopSign[0];
  2760. excludeSel = this.curSiteRule.stopSign[1];
  2761. curSign = this.curSiteRule.stopSign[2];
  2762. maxSign = this.curSiteRule.stopSign[3];
  2763. if (Array && Array.isArray && Array.isArray(includeSel) && !curSign) {
  2764. curSign = includeSel;
  2765. includeSel = false;
  2766. }
  2767. if (excludeSel && Array && Array.isArray && Array.isArray(excludeSel) && !maxSign) {
  2768. maxSign = excludeSel;
  2769. excludeSel = false;
  2770. }
  2771. } else {
  2772. includeSel = this.curSiteRule.stopSign.include;
  2773. excludeSel = this.curSiteRule.stopSign.exclude;
  2774. curSign = this.curSiteRule.stopSign.pageNum;
  2775. }
  2776. if (includeSel) {
  2777. includeSel = includeSel.trim();
  2778. if (!getElement(includeSel, doc)) {
  2779. isPause = true;
  2780. this.nextLinkHref = false;
  2781. return false;
  2782. }
  2783. }
  2784. if (excludeSel) {
  2785. excludeSel = excludeSel.trim();
  2786. if (getElement(excludeSel, doc)) {
  2787. isPause = true;
  2788. this.nextLinkHref = false;
  2789. return false;
  2790. }
  2791. }
  2792. if (curSign) {
  2793. if (!maxSign) maxSign = curSign.slice(2);
  2794. let currentEle = getElement(curSign[0], doc);
  2795. let maxEle = getElement(maxSign[0], doc);
  2796. if (currentEle && maxEle) {
  2797. let currentSignNum, maxSignNum;
  2798. if (/\(.*\)/.test(curSign[1])) {
  2799. currentSignNum = currentEle.innerText.match(new RegExp(curSign[1]));
  2800. if (currentSignNum) currentSignNum = currentSignNum[1];
  2801. } else if (currentEle.getAttribute) {
  2802. currentSignNum = currentEle.getAttribute(curSign[1]);
  2803. }
  2804. if (/\(.*\)/.test(maxSign[1])) {
  2805. maxSignNum = maxEle.innerText.match(new RegExp(maxSign[1]));
  2806. if (maxSignNum) maxSignNum = maxSignNum[1];
  2807. } else if (maxEle.getAttribute) {
  2808. maxSignNum = maxEle.getAttribute(maxSign[1]);
  2809. }
  2810. if (currentSignNum && maxSignNum && currentSignNum == maxSignNum) {
  2811. isPause = true;
  2812. this.nextLinkHref = false;
  2813. return false;
  2814. }
  2815. }
  2816. }
  2817. } else {
  2818. try {
  2819. let stopSign = ((typeof _unsafeWindow.stopSign == 'undefined') ? Function("doc", "nextLink", '"use strict";' + this.curSiteRule.stopSign) : _unsafeWindow.stopSign)(doc, nextLink);
  2820. if (stopSign) {
  2821. isPause = true;
  2822. this.nextLinkHref = false;
  2823. return false;
  2824. }
  2825. } catch(e) {
  2826. debug(e);
  2827. }
  2828. }
  2829. }
  2830. return true;
  2831. }
  2832.  
  2833. preload() {
  2834. if (!rulesData.preload) return;
  2835. if (!this.nextLinkHref || this.nextLinkHref == "#") return;
  2836. let self = this, url = this.nextLinkHref;
  2837. let postParams = url.match(/#p{(.*)}$/);
  2838. if (postParams) {
  2839. postParams = postParams[1];
  2840. url = url.replace(/#p{.*/, "");
  2841. }
  2842. _GM_xmlhttpRequest({
  2843. url: url,
  2844. method: postParams ? 'POST' : 'GET',
  2845. data: postParams,
  2846. overrideMimeType: 'text/html;charset=' + (document.characterSet || document.charset || document.inputEncoding),
  2847. headers: {
  2848. 'Referer': location.href,
  2849. 'User-Agent': navigator.userAgent,
  2850. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + (document.characterSet || document.charset || document.inputEncoding),
  2851. },
  2852. timeout: 10000,
  2853. onload: function(res) {
  2854. var doc = null;
  2855. try {
  2856. doc = document.implementation.createHTMLDocument('');
  2857. doc.documentElement.innerHTML = res.response;
  2858. var body = getBody(doc);
  2859. if (body && body.firstChild) {
  2860. self.lazyImgAction(body.children);
  2861. }
  2862. if (!self.preloadDiv) {
  2863. self.preloadDiv = document.createElement('div');
  2864. self.preloadDiv.id = "pagetual-preload";
  2865. self.preloadDiv.style.cssText = 'display:none!important;';
  2866. getBody(document).appendChild(self.preloadDiv);
  2867. self.checkedImgs = {};
  2868. }
  2869. [].forEach.call(doc.images, i => {
  2870. let iSrc = i.src;
  2871. if (iSrc && !self.checkedImgs[iSrc]) {
  2872. self.checkedImgs[iSrc] = true;
  2873. let img = document.createElement('img');
  2874. img.src = iSrc;
  2875. self.preloadDiv.appendChild(img);
  2876. }
  2877. });
  2878. let code = self.curSiteRule.preloadImages;
  2879. if (code) {
  2880. let imgSrcArr = new Function("doc", '"use strict";' + code)(doc);
  2881. if (imgSrcArr && imgSrcArr.length) {
  2882. imgSrcArr.forEach(imgSrc => {
  2883. if (imgSrc && !self.checkedImgs[imgSrc]) {
  2884. self.checkedImgs[imgSrc] = true;
  2885. let img = document.createElement('img');
  2886. img.src = imgSrc;
  2887. self.preloadDiv.appendChild(img);
  2888. }
  2889. });
  2890. }
  2891. }
  2892. }
  2893. catch(e) {
  2894. debug(e);
  2895. return;
  2896. }
  2897. }
  2898. });
  2899. }
  2900.  
  2901. getInsert(refresh) {
  2902. if (refresh) {
  2903. this.insert = null;
  2904. }
  2905. if (this.insert && document.documentElement.contains(this.insert)) {
  2906. return this.insert;
  2907. }
  2908. if (this.curSiteRule.insert) {
  2909. let insertSel = this.curSiteRule.insert;
  2910. if (Array && Array.isArray && Array.isArray(insertSel)) {
  2911. insertSel = insertSel[nextIndex < insertSel.length ? nextIndex : 0];
  2912. }
  2913. this.insert = getElement(insertSel, document, null, true);
  2914. } else {
  2915. this.docPageElement = null;
  2916. let pageElement = this.getPageElement(document, _unsafeWindow);
  2917. if (this.curSiteRule.singleUrl && this.nextLinkHref == "#" && this.curSiteRule.pageElement === 'body') {
  2918. debug("Stop as jsNext & whole body");
  2919. isPause = true;
  2920. return null;
  2921. }
  2922. if (pageElement && pageElement.length > 0) {
  2923. var pELast = pageElement[pageElement.length - 1];
  2924. this.insert = pELast.nextSibling ? pELast.nextSibling : pELast.parentNode.appendChild(document.createTextNode(' '));
  2925. }
  2926. }
  2927. return this.insert;
  2928. }
  2929.  
  2930. pageInit(doc, eles) {
  2931. let code = this.curSiteRule.pageInit;
  2932. if (code) {
  2933. let initFunc = ((typeof _unsafeWindow.pagetualPageInit == 'undefined') ? Function("doc", "eles", '"use strict";' + code) : _unsafeWindow.pagetualPageInit);
  2934. let checkInit = (resolve) => {
  2935. try {
  2936. if (initFunc(doc, eles) === false) {
  2937. setTimeout(() => {
  2938. checkInit(resolve);
  2939. }, 100);
  2940. } else {
  2941. resolve(true);
  2942. }
  2943. } catch(e) {
  2944. resolve(false);
  2945. debug(e);
  2946. }
  2947. };
  2948. return new Promise((resolve) => {
  2949. checkInit(function(e) {
  2950. resolve(e)
  2951. });
  2952. })
  2953. }
  2954. }
  2955.  
  2956. pageAction(doc, eles) {
  2957. let code = this.curSiteRule.pageAction;
  2958. if (code) {
  2959. try {
  2960. ((typeof _unsafeWindow.pagetualPageAction == 'undefined') ? Function("doc", "eles", '"use strict";' + code) : _unsafeWindow.pagetualPageAction)(doc, eles);
  2961. } catch(e) {
  2962. debug(e);
  2963. }
  2964. }
  2965. this.openInNewTab(eles);
  2966. this.replaceElement(doc);
  2967. }
  2968.  
  2969. openInNewTab(eles) {
  2970. if (openInNewTab) {
  2971. [].forEach.call(eles, ele => {
  2972. if (/^A$/i.test(ele.nodeName) && ele.href && !/^(mailto:|javascript:)|#/.test(ele.href)) {
  2973. ele.setAttribute('target', openInNewTab == 1 ? '_blank' : '_self');
  2974. } else {
  2975. [].forEach.call(ele.querySelectorAll('a[href]:not([href^="mailto:"]):not([href^="javascript:"]):not([href^="#"])'), a => {
  2976. if (openInNewTab == 1) {
  2977. a.setAttribute('target', '_blank');
  2978. if (a.getAttribute('onclick') == 'atarget(this)') {
  2979. a.removeAttribute('onclick');
  2980. }
  2981. } else a.setAttribute('target', '_self');
  2982. });
  2983. }
  2984. });
  2985. }
  2986. }
  2987.  
  2988. lazyImgAction(eles) {
  2989. if (!eles || eles.length == 0) return;
  2990. let lazyImgSrc = this.curSiteRule.lazyImgSrc;
  2991. if (lazyImgSrc === 0 || lazyImgSrc === '0') return;
  2992. let setLazyImg = img => {
  2993. let realSrc;
  2994. if (lazyImgSrc) {
  2995. if (!Array.isArray(lazyImgSrc)) {
  2996. lazyImgSrc = [lazyImgSrc];
  2997. }
  2998. realSrc = img.getAttribute(lazyImgSrc[0]);
  2999. if (lazyImgSrc.length == 2) {
  3000. let removeProps = lazyImgSrc[1].split(",");
  3001. removeProps.forEach(prop => {
  3002. img.removeAttribute(prop.trim());
  3003. });
  3004. }
  3005. if (realSrc) img.src = realSrc;
  3006. }
  3007. if (!realSrc) {
  3008. let lazyAttr = "";
  3009. if (img.getAttribute("_src") && !img.src) {
  3010. lazyAttr = "_src";
  3011. realSrc = img.getAttribute(lazyAttr);
  3012. } else {
  3013. for (let i in lazyImgAttr) {
  3014. lazyAttr = lazyImgAttr[i];
  3015. let attrValue = img.getAttribute(lazyAttr);
  3016. if (attrValue) {
  3017. realSrc = attrValue;
  3018. break;
  3019. }
  3020. }
  3021. }
  3022. if (!realSrc && img._lazyrias && img._lazyrias.srcset) {
  3023. realSrc = img._lazyrias.srcset[img._lazyrias.srcset.length - 1];
  3024. lazyAttr = "_lazyrias";
  3025. }
  3026. if (!realSrc && img.srcset) {
  3027. lazyAttr = "srcset";
  3028. var srcs = img.srcset.split(/[xw],/i), largeSize = 0;
  3029. srcs.forEach(srci => {
  3030. let srcInfo = srci.trim().split(" "), curSize = parseInt(srcInfo[1]);
  3031. if (srcInfo[1] && curSize > largeSize) {
  3032. largeSize = curSize;
  3033. realSrc = srcInfo[0];
  3034. }
  3035. });
  3036. }
  3037. if (realSrc) {
  3038. img.src = realSrc;
  3039. img.removeAttribute("srcset");
  3040. img.removeAttribute(lazyAttr);
  3041. if (img.style.display == "none") {
  3042. img.style.display = "";
  3043. }
  3044. if (img.style.visibility == "hidden") {
  3045. img.style.visibility = "";
  3046. }
  3047. if (img.style.opacity == 0) {
  3048. img.style.opacity = "";
  3049. }
  3050. }
  3051. }
  3052. };
  3053. [].forEach.call(eles, ele => {
  3054. if (/^IMG$/i.test(ele.nodeName)) {
  3055. setLazyImg(ele);
  3056. } else {
  3057. [].forEach.call(ele.querySelectorAll("img,picture>source"), img => {
  3058. setLazyImg(img);
  3059. });
  3060. [].forEach.call(ele.querySelectorAll("div[data-src][data-thumb],div.img[data-src],div.lazy[data-src]"), div => {
  3061. div.style.setProperty("background-image", "url(" + div.dataset.src + ")", "important");
  3062. });
  3063. }
  3064. if (/^A$/i.test(ele.nodeName) && ele.classList.contains("lazyload")) {
  3065. if (ele.dataset.original) {
  3066. ele.style.backgroundImage = 'url("' + ele.dataset.original + '")';
  3067. }
  3068. } else {
  3069. [].forEach.call(ele.querySelectorAll("a.lazyload"), a => {
  3070. if (a.dataset.original) {
  3071. a.style.backgroundImage = 'url("' + a.dataset.original + '")';
  3072. }
  3073. });
  3074. }
  3075. });
  3076. }
  3077.  
  3078. initPage(callback) {
  3079. let self = this;
  3080. if (self.initing) return;
  3081. self.initing = true;
  3082. setTimeout(() => {
  3083. self.initing = false;
  3084. }, 100);
  3085. curPage = 1;
  3086. urlChanged = false;
  3087. this.clearAddedElements();
  3088. this.insert = null;
  3089. this.visibilityItems = [];
  3090. this.visibleIndex = -1;
  3091. this.pageDoc = document;
  3092. this.nextLinkHref = null;
  3093. this.curUrl = location.href;
  3094. this.oldUrl = "";
  3095. this.initUrl = location.href;
  3096. this.historyUrl = "";
  3097. let base = document.querySelector("base");
  3098. this.basePath = base ? base.href : location.href;
  3099. this.getRule(async () => {
  3100. isPause = false;
  3101. if (self.curSiteRule.enable == 0) {
  3102. debug("Stop as rule disable");
  3103. isPause = true;
  3104. _GM_registerMenuCommand(i18n("enable"), () => {
  3105. showTips(i18n("enableSiteTips"));
  3106. if(!self.customRules) {
  3107. self.customRules = [];
  3108. }
  3109. for (let i in self.customRules) {
  3110. if (self.customRules[i].url == self.curSiteRule.url) {
  3111. self.customRules.splice(i, 1);
  3112. break;
  3113. }
  3114. }
  3115. self.curSiteRule.enable = 1;
  3116. self.customRules.unshift(self.curSiteRule);
  3117. storage.setItem("customRules", self.customRules);
  3118. location.reload();
  3119. });
  3120. return;
  3121. }
  3122. //若是再亂匹配就不緩存wedata,或者只在找完本地規則之後再考慮wedata的緩存
  3123. if (self.curSiteRule.singleUrl) {
  3124. delete self.curSiteRule.pageElement;
  3125. self.smartRules = self.smartRules.filter(item => {return item && item.url != self.curSiteRule.url});
  3126. self.smartRules.unshift(self.curSiteRule);
  3127. if (self.smartRules.length > 100) {
  3128. self.smartRules.pop();
  3129. }
  3130. storage.setItem("smartRules", self.smartRules);
  3131. } else if (self.curSiteRule && self.curSiteRule.url.length > 13) {
  3132. self.addToHpRules();
  3133. }
  3134. let css = self.curSiteRule.css || rulesData.customCss;
  3135. if (css) {
  3136. let cssArr = css.split("inIframe:");
  3137. if (cssArr && cssArr.length) {
  3138. _GM_addStyle(cssArr[0]);
  3139. }
  3140. }
  3141. if (/sidesearch=(1|true)$/.test(self.curUrl)) {
  3142. openInNewTab = 0;
  3143. } else if (typeof self.curSiteRule.openInNewTab !== 'undefined') {
  3144. openInNewTab = self.curSiteRule.openInNewTab ? 1 : 2;
  3145. }
  3146. let autoClick = self.curSiteRule.autoClick;
  3147. if (autoClick) {
  3148. let autoClickBtn;
  3149. autoClickBtn = getElement(autoClick, document, null, true);
  3150. if (autoClickBtn) {
  3151. emuClick(autoClickBtn);
  3152. }
  3153. }
  3154. let code = self.curSiteRule.init;
  3155. if (code) {
  3156. try {
  3157. ((typeof _unsafeWindow.pagetualInit == 'undefined') ? new AsyncFunction('doc', 'win', 'iframe', 'click', 'enter', 'input', '"use strict";' + code) : _unsafeWindow.pagetualInit)(null, null, null, sel => {clickAction(sel, document)}, sel => {enterAction(sel, document)}, (sel, v) =>{inputAction(sel, v, document)});
  3158. } catch(e) {
  3159. debug(e);
  3160. }
  3161. }
  3162. await self.getNextLink(document, true);
  3163. if (self.curSiteRule.pageNum && self.nextLinkHref && self.nextLinkHref != "#") {
  3164. let num1st = self.getPageNumFromUrl(location.href, 1);
  3165. let num2nd = self.getPageNumFromUrl(self.nextLinkHref, 1);
  3166. if (num2nd != num1st + 1) {
  3167. self.curSiteRule.pageNum = null;
  3168. }
  3169. }
  3170. if (self.curSiteRule.singleUrl && self.nextLinkHref == false && self.possibleRule) {
  3171. setTimeout(() => {
  3172. self.initPage(() => {});
  3173. }, 1000);
  3174. }
  3175. self.refreshByClick();
  3176.  
  3177. let pageElementCss = self.curSiteRule.pageElementCss || rulesData.pageElementCss;
  3178. if (pageElementCss && pageElementCss !== '0') {
  3179. self.getPageElement(document, _unsafeWindow);
  3180. }
  3181. callback();
  3182. let initRun = typeof self.curSiteRule.initRun == 'undefined' ? rulesData.initRun : self.curSiteRule.initRun;
  3183. if (initRun && initRun != false && self.nextLinkHref) {
  3184. setTimeout(() => {
  3185. nextPage();
  3186. }, 500);
  3187. }
  3188. });
  3189. }
  3190.  
  3191. beginLoading() {
  3192. isLoading = true;
  3193. let lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3194. ruleParser.insertElement(loadingDiv);
  3195. if (forceState == 2) {
  3196. getBody(document).appendChild(loadingDiv);
  3197. } else {
  3198. let parent = loadingDiv.parentNode;
  3199. if (/^TBODY$/i.test(parent.nodeName)) {
  3200. parent = parent.parentNode;
  3201. }
  3202. if (/^TABLE$/i.test(parent.nodeName)) {
  3203. parent.parentNode.appendChild(loadingDiv);
  3204. }
  3205. }
  3206. getBody(document).scrollTop = lastScrollTop;
  3207. document.documentElement.scrollTop = lastScrollTop;
  3208. }
  3209.  
  3210. insertElement(ele) {
  3211. if (!this.insert || !this.insert.parentNode) {
  3212. this.getInsert();
  3213. }
  3214. if (this.insert) {
  3215. let self = this;
  3216. if (ele.nodeName == "#document-fragment") {
  3217. [].forEach.call(ele.children, el => {
  3218. self.addedElePool.push(el);
  3219. });
  3220. } else {
  3221. this.addedElePool.push(ele);
  3222. }
  3223. if (this.curSiteRule.insertPos == 2) {
  3224. this.insert.appendChild(ele);
  3225. } else {
  3226. this.insert.parentNode.insertBefore(ele, this.insert);
  3227. }
  3228. }
  3229. }
  3230.  
  3231. noValidContent(url) {
  3232. if (!this.curSiteRule.nextLinkByUrl) showTips(i18n("noValidContent"), url);
  3233. }
  3234.  
  3235. async insertPage(doc, eles, url, callback, tried) {
  3236. this.oldUrl = this.curUrl;
  3237. let oldTitle = this.pageDoc.title;
  3238. this.pageDoc = doc;
  3239. this.curUrl = url;
  3240. isLoading = true;
  3241. let nextLink = await this.getNextLink(doc);
  3242. this.nextTitle = "";
  3243. if (this.curSiteRule.pageBarText) {
  3244. if (this.curSiteRule.pageBarText == 1 || this.curSiteRule.pageBarText == true) {
  3245. this.nextTitle = doc.title;
  3246. } else {
  3247. try {
  3248. this.nextTitle = ((typeof _unsafeWindow.pagetualPageBarText == 'undefined') ? Function("doc",'"use strict";' + this.curSiteRule.pageBarText) : _unsafeWindow.pagetualPageBarText)(doc);
  3249. } catch(e) {
  3250. debug(e);
  3251. }
  3252. }
  3253. }
  3254. if (curPage == 1 && !tried && !nextLink && this.curSiteRule.singleUrl && this.curSiteRule.pageElement && this.curSiteRule.action != 0) {
  3255. this.curSiteRule.action = 1;
  3256. this.curUrl = location.href;
  3257. isLoading = false;
  3258. return false;
  3259. }
  3260. let lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3261. this.getInsert();
  3262. var self = this, newEles = [];
  3263. if (!eles || eles.length == 0 || !self.insert || !self.insert.parentNode) {
  3264. if (callback) callback(eles);
  3265. loadPageOver();
  3266. } else {
  3267. await this.pageInit(doc, eles);
  3268. if (callback) callback(eles);
  3269. loadPageOver();
  3270. const collection = document.createDocumentFragment();
  3271. [].forEach.call(eles, ele => {
  3272. let newEle = ele.cloneNode(true);
  3273. let oldCanvass = ele.querySelectorAll("canvas");
  3274. let newCanvass = newEle.querySelectorAll("canvas");
  3275. if (self.updateUrl) {
  3276. [].forEach.call(newEle.querySelectorAll("img"), img => {
  3277. if (img.getAttribute("src")) img.src = self.canonicalUri(img.getAttribute("src"));
  3278. });
  3279. [].forEach.call(newEle.querySelectorAll("a"), a => {
  3280. if (a.getAttribute("href")) a.href = self.canonicalUri(a.getAttribute("href"));
  3281. });
  3282. }
  3283. for (let i = 0; i < oldCanvass.length; i++) {
  3284. let oldCanvas = oldCanvass[i];
  3285. let newCanvas = newCanvass[i];
  3286. newCanvas.getContext('2d').drawImage(oldCanvas, 0, 0);
  3287. }
  3288. if (!/^(STYLE|SCRIPT)$/.test(newEle.nodeName)) self.visibilityItems.push(newEle);
  3289. collection.appendChild(newEle)
  3290. newEles.push(newEle);
  3291. });
  3292. self.insertElement(collection);
  3293. }
  3294. getBody(document).scrollTop = lastScrollTop;
  3295. document.documentElement.scrollTop = lastScrollTop;
  3296. this.pageAction(doc, newEles);
  3297. let enableHistory = this.curSiteRule.history;
  3298. let enableHistoryAfterInsert = false;
  3299. if (enableHistory == 1) {
  3300. enableHistory = true;
  3301. } else if (enableHistory == 2) {
  3302. enableHistory = true;
  3303. enableHistoryAfterInsert = true;
  3304. } else if (enableHistory == 0) {
  3305. enableHistory = false;
  3306. } else {
  3307. enableHistory = rulesData.enableHistory;
  3308. enableHistoryAfterInsert = rulesData.enableHistoryAfterInsert;
  3309. }
  3310. if (enableHistory) {
  3311. this.historyUrl = enableHistoryAfterInsert ? this.curUrl : this.oldUrl;
  3312. if(this.historyUrl != location.href) {
  3313. let isJs = this.hrefIsJs(this.historyUrl);
  3314. if (!isJs) {
  3315. let historyTitle = enableHistoryAfterInsert ? doc.title : oldTitle;
  3316. _unsafeWindow.history.replaceState(undefined, historyTitle, this.historyUrl);
  3317. document.title = historyTitle;
  3318. }
  3319. }
  3320. }
  3321. isLoading = false;
  3322. return true;
  3323. }
  3324. }
  3325. var ruleParser = new RuleParser();
  3326.  
  3327. class SideController {
  3328. //static controller;
  3329. constructor() {
  3330. this.inited = false;
  3331. }
  3332.  
  3333. /*static getInstance() {
  3334. if (!SideController.controller) {
  3335. SideController.controller = new SideController();
  3336. }
  3337. return SideController.controller;
  3338. }*/
  3339.  
  3340. setup() {
  3341. if (ruleParser.curSiteRule.sideController === false) return;
  3342. if (!rulesData.sideController && !ruleParser.curSiteRule.sideController) return;
  3343. this.addToStage();
  3344. }
  3345.  
  3346. init() {
  3347. if (this.inited) return;
  3348. this.inited = true;
  3349. let self = this;
  3350. this.cssText = `
  3351. #pagetual-sideController {
  3352. position: fixed;
  3353. top: calc(50% - 83px);
  3354. left: calc(99% - 40px);
  3355. width: 40px;
  3356. border-radius: 20px;
  3357. box-shadow: rgb(0 0 0) 0px 0px 10px;
  3358. text-align: center;
  3359. background: #ffffffd0!important;
  3360. user-select: none;
  3361. z-index: 2147483646!important;
  3362. padding: 0!important;
  3363. opacity: 0.35;
  3364. transition: opacity .5s ease, background .5s, box-shadow .5s;
  3365. }
  3366. #pagetual-sideController:hover {
  3367. opacity: 1;
  3368. }
  3369. #pagetual-sideController * {
  3370. font-weight: bold;
  3371. font-family: arial;
  3372. font-style: normal;
  3373. font-size: 20px!important;
  3374. color: black!important;
  3375. line-height: normal;
  3376. float: none;
  3377. }
  3378. #pagetual-sideController.stop {
  3379. -webkit-filter: invert(100%);
  3380. filter: invert(100%);
  3381. }
  3382. .pagetual-sideController-btn {
  3383. padding: 5px 0;
  3384. cursor: pointer;
  3385. transition: transform .15s ease-in-out, opacity .3s ease;
  3386. }
  3387. #pagetual-sideController .pagetual-sideController-btn:hover {
  3388. transform: scale(1.5);
  3389. color: red!important;
  3390. }
  3391. #pagetual-sideController.minSize {
  3392. box-shadow: rgb(0 0 0 / 0%) 0px 0px 0px;
  3393. background: #00000000!important;
  3394. }
  3395. #pagetual-sideController.minSize .pagetual-sideController-btn {
  3396. opacity: 0;
  3397. }
  3398. #pagetual-sideController #pagetual-sideController-move > svg {
  3399. transition: transform .3s ease;
  3400. }
  3401. #pagetual-sideController #pagetual-sideController-move > svg:hover {
  3402. transform: scale(1.2);
  3403. }
  3404. #pagetual-sideController.minSize #pagetual-sideController-move > svg {
  3405. background: white;
  3406. opacity: 0;
  3407. }
  3408. #pagetual-sideController #pagetual-sideController-move > img,
  3409. #pagetual-sideController #pagetual-sideController-move > span {
  3410. width: 35px;
  3411. height: 35px;
  3412. cursor: pointer;
  3413. }
  3414. #pagetual-sideController.minSize #pagetual-sideController-move > img,
  3415. #pagetual-sideController.minSize #pagetual-sideController-move > span {
  3416. border-radius: 50px;
  3417. text-shadow: rgb(255 255 255) 0px 0px 10px;
  3418. }
  3419. #pagetual-sideController #pagetual-sideController-pagenum {
  3420. font-size: 15px!important;
  3421. line-height: 30px;
  3422. text-align: center;
  3423. position: absolute;
  3424. right: calc(50% - 15px);
  3425. top: calc(50% - 15px);
  3426. border: 1px solid #00000099;
  3427. display: inline-block;
  3428. width: 30px;
  3429. height: 30px;
  3430. box-sizing: border-box;
  3431. border-radius: 50%;
  3432. background: white;
  3433. opacity: 0;
  3434. transition: opacity .5s ease;
  3435. pointer-events: none;
  3436. }
  3437. #pagetual-sideController.minSize #pagetual-sideController-pagenum {
  3438. opacity: 0.8;
  3439. }
  3440. `;
  3441. let frame = document.createElement("div");
  3442. frame.id = "pagetual-sideController";
  3443. frame.innerHTML = createHTML(`
  3444. <div id="pagetual-sideController-top" class="pagetual-sideController-btn">⊼</div>
  3445. <div>
  3446. <div id="pagetual-sideController-pre" class="pagetual-sideController-btn">∧</div>
  3447. <div id="pagetual-sideController-move"><svg 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>
  3448. <div id="pagetual-sideController-next" class="pagetual-sideController-btn">∨</div>
  3449. </div>
  3450. <div id="pagetual-sideController-bottom" class="pagetual-sideController-btn">⊻</div>
  3451. `);
  3452. let top = frame.querySelector("#pagetual-sideController-top");
  3453. let pre = frame.querySelector("#pagetual-sideController-pre");
  3454. let move = frame.querySelector("#pagetual-sideController-move");
  3455. let next = frame.querySelector("#pagetual-sideController-next");
  3456. let bottom = frame.querySelector("#pagetual-sideController-bottom");
  3457. let pagenum = frame.querySelector("#pagetual-sideController-pagenum");
  3458. if (sideControllerIcon) move.innerHTML = sideControllerIcon;
  3459.  
  3460. frame.addEventListener("dblclick", e => {
  3461. e.preventDefault();
  3462. e.stopPropagation();
  3463. });
  3464.  
  3465. frame.addEventListener("mouseenter", e => {
  3466. clearTimeout(self.hideTimer);
  3467. frame.classList.remove("minSize");
  3468. });
  3469.  
  3470. frame.addEventListener("mouseleave", e => {
  3471. clearTimeout(self.hideTimer);
  3472. self.hideTimer = setTimeout(() => {
  3473. frame.classList.add("minSize");
  3474. }, 800);
  3475. });
  3476.  
  3477. pre.addEventListener("click", e => {
  3478. let prePageBar = getPageBar().preBar;
  3479. if (prePageBar) {
  3480. scrollToPageBar(prePageBar);
  3481. } else {
  3482. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3483. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  3484. }
  3485. }, true);
  3486.  
  3487. next.addEventListener("click", e => {
  3488. let pageBarObj = getPageBar();
  3489. let nextPageBar = pageBarObj.nextBar;
  3490. if (nextPageBar) {
  3491. scrollToPageBar(nextPageBar);
  3492. } else {
  3493. if (pageBarObj.preBar) {
  3494. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  3495. window.scrollTo({ top: (scrollH || 9999999), behavior: 'smooth'});
  3496. } else {
  3497. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3498. window.scrollTo({ top: scrollTop + (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  3499. }
  3500. }
  3501. }, true);
  3502.  
  3503. top.addEventListener("click", e => {
  3504. getBody(document).scrollTop=0;
  3505. document.documentElement.scrollTop=0;
  3506. e.preventDefault();
  3507. e.stopPropagation();
  3508. }, true);
  3509.  
  3510. bottom.addEventListener("click", e => {
  3511. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  3512. changeStop(true);
  3513. }
  3514. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  3515. getBody(document).scrollTop = scrollH || 9999999;
  3516. document.documentElement.scrollTop = scrollH || 9999999;
  3517. e.preventDefault();
  3518. e.stopPropagation();
  3519. }, true);
  3520.  
  3521. let initX, initY, moving = false;
  3522. move.addEventListener("click", e => {
  3523. if (!moving) {
  3524. changeStop(!isPause);
  3525. }
  3526. }, true);
  3527. move.addEventListener("dblclick", e => {
  3528. clearTimeout(removeTimer);
  3529. document.removeEventListener("mousemove", mouseMoveHandler, true);
  3530. document.removeEventListener("mouseup", mouseUpHandler, true);
  3531. changeStop(!isPause);
  3532. if (isPause) {
  3533. ruleParser.hideAddedElements();
  3534. } else {
  3535. ruleParser.showAddedElements();
  3536. }
  3537. }, true);
  3538.  
  3539. move.oncontextmenu = e => {
  3540. e.preventDefault();
  3541. picker.start();
  3542. };
  3543. let removeTimer;
  3544.  
  3545. let mouseMoveHandler = e => {
  3546. if (moving) {
  3547. let windowHeight=window.innerHeight || document.documentElement.clientHeight;
  3548. let windowWidth=window.innerWidth || document.documentElement.clientWidth;
  3549. initX = (e.clientX - 10 + 40) / windowWidth * 100;
  3550. initY = (e.clientY - 83 + 83) / windowHeight * 100;
  3551. this.frame.style.top = `calc(${initY}% - 83px)`;
  3552. this.frame.style.left = `calc(${initX}% - 40px)`;
  3553. } else if (Math.abs(e.clientX - initX) + Math.abs(e.clientY - initY) > 20) {
  3554. moving = true;
  3555. clearTimeout(removeTimer);
  3556. }
  3557. };
  3558. let mouseUpHandler = e => {
  3559. clearTimeout(removeTimer);
  3560. document.removeEventListener("mousemove", mouseMoveHandler, true);
  3561. document.removeEventListener("mouseup", mouseUpHandler, true);
  3562. if (moving) {
  3563. rulesData.sideControllerPos = {x: parseInt(initX), y: parseInt(initY)};
  3564. storage.setItem("rulesData", rulesData);
  3565. }
  3566. };
  3567.  
  3568. move.addEventListener("mousedown", e => {
  3569. initX = e.clientX;
  3570. initY = e.clientY;
  3571. moving = false;
  3572. clearTimeout(removeTimer);
  3573. removeTimer = setTimeout(() => {
  3574. self.remove();
  3575. }, 1500);
  3576. document.addEventListener("mousemove", mouseMoveHandler, true);
  3577. document.addEventListener("mouseup", mouseUpHandler, true);
  3578. }, true);
  3579.  
  3580. this.frame = frame;
  3581. this.pagenum = pagenum;
  3582. if (rulesData.sideControllerPos) {
  3583. this.frame.style.top = `calc(${rulesData.sideControllerPos.y}% - 83px)`;
  3584. this.frame.style.left = `calc(${rulesData.sideControllerPos.x}% - 40px)`;
  3585. }
  3586. }
  3587.  
  3588. addToStage() {
  3589. this.init();
  3590. if (!this.styleEle || !this.styleEle.parentNode) {
  3591. this.styleEle = _GM_addStyle(this.cssText);
  3592. }
  3593. if (!isPause) {
  3594. this.frame.classList.remove("stop");
  3595. }
  3596. this.pagenum.innerText = curPage;
  3597. this.frame.title = i18n("page") + curPage;
  3598. if (this.frame.parentNode) return;
  3599. getBody(document).appendChild(this.frame);
  3600. clearTimeout(this.hideTimer);
  3601. this.frame.classList.add("minSize");
  3602. }
  3603.  
  3604. remove() {
  3605. if (this.frame && this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  3606. }
  3607. }
  3608. const sideController = new SideController();
  3609.  
  3610. class NextSwitch {
  3611. //static nextSwitch;
  3612. constructor() {
  3613. this.inited = false;
  3614. }
  3615.  
  3616. /*static getInstance() {
  3617. if (!NextSwitch.nextSwitch) {
  3618. NextSwitch.nextSwitch = new NextSwitch();
  3619. }
  3620. return NextSwitch.nextSwitch;
  3621. }*/
  3622.  
  3623. init() {
  3624. if (this.inited) return;
  3625. this.inited = true;
  3626. let self = this;
  3627. this.cssText = `
  3628. #pagetual-nextSwitch {
  3629. position: fixed;
  3630. top: 10px;
  3631. left: calc(50% - 160px);
  3632. background: aliceblue;
  3633. padding: 10px;
  3634. border-radius: 5px;
  3635. text-align: center;
  3636. opacity: 0.95;
  3637. color: #161616;
  3638. z-index: 2147483647;
  3639. font-size: 16px;
  3640. box-shadow: rgb(0 0 0) 0px 0px 10px;
  3641. }
  3642. #pagetual-nextSwitch>.title {
  3643. margin: -5px 45px 10px 45px;
  3644. font-size: 20px;
  3645. font-weight: bold;
  3646. border-bottom: 1px solid black;
  3647. user-select: none;
  3648. color: orangered;
  3649. }
  3650. #pagetual-nextSwitch>.group {
  3651. display: flex;
  3652. flex-direction: column;
  3653. }
  3654. #pagetual-nextSwitch>.group>span {
  3655. color: #161616;
  3656. cursor: pointer;
  3657. margin: 3px;
  3658. font-size: larger;
  3659. }
  3660. #pagetual-nextSwitch>.group>span:hover {
  3661. color: red;
  3662. }
  3663. #pagetual-nextSwitch>.group>span.current {
  3664. border: 2px dotted red;
  3665. border-radius: 10px;
  3666. }
  3667. #pagetual-nextSwitch>.closeSwitch {
  3668. position: absolute;
  3669. top: 3px;
  3670. right: 10px;
  3671. background: none;
  3672. border: none;
  3673. vertical-align: top;
  3674. transition: transform .15s ease-in-out;
  3675. float: right;
  3676. cursor: pointer;
  3677. }
  3678. #pagetual-nextSwitch svg {
  3679. width: 30px;
  3680. height: 30px;
  3681. vertical-align: middle;
  3682. fill: #161616;
  3683. overflow: hidden;
  3684. }
  3685. #pagetual-nextSwitch button:hover {
  3686. transform: scale(1.2);
  3687. }
  3688. `;
  3689. let frame = document.createElement("div");
  3690. frame.id = "pagetual-nextSwitch";
  3691. frame.innerHTML = createHTML(`
  3692. <div class="title">${i18n("nextSwitch")}</div>
  3693. <button type="button" class="closeSwitch">
  3694. <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2754">
  3695. <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">
  3696. </path>
  3697. </svg>
  3698. </button>
  3699. <div class="group"></div>
  3700. `);
  3701. let group = frame.querySelector(".group");
  3702. let closeBtn = frame.querySelector(".closeSwitch");
  3703. closeBtn.addEventListener("click", e => {
  3704. self.close();
  3705. }, true);
  3706. this.frame = frame;
  3707. let currentSpan;
  3708. ruleParser.curSiteRule.nextLink.forEach((link, i) => {
  3709. let span = document.createElement("span");
  3710. let target = getElement(link, document);
  3711. let index = "<b>" + (i + 1) + "</b>: ";
  3712. if (target) {
  3713. let targetInner = target.innerText.trim();
  3714. span.innerHTML = index + (targetInner || link);
  3715. } else {
  3716. span.innerHTML = index + "Not Found";
  3717. }
  3718. span.title = link;
  3719. span.addEventListener("click", e => {
  3720. if (currentSpan) currentSpan.classList.remove("current");
  3721. span.classList.add("current");
  3722. currentSpan = span;
  3723. nextIndex = i;
  3724. storage.setItem("nextSwitch_" + location.host, nextIndex === 0 ? "" : nextIndex);
  3725. ruleParser.curUrl += "#pagetual";
  3726. ruleParser.oldUrl = ruleParser.curUrl;
  3727. autoLoadNum = -1;
  3728. if (!ruleParser.nextLinkHref) {
  3729. isLoading = false;
  3730. }
  3731. ruleParser.getNextLink(ruleParser.pageDoc || document);
  3732. self.close();
  3733. }, true);
  3734. if (i == nextIndex) {
  3735. span.classList.add("current");
  3736. currentSpan = span;
  3737. }
  3738. group.appendChild(span);
  3739. });
  3740. }
  3741.  
  3742. start() {
  3743. this.init();
  3744. if (!this.styleEle || !this.styleEle.parentNode) {
  3745. this.styleEle = _GM_addStyle(this.cssText);
  3746. }
  3747. document.documentElement.appendChild(this.frame);
  3748. }
  3749.  
  3750. close() {
  3751. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  3752. }
  3753. }
  3754. const nextSwitch = new NextSwitch();
  3755.  
  3756. class Picker {
  3757. //static picker;
  3758. constructor() {
  3759. this.inited = false;
  3760. }
  3761.  
  3762. /*static getInstance() {
  3763. if (!Picker.picker) {
  3764. Picker.picker = new Picker();
  3765. }
  3766. return Picker.picker;
  3767. }*/
  3768.  
  3769. init() {
  3770. if (this.inited) return;
  3771. this.inited = true;
  3772. let self = this;
  3773. this.signList = [];
  3774. this.cssText = `
  3775. body.pagetual-picker,
  3776. body.pagetual-picker *:hover,
  3777. body.pagetual-picker a:hover {
  3778. cursor: crosshair !important;
  3779. }
  3780. #pagetual-picker {
  3781. position: fixed;
  3782. top: 10px;
  3783. left: calc(50% - 178px);
  3784. background: aliceblue;
  3785. padding: 10px;
  3786. border-radius: 5px;
  3787. text-align: center;
  3788. opacity: 0.95;
  3789. color: #161616;
  3790. z-index: 2147483646;
  3791. font-size: 16px;
  3792. box-shadow: rgb(0 0 0) 0px 0px 10px;
  3793. }
  3794. #pagetual-picker * {
  3795. margin: 0;
  3796. padding: 0;
  3797. font-family: Times New Roman;
  3798. overflow: initial;
  3799. user-select: none;
  3800. }
  3801. #pagetual-picker>.title {
  3802. margin: -5px 45px 10px 45px;
  3803. font-size: 20px;
  3804. font-weight: bold;
  3805. cursor: move;
  3806. border-bottom: 1px solid black;
  3807. user-select: none;
  3808. color: orangered;
  3809. height: initial;
  3810. width: initial;
  3811. position: initial;
  3812. }
  3813. #pagetual-picker button {
  3814. background: none;
  3815. border: none;
  3816. vertical-align: top;
  3817. transition: transform .15s ease-in-out;
  3818. float: right;
  3819. cursor: pointer;
  3820. overflow: hidden;
  3821. background-color: unset!important;
  3822. }
  3823. #pagetual-picker button:hover {
  3824. transform: scale(1.2);
  3825. }
  3826. #pagetual-picker>.closePicker {
  3827. position: absolute;
  3828. top: 3px;
  3829. right: 10px;
  3830. }
  3831. #pagetual-picker>.logoIcon {
  3832. position: absolute;
  3833. top: 3px;
  3834. left: 10px;
  3835. }
  3836. #pagetual-picker>.logoIcon.showSign>svg>path {
  3837. fill: gray;
  3838. }
  3839. #pagetual-picker textarea{
  3840. display: inline-block;
  3841. width: calc(100% - 65px);
  3842. height: 20px;
  3843. min-width: 290px;
  3844. max-width: calc(65vw - 50px);
  3845. min-height: unset;
  3846. padding: 6px 12px;
  3847. font-size: 16px;
  3848. font-weight: 400;
  3849. line-height: 1.5;
  3850. color: #495057;
  3851. background-color: #fff;
  3852. background-clip: padding-box;
  3853. border: 1px solid #ced4da;
  3854. border-radius: 4px;
  3855. transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
  3856. box-sizing: content-box;
  3857. margin-right: 5px;
  3858. resize: both;
  3859. box-shadow: 0 1px 5px 1px #ddd;
  3860. }
  3861. #pagetual-picker textarea:focus {
  3862. color: black;
  3863. background-color: #fff;
  3864. border-color: #80bdff;
  3865. outline: 0;
  3866. box-shadow: 0 0 0 3.2px rgb(0 123 255 / 25%);
  3867. }
  3868. #pagetual-picker [type=checkbox],
  3869. #pagetual-picker [type=radio] {
  3870. line-height: 20px;
  3871. height: 25px;
  3872. width: 25px;
  3873. margin-left: 5px;
  3874. vertical-align: middle;
  3875. appearance: auto;
  3876. display: inline-block;
  3877. position: initial;
  3878. }
  3879. #pagetual-picker label {
  3880. font-size: 18px;
  3881. line-height: 25px;
  3882. vertical-align: middle;
  3883. display: inline-block;
  3884. color: black;
  3885. position: initial;
  3886. cursor: pointer;
  3887. }
  3888. #pagetual-picker .bottom {
  3889. text-align: left;
  3890. margin: 10px 0;
  3891. width: 100%;
  3892. }
  3893. #pagetual-picker .bottom>button {
  3894. float: right;
  3895. }
  3896. #pagetual-picker svg {
  3897. width: 30px;
  3898. height: 30px;
  3899. vertical-align: middle;
  3900. fill: #161616;
  3901. overflow: hidden;
  3902. }
  3903. #pagetual-picker svg * {
  3904. pointer-events: none;
  3905. }
  3906. #pagetual-picker .allpath {
  3907. font-size: 18px;
  3908. margin: 10px auto;
  3909. max-width: 330px;
  3910. word-break: break-all;
  3911. cursor: context-menu;
  3912. overflow: hidden;
  3913. max-height: 42px;
  3914. -moz-transition:max-height 1s ease-in;
  3915. -webkit-transition:max-height 1s ease-in;
  3916. transition:max-height 1s ease-in;
  3917. color: black;
  3918. }
  3919. #pagetual-picker .allpath:hover {
  3920. max-height: calc(100vh - 130px);
  3921. overflow: auto;
  3922. }
  3923. #pagetual-picker .allpath>span.path {
  3924. cursor: pointer;
  3925. }
  3926. #pagetual-picker .allpath>span.path:hover {
  3927. color: orangered;
  3928. }
  3929. #pagetual-picker .moreConfig {
  3930. display: flex;
  3931. justify-content: space-between;
  3932. border-top: 1px solid;
  3933. padding-top: 10px;
  3934. width: 100%;
  3935. }
  3936. #pagetual-picker .command {
  3937. width: 100%;
  3938. color: black!important;
  3939. text-align: center;
  3940. font-size: large;
  3941. margin-top: 10px;
  3942. box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.12);
  3943. border-radius: 5px;
  3944. }
  3945. #pagetual-picker .command:hover {
  3946. color: orangered;
  3947. }
  3948. #pagetual-picker #showDetail {
  3949. float: initial;
  3950. margin-top: 10px;
  3951. }
  3952. #pagetual-picker #showDetail.showDetail {
  3953. float: right;
  3954. }
  3955. #pagetual-picker #showDetail>svg {
  3956. -moz-transition:transform 0.3s ease;
  3957. -webkit-transition:transform 0.3s ease;
  3958. transition:transform 0.3 ease;
  3959. }
  3960. #pagetual-picker #showDetail.showDetail>svg {
  3961. transform: rotate(180deg);
  3962. }
  3963. #pagetual-picker .tempRule {
  3964. margin-top: 10px;
  3965. height: 300px;
  3966. min-height: 150px;
  3967. }
  3968. #pagetual-picker #saveDetail {
  3969. display: none;
  3970. position: absolute;
  3971. bottom: 10px;
  3972. right: 8px;
  3973. }
  3974. #pagetual-picker .showDetail~#saveDetail {
  3975. display: inline-block;
  3976. }
  3977. #pagetual-picker #saveDetail svg {
  3978. width: 35px;
  3979. height: 35px;
  3980. }
  3981. #pagetual-picker .addProp {
  3982. display: none;
  3983. flex-direction: column;
  3984. position: absolute;
  3985. bottom: 45px;
  3986. right: 12px;
  3987. }
  3988. #pagetual-picker .showDetail~.addProp {
  3989. display: flex;
  3990. }
  3991. #pagetual-picker .addProp>button {
  3992. font-size: 30px;
  3993. font-family: Arial,sans-serif;
  3994. line-height: 35px;
  3995. color: #161616;
  3996. }
  3997. `;
  3998. this.mainSignDiv = this.createSignDiv();
  3999. this.allSignDiv = [];
  4000. let frame = document.createElement("div");
  4001. frame.id = "pagetual-picker";
  4002. frame.innerHTML = createHTML(`
  4003. <button title="Pagetual" type="button" class="logoIcon">
  4004. <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" 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>
  4005. </button>
  4006. <div class="title" title="${i18n("configure")}">${i18n("picker")}</div>
  4007. <button title="${i18n("closePicker")}" type="button" class="closePicker">
  4008. <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" fill="#604b4a"></path></svg>
  4009. </button>
  4010. <div class="allpath" title="${i18n("switchSelector")}"></div>
  4011. <div>
  4012. <textarea class="selector" spellcheck="false" name="selector" placeholder="${i18n("pickerPlaceholder")}"></textarea>
  4013. <button id="check" title="${i18n("pickerCheck")}" type="button">
  4014. <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" fill="#604b4a"></path></svg>
  4015. </button>
  4016. </div>
  4017. <div class="bottom">
  4018. <input name="xpath" id="checkbox_id" type="checkbox" />
  4019. <label for="checkbox_id">XPath</label>
  4020. <button id="edit" title="${i18n("gotoEdit")}" type="button">
  4021. <svg viewBox="0 0 1024 1024" style="color: orangered;fill: orangered;" version="1.1" xmlns="http://www.w3.org/2000/svg">
  4022. <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">
  4023. </path>
  4024. </svg>
  4025. </button>
  4026. </div>
  4027. <div class="moreConfig">
  4028. <div title="${i18n('forceStateIframe')}">
  4029. <input name="forceState" id="forceStateIframe" type="radio" />
  4030. <label for="forceStateIframe">${i18n('iframe')}</label>
  4031. </div>
  4032. <div title="${i18n('forceStateDynamic')}">
  4033. <input name="forceState" id="forceStateDynamic" type="radio" />
  4034. <label for="forceStateDynamic">${i18n('dynamic')}</label>
  4035. </div>
  4036. <div title="${i18n('forceStateDisable')}">
  4037. <input name="forceState" id="forceStateDisable" type="radio" />
  4038. <label for="forceStateDisable">${i18n('disable')}</label>
  4039. </div>
  4040. </div>
  4041. <button id="nextSwitch" class="command" title="${i18n("nextSwitch")}" type="button">${i18n("nextSwitch")}</button>
  4042. <button id="loadNow" class="command" title="${i18n("loadNow")}" type="button">${i18n("loadNow")}</button>
  4043. <button id="autoScroll" class="command" title="${i18n("toggleAutoScroll")}" type="button"></button>
  4044. <div>
  4045. <textarea style="display: none;" class="tempRule" spellcheck="false" placeholder="{Rule object}" title="Rule for current site"></textarea>
  4046. <button id="showDetail" title="" type="button">
  4047. <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" fill="orangered"></path></svg>
  4048. </button>
  4049. <div class="addProp">
  4050. <button id="addOtherProp" title="${i18n("addOtherProp")}" type="button">+</button>
  4051. <button id="addNextSelector" title="${i18n("addNextSelector")}" type="button">></button>
  4052. <button id="addPageSelector" title="${i18n("addPageSelector")}" type="button">❏</button>
  4053. </div>
  4054. <button id="saveDetail" title="${i18n("save")}" type="button">
  4055. <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" fill="orangered"></path></svg>
  4056. </button>
  4057. </div>
  4058. `);
  4059. let forceStateIframe = frame.querySelector("#forceStateIframe");//forceState 1 禁用 2 强嵌 3 动态
  4060. let forceStateDynamic = frame.querySelector("#forceStateDynamic");
  4061. let forceStateDisable = frame.querySelector("#forceStateDisable");
  4062. let clickRadio = e => {
  4063. let radio = e.currentTarget.querySelector('input');
  4064. if (radio.checked) {
  4065. forceState = "";
  4066. } else {
  4067. switch (radio.id) {
  4068. case "forceStateIframe":
  4069. forceState = 2;
  4070. break;
  4071. case "forceStateDynamic":
  4072. forceState = 3;
  4073. break;
  4074. case "forceStateDisable":
  4075. forceState = 1;
  4076. break;
  4077. default:
  4078. return;
  4079. }
  4080. }
  4081. storage.setItem("forceState_" + location.host, forceState);
  4082. self.close();
  4083. location.reload();
  4084. };
  4085. forceStateIframe.parentNode.addEventListener("mousedown", clickRadio);
  4086. forceStateDynamic.parentNode.addEventListener("mousedown", clickRadio);
  4087. forceStateDisable.parentNode.addEventListener("mousedown", clickRadio);
  4088. if (forceState == 1) forceStateDisable.checked = true;
  4089. else if (forceState == 2) forceStateIframe.checked = true;
  4090. else if (forceState == 3) forceStateDynamic.checked = true;
  4091. let closeBtn = frame.querySelector(".closePicker");
  4092. let logoBtn = frame.querySelector(".logoIcon");
  4093. let title = frame.querySelector(".title");
  4094. let allpath = frame.querySelector(".allpath");
  4095. let selectorInput = frame.querySelector(".selector");
  4096. let xpath = frame.querySelector("#checkbox_id");
  4097. let checkBtn = frame.querySelector("#check");
  4098. let editBtn = frame.querySelector("#edit");
  4099. let nextSwitchBtn = frame.querySelector("#nextSwitch");
  4100. let autoScrollBtn = frame.querySelector("#autoScroll");
  4101. let loadNow = frame.querySelector("#loadNow");
  4102. let tempRule = frame.querySelector(".tempRule");
  4103. let showDetailBtn = frame.querySelector("#showDetail");
  4104. let saveDetailBtn = frame.querySelector("#saveDetail");
  4105. let addOtherProp = frame.querySelector("#addOtherProp");
  4106. let addNextSelector = frame.querySelector("#addNextSelector");
  4107. let addPageSelector = frame.querySelector("#addPageSelector");
  4108. autoScrollBtn.addEventListener("click", e => {
  4109. self.close();
  4110. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), 50)) || 0;
  4111. autoScroll = parseInt(autoScroll) || 0;
  4112. if (autoScroll < 0) autoScroll = 0;
  4113. else if (autoScroll > 1000) autoScroll = 1000;
  4114. storage.setItem("autoScroll_" + location.host + location.pathname, autoScroll);
  4115. startAutoScroll();
  4116. }, true);
  4117. addOtherProp.addEventListener("click", e => {
  4118. let propName = prompt(i18n("propName"));
  4119. if (!propName) return;
  4120. let propValue = prompt(i18n("propValue"));
  4121. if (!propValue) return;
  4122. if (propValue === "true") propValue = true;
  4123. else if (propValue === "false") propValue = false;
  4124. else if (/^\d+$/.test(propValue)) propValue = parseInt(propValue);
  4125. let editTemp = self.getTempRule();
  4126. if (!editTemp) return;
  4127. editTemp[propName] = propValue;
  4128. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  4129. }, true);
  4130. addNextSelector.addEventListener("click", e => {
  4131. let editTemp = self.getTempRule();
  4132. if (!editTemp) return;
  4133. let selector = self.selectorInput.value;
  4134. if (selector) {
  4135. editTemp.nextLink = selector;
  4136. }
  4137. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  4138. }, true);
  4139. addPageSelector.addEventListener("click", e => {
  4140. let editTemp = self.getTempRule();
  4141. if (!editTemp) return;
  4142. let selector = self.selectorInput.value;
  4143. if (selector) {
  4144. editTemp.pageElement = selector;
  4145. }
  4146. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  4147. }, true);
  4148. showDetailBtn.addEventListener("click", e => {
  4149. if (tempRule.style.display == "none") {
  4150. tempRule.style.display = "";
  4151. showDetailBtn.classList.add("showDetail");
  4152. } else {
  4153. tempRule.style.display = "none";
  4154. showDetailBtn.classList.remove("showDetail");
  4155. }
  4156. }, true);
  4157. saveDetailBtn.addEventListener("click", e => {
  4158. let editTemp = self.getTempRule(true);
  4159. if (tempRule.value && !editTemp) {
  4160. return;
  4161. }
  4162. if(!ruleParser.customRules) {
  4163. ruleParser.customRules = [];
  4164. }
  4165. for (let i in ruleParser.customRules) {
  4166. if (ruleParser.customRules[i].url == editTemp.url) {
  4167. ruleParser.customRules.splice(i, 1);
  4168. break;
  4169. }
  4170. }
  4171. if (tempRule.value) {
  4172. ruleParser.customRules.unshift(editTemp);
  4173. ruleParser.curSiteRule = editTemp;
  4174. } else {
  4175. ruleParser.curSiteRule = {};
  4176. isPause = true;
  4177. }
  4178. storage.setItem("customRules", ruleParser.customRules);
  4179. if (ruleParser.hpRules && ruleParser.curSiteRule && !ruleParser.curSiteRule.singleUrl) {
  4180. ruleParser.addToHpRules(true);
  4181. }
  4182. if (window.confirm(i18n("reloadPage"))) {
  4183. setTimeout(() => {location.reload()}, 100);
  4184. }
  4185. }, true);
  4186. nextSwitchBtn.addEventListener("click", e => {
  4187. self.close();
  4188. nextSwitch.start();
  4189. }, true);
  4190. loadNow.addEventListener("click", e => {
  4191. self.close();
  4192. let loadNum = window.prompt(i18n("loadConfirm"), "1");
  4193. if (loadNum === "" || loadNum === null) return;
  4194. autoLoadNum = Math.abs(parseInt(loadNum));
  4195. nextPage();
  4196. }, true);
  4197. closeBtn.addEventListener("click", e => {
  4198. self.close();
  4199. }, true);
  4200. this.showSign = true;
  4201. logoBtn.addEventListener("click", e => {
  4202. logoBtn.classList.toggle("showSign");
  4203. self.showSign = !self.showSign;
  4204. getBody(document).classList.toggle("pagetual-picker");
  4205. }, true);
  4206. let moving = false;
  4207. let initX = 0, initY = 0, initPos = {x: 0, y: 0};
  4208. let moveHanlder = e => {
  4209. if (moving) {
  4210. frame.style.left = e.clientX - initX + "px";
  4211. frame.style.top = e.clientY - initY + "px";
  4212. e.stopPropagation();
  4213. e.preventDefault();
  4214. } else if(Math.abs(e.clientX - initPos.x) + Math.abs(e.clientY - initPos.y) > 20) {
  4215. moving = true;
  4216. }
  4217. };
  4218. let upHanlder = e => {
  4219. if (moving) {
  4220. moving = false;
  4221. } else {
  4222. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  4223. }
  4224. document.removeEventListener("mousemove", moveHanlder, true);
  4225. title.removeEventListener("mouseup", upHanlder, true);
  4226. e.stopPropagation();
  4227. e.preventDefault();
  4228. };
  4229. title.addEventListener("mousedown", e => {
  4230. initPos = {x: e.clientX, y: e.clientY};
  4231. initX = e.clientX - parseInt(getComputedStyle(frame).left);
  4232. initY = e.clientY - parseInt(getComputedStyle(frame).top);
  4233. document.addEventListener("mousemove", moveHanlder, true);
  4234. title.addEventListener("mouseup", upHanlder, true);
  4235. });
  4236. frame.addEventListener("mouseenter", e => {
  4237. if (!self.showSign || moving) return;
  4238. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  4239. self.checkInputSelector();
  4240. });
  4241. frame.addEventListener("mouseleave", e => {
  4242. if (!self.showSign) {
  4243. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  4244. self.clearSigns();
  4245. return;
  4246. }
  4247. if (moving) return;
  4248. getBody(document).appendChild(self.mainSignDiv);
  4249. self.clearSigns();
  4250. });
  4251. checkBtn.addEventListener("click", e => {
  4252. self.checkInputSelector();
  4253. if (this.selectorInput.value) _GM_setClipboard(this.selectorInput.value);
  4254. showTips(i18n("copied"));
  4255. });
  4256. xpath.addEventListener("click", e => {
  4257. if (!selectorInput.value) {
  4258. self.setSelectorDiv("");
  4259. return;
  4260. }
  4261. let element = getElement(selectorInput.value, document);
  4262. let selector = self.getSelectorFromEle(element);
  4263. self.setSelectorDiv(selector);
  4264. selectorInput.value = selector;
  4265. });
  4266. editBtn.addEventListener("click", e => {
  4267. rulesData.editTemp = self.getTempRule();
  4268. storage.setItem("rulesData", rulesData);
  4269. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  4270. });
  4271. editBtn.oncontextmenu = e => {
  4272. e.preventDefault();
  4273. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  4274. };
  4275. this.frame = frame;
  4276. this.xpath = xpath;
  4277. this.allpath = allpath;
  4278. this.selectorInput = selectorInput;
  4279. this.nextSwitchBtn = nextSwitchBtn;
  4280. this.autoScrollBtn = autoScrollBtn;
  4281. this.loadNow = loadNow;
  4282. this.tempRule = tempRule;
  4283. this.logoBtn = logoBtn;
  4284. let setTitleTimer;
  4285. this.moveHandler = e => {
  4286. if (!self.showSign || e.target === document) return;
  4287. let target = self.getTarget(e.target);
  4288. self.adjustSignDiv(self.mainSignDiv, target);
  4289. clearTimeout(setTitleTimer);
  4290. setTitleTimer = setTimeout(() => {
  4291. if (self.inPicker && target.hasAttributes()) {
  4292. let title = target.nodeName.toLowerCase() + "\n";
  4293. for (const attr of target.attributes) {
  4294. title += `【${attr.name}】${attr.value ? " ➡️ " + attr.value : ""}\n`;
  4295. }
  4296. getBody(document).title = title;
  4297. }
  4298. }, 100);
  4299. };
  4300. this.clickHandler = e => {
  4301. if (!self.showSign) return;
  4302. if (self.inPicker) {
  4303. e.stopPropagation();
  4304. e.preventDefault();
  4305. }
  4306. let target = self.getTarget(e.target);
  4307. let selector = self.getSelectorFromEle(target);
  4308. selectorInput.value = selector;
  4309. self.setSelectorDiv(selector);
  4310. };
  4311. }
  4312.  
  4313. getTempRule(detail) {
  4314. if (this.tempRule.value) {
  4315. try {
  4316. this.editTemp = JSON.parse(this.tempRule.value);
  4317. } catch (e) {
  4318. this.editTemp = null;
  4319. if (detail) {
  4320. let pos = e && e.message && e.message.match(/position (\d+)/);
  4321. if (pos) {
  4322. pos = parseInt(pos[1]);
  4323. this.tempRule.value = this.tempRule.value.slice(0, pos) + "➡️" + this.tempRule.value[pos] + "⬅️" + this.tempRule.value.slice(pos + 1);
  4324. }
  4325. showTips(i18n("errorJson"));
  4326. return null;
  4327. }
  4328. }
  4329. }
  4330. if (!this.editTemp) {
  4331. if (ruleParser.curSiteRule.url && !ruleParser.curSiteRule.singleUrl) {
  4332. this.editTemp = ruleParser.curSiteRule;
  4333. } else {
  4334. this.editTemp = {
  4335. name: document.title,
  4336. url: "^" + (location.origin + location.pathname).replace(/[^\/]*$/, "").replace(/^https?/, "https?").replace(/\./g, "\\."),
  4337. example: location.href
  4338. };
  4339. }
  4340. delete this.editTemp.from;
  4341. delete this.editTemp.type;
  4342. delete this.editTemp.updatedAt;
  4343. }
  4344. if (this.selectorInput.value && this.tempRule.style.display == "none") {
  4345. this.editTemp.pageElement = this.selectorInput.value;
  4346. }
  4347. return this.editTemp;
  4348. }
  4349.  
  4350. getTarget(ele) {
  4351. while (ele.parentNode && (ele.offsetWidth === 0 || ele.offsetHeight === 0)) {
  4352. ele = ele.parentNode;
  4353. }
  4354. return ele;
  4355. }
  4356.  
  4357. close() {
  4358. this.clearSigns();
  4359. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  4360. if (this.mainSignDiv.parentNode) this.mainSignDiv.parentNode.removeChild(this.mainSignDiv);
  4361. getBody(document).classList.remove("pagetual-picker");
  4362. getBody(document).removeEventListener("mousemove", this.moveHandler, true);
  4363. getBody(document).removeEventListener("click", this.clickHandler, true);
  4364. getBody(document).title = "";
  4365. this.inPicker = false;
  4366. }
  4367.  
  4368. setImportant(ele, prop, value) {
  4369. ele.style.setProperty(prop, value, "important");
  4370. }
  4371.  
  4372. createSignDiv() {
  4373. let signDiv = document.createElement("div");
  4374. this.setImportant(signDiv, "position", "absolute");
  4375. this.setImportant(signDiv, "pointer-events", "none");
  4376. this.setImportant(signDiv, "z-index", "2147483646");
  4377. this.setImportant(signDiv, "background", "rgba(120, 170, 210, 0.6)");
  4378. this.setImportant(signDiv, "transition", "all 0.15s ease-out");
  4379. this.setImportant(signDiv, "box-shadow", "rgb(0 0 0) 0px 0px 3px 0px");
  4380. return signDiv;
  4381. }
  4382.  
  4383. adjustSignDiv(div, target) {
  4384. let rect = target.getBoundingClientRect();
  4385. this.setImportant(div, "width", rect.width + "px");
  4386. this.setImportant(div, "height", rect.height + "px");
  4387. this.setImportant(div, "left", rect.left + window.scrollX + "px");
  4388. this.setImportant(div, "top", rect.top + window.scrollY + "px");
  4389. }
  4390.  
  4391. getSelectorFromEle(ele) {
  4392. return this.xpath.checked ? createXPathFromElement(ele) : geneSelector(ele, true);
  4393. }
  4394.  
  4395. fillTempRuleTextarea() {
  4396. if (this.tempRule.style.display == "none") this.tempRule.value = JSON.stringify(this.getTempRule(), null, 4);
  4397. }
  4398.  
  4399. setSelectorDiv(selector) {
  4400. this.fillTempRuleTextarea();
  4401. let self = this;
  4402. this.allpath.innerHTML = createHTML("");
  4403. if (!selector) return;
  4404. if (this.xpath.checked) {
  4405. let span = document.createElement("span");
  4406. span.innerText = selector;
  4407. span.addEventListener("click", e => {
  4408. self.selectorInput.value = selector;
  4409. self.checkInputSelector();
  4410. }, true);
  4411. this.allpath.appendChild(span);
  4412. } else {
  4413. selector.split(">").forEach((item, index) => self.geneSelectorItem(item, index));
  4414. }
  4415. }
  4416.  
  4417. geneSelectorItem(item, index) {
  4418. let self = this;
  4419. item = item.trim();
  4420. if (!item) return;
  4421. if (index !== 0) {
  4422. let span = document.createElement("span");
  4423. span.innerText = " > ";
  4424. this.allpath.appendChild(span);
  4425. }
  4426. let span = document.createElement("span");
  4427. span.className = "path";
  4428. span.innerText = item;
  4429. span.addEventListener("click", e => {
  4430. let selector = "";
  4431. let target = e.target;
  4432. while (target) {
  4433. selector = target.innerText + selector;
  4434. target = target.previousElementSibling;
  4435. }
  4436. self.selectorInput.value = selector;
  4437. self.checkInputSelector();
  4438. }, true);
  4439. this.allpath.appendChild(span);
  4440. }
  4441.  
  4442. checkInputSelector() {
  4443. let self = this;
  4444. this.clearSigns();
  4445. if (!this.selectorInput.value) return;
  4446. let eles = getAllElements(this.selectorInput.value, document);
  4447. if (eles && eles.length > 0) {
  4448. eles.forEach(ele => {
  4449. let sign = self.createSignDiv();
  4450. getBody(document).appendChild(sign);
  4451. self.adjustSignDiv(sign, ele);
  4452. self.signList.push(sign);
  4453. });
  4454. this.fillTempRuleTextarea();
  4455. }
  4456. }
  4457.  
  4458. clearSigns() {
  4459. this.signList.forEach(sign => {
  4460. if (sign.parentNode) sign.parentNode.removeChild(sign);
  4461. });
  4462. this.signList = [];
  4463. }
  4464.  
  4465. start() {
  4466. this.init();
  4467. if (this.inPicker) return;
  4468. this.inPicker = true;
  4469. if (!this.styleEle || !this.styleEle.parentNode) {
  4470. this.styleEle = _GM_addStyle(this.cssText);
  4471. }
  4472. document.documentElement.appendChild(this.frame);
  4473. getBody(document).appendChild(this.mainSignDiv);
  4474. getBody(document).classList.add("pagetual-picker");
  4475.  
  4476. this.logoBtn.classList.remove("showSign");
  4477. this.showSign = true;
  4478.  
  4479. getBody(document).addEventListener("mousemove", this.moveHandler, true);
  4480. getBody(document).addEventListener("click", this.clickHandler, true);
  4481. this.xpath.checked = isXPath(ruleParser.curSiteRule.pageElement);
  4482.  
  4483. this.loadNow.style.display = ruleParser.nextLinkHref ? "block" : "none";
  4484. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  4485. this.nextSwitchBtn.style.display = "block";
  4486. } else {
  4487. this.nextSwitchBtn.style.display = "none";
  4488. }
  4489. this.autoScrollBtn.innerText = i18n(autoScroll ? "disableAutoScroll" : "enableAutoScroll");
  4490.  
  4491. let pageElementSel = ruleParser.curSiteRule.pageElement || "";
  4492. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  4493. pageElementSel = pageElementSel[nextIndex < pageElementSel.length ? nextIndex : 0];
  4494. }
  4495. this.setSelectorDiv(pageElementSel);
  4496. }
  4497. }
  4498. const picker = new Picker();
  4499.  
  4500. var editor, editorChanged = false;
  4501. function createEdit() {
  4502. var options = {
  4503. mode: 'code',
  4504. modes: ['code', 'tree'],
  4505. templates: [
  4506. {
  4507. text: 'New site',
  4508. title: 'Insert a new site',
  4509. className: 'jsoneditor-type-object',
  4510. field: 'SiteTemplate',
  4511. value: {
  4512. 'name': 'Site name',
  4513. 'url': 'Site url'
  4514. }
  4515. }
  4516. ],
  4517. schema: {
  4518. "title": "Sites data",
  4519. "description": "Object containing site config",
  4520. "type": "array",
  4521. "items": {
  4522. "type": 'object',
  4523. "properties": {
  4524. "name": {
  4525. "title": "Site Name",
  4526. "description": "The site's name.",
  4527. "examples": [
  4528. "Google"
  4529. ],
  4530. "type": "string"
  4531. },
  4532. "url": {
  4533. "title": "Site Url",
  4534. "description": "The Regexp of site's url.",
  4535. "examples": [
  4536. "^https:\/\/yande\\.re\/"
  4537. ],
  4538. "type": "string"
  4539. }
  4540. },
  4541. "required": ["name", "url"]
  4542. }
  4543. },
  4544. onChange: () => {
  4545. editorChanged = true;
  4546. }
  4547. };
  4548. setTimeout(() => {
  4549. var container = document.getElementById("jsoneditor");
  4550. container.style.height = '800px';
  4551. container.innerHTML = "";
  4552. editor = new JSONEditor(container, options);
  4553. editor.set(ruleParser.customRules);
  4554. }, 500);
  4555. }
  4556.  
  4557. function checkGuidePage(href) {
  4558. if (guidePage.test(href)) {
  4559. if (typeof JSONEditor !== 'undefined') {
  4560. createEdit();
  4561. } else {
  4562. let checkEditorReady = setInterval(() => {
  4563. if (typeof JSONEditor !== 'undefined') {
  4564. createEdit();
  4565. clearInterval(checkEditorReady);
  4566. }
  4567. }, 100);
  4568. }
  4569. [].forEach.call(getBody(document).querySelectorAll('a'), ele => {
  4570. ele.target = "_blank";
  4571. });
  4572. return true;
  4573. }
  4574. return false;
  4575. }
  4576.  
  4577. function startAutoScroll() {
  4578. clearInterval(autoScrollInterval);
  4579. if (autoScroll <= 0) return;
  4580. autoScrollInterval = setInterval(() => {
  4581. if (isPause) return;
  4582. window.scroll(window.scrollX, window.scrollY + 1);
  4583. }, parseInt(1000 / autoScroll));
  4584. }
  4585.  
  4586. var inUpdate = false;
  4587. function initConfig(href) {
  4588. let isGuidePage = checkGuidePage(href);
  4589. if (!isGuidePage) {
  4590. if (href.indexOf("PagetualGuide") != -1) return true;
  4591. if (location.hostname === "pagetual.hoothin.com") return true;
  4592. }
  4593.  
  4594. var configCon, insertPos, click2import, importUrlPre;
  4595.  
  4596. let inConfig = isGuidePage;
  4597. if (!inConfig) {
  4598. for (let i = 0; i < configPage.length; i++) {
  4599. if (configPage[i] == location.href) {
  4600. inConfig = true;
  4601. break;
  4602. }
  4603. }
  4604. }
  4605. if (ruleImportUrlReg.test(href) || inConfig) {
  4606. let importing = false;
  4607. if (!inUpdate && rulesData.uninited) {
  4608. setTimeout(() => {
  4609. if (!inUpdate && !importing) showTips(i18n("firstAlert"));
  4610. }, 3000);
  4611. setTimeout(() => {
  4612. if (!inUpdate && !importing) showTips(i18n("firstAlert"));
  4613. }, 6000);
  4614. showTips(i18n("firstAlert"));
  4615. }
  4616. let defaultOption = document.querySelector('#discussion_rating_4');
  4617. if (defaultOption) defaultOption.checked = true;
  4618. let createImportBtn = (pre) => {
  4619. let importBtn = document.createElement("button");
  4620. importBtn.id = "pagetualImport";
  4621. importBtn.innerText = i18n("import");
  4622. importBtn.style.marginTop = "100px";
  4623. importBtn.style.float = "right";
  4624. importBtn.style.position = "relative";
  4625. importBtn.style.display = "block";
  4626. importBtn.style.fontSize = "20px";
  4627. importBtn.addEventListener("click", e => {
  4628. let parentNode = importBtn.parentNode;
  4629. if (!parentNode) return;
  4630. parentNode.removeChild(importBtn);
  4631. try {
  4632. let rules = parentNode.innerText.trim();
  4633. let isContent = /['"]name['"]/i.test(rules);
  4634. if (isContent) {
  4635. let ruleList = JSON.parse(`[${rules}]`);
  4636. for (let i in ruleList) {
  4637. let hasRule = false;
  4638. let r = ruleList[i];
  4639. for (let j in ruleParser.customRules) {
  4640. if (ruleParser.customRules[j].name == r.name) {
  4641. ruleParser.customRules[j] = r;
  4642. hasRule = true;
  4643. break;
  4644. }
  4645. }
  4646. if (!hasRule) ruleParser.customRules.push(r);
  4647. ruleParser.hpRules.unshift(r);
  4648. }
  4649. storage.setItem("customRules", ruleParser.customRules);
  4650. storage.setItem("hpRules", ruleParser.hpRules);
  4651. storage.setItem("smartRules", []);
  4652. showTips(i18n("importSucc"));
  4653. } else {
  4654. rules = rules.split("\n");
  4655. let diff = false;
  4656. for (let c = 0; c < rules.length; c++) {
  4657. let urlArr = rules[c].split("|"), url, type = 1;
  4658. if (urlArr.length == 1) {
  4659. url = urlArr[0].trim();
  4660. if (!/^http/.test(url)) {
  4661. showTips(i18n("errorWrongUrl"));
  4662. return;
  4663. }
  4664. } else if (urlArr.length == 2) {
  4665. type = urlArr[0].trim();
  4666. url = urlArr[1].trim();
  4667. if (!/^http/.test(url)) {
  4668. showTips(i18n("errorWrongUrl"));
  4669. return;
  4670. }
  4671. } else {
  4672. break;
  4673. }
  4674. let maxId = 1, hasUrl = false;
  4675. if (!rulesData.urls) {
  4676. rulesData.urls = [];
  4677. maxId = 1;
  4678. } else {
  4679. rulesData.urls.forEach(u => {
  4680. if (maxId < u.id) {
  4681. maxId = u.id;
  4682. }
  4683. if (u.url == url) {
  4684. hasUrl = true;
  4685. }
  4686. });
  4687. if (hasUrl) break;
  4688. }
  4689. diff = true;
  4690. if (!rulesData.sort) rulesData.sort = [1];
  4691. rulesData.urls.push({id: maxId + 1, url: url, type: type});
  4692. rulesData.sort.unshift(maxId + 1);
  4693. }
  4694. if (!diff) {
  4695. showTips(i18n("errorAlreadyExists"));
  4696. setTimeout(() => {
  4697. showTips(i18n("beginUpdate"), "", 30000);
  4698. updateRules(() => {
  4699. showTips(i18n("updateSucc"));
  4700. location.reload();
  4701. }, (rule, err) => {
  4702. showTips(`Failed to update ${rule.url} rules!`);
  4703. debug(err);
  4704. });
  4705. }, 500);
  4706. return;
  4707. }
  4708. storage.setItem("rulesData", rulesData);
  4709.  
  4710. if (rulesData.urls) ruleUrls = ruleUrls.concat(rulesData.urls);
  4711. if (rulesData.sort) {
  4712. let urls = [];
  4713. rulesData.sort.forEach(id => {
  4714. for (let s = 0; s < ruleUrls.length; s++) {
  4715. if (id == ruleUrls[s].id) {
  4716. urls.push(ruleUrls[s]);
  4717. break;
  4718. }
  4719. }
  4720. });
  4721. ruleUrls = urls;
  4722. }
  4723. showTips(i18n("beginUpdate"), "", 30000);
  4724. updateRules(() => {
  4725. showTips(i18n("updateSucc"));
  4726. location.reload();
  4727. }, (rule, err) => {
  4728. showTips(`Failed to update ${rule.url} rules!`);
  4729. debug(err);
  4730. });
  4731. importing = true;
  4732. }
  4733. } catch (e) {
  4734. _GM_notification(e.toString());
  4735. }
  4736. });
  4737. if (pre) {
  4738. let clientHeight = 35 - pre.clientHeight;
  4739. if (clientHeight > -20) clientHeight = -20;
  4740. importBtn.style.marginTop = `${clientHeight}px`;
  4741. pre.appendChild(importBtn);
  4742. }
  4743. return importBtn;
  4744. };
  4745. [].forEach.call(document.querySelectorAll('pre[name=pagetual],pre[name=user-content-pagetual]'), pre => {
  4746. let importBtn = createImportBtn(pre);
  4747. });
  4748. document.addEventListener("mouseover", e => {
  4749. if (/^PRE$/i.test(e.target.nodeName)) {
  4750. let nameAttr = e.target.getAttribute("name");
  4751. if (nameAttr == "pagetual" || nameAttr == "user-content-pagetual") {
  4752. if (e.target.querySelector('#pagetualImport')) return;
  4753. let importBtn = createImportBtn(e.target);
  4754. }
  4755. }
  4756. });
  4757.  
  4758. if (inConfig) {
  4759. if (!inUpdate && _GM_info.script && _GM_info.script.version && _GM_info.script.version !== '1.0.0') {
  4760. let versionEle = document.querySelector('.markdown-body>h1[id],article>h1');
  4761. let latestVer = versionEle && versionEle.innerText.match(/\d[\d\.]+/)[0];
  4762. if (latestVer && latestVer != _GM_info.script.version) {
  4763. showTips(i18n('outOfDate'), "", 3000);
  4764. }
  4765. }
  4766. _GM_addStyle(`
  4767. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  4768. cursor: pointer;
  4769. user-select: none;
  4770. display: inline-block;
  4771. margin-right: 5px;
  4772. -moz-transition:color 0.3s ease, transform 0.3s;
  4773. -webkit-transition:color 0.3s ease, transform 0.3s;
  4774. transition:color 0.3s ease, transform 0.3s;
  4775. }
  4776. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  4777. color:red;
  4778. transform: scale(1.5);
  4779. -webkit-transform: scale(1.5);
  4780. }
  4781. .updateDate{
  4782. cursor: pointer;
  4783. user-select: none;
  4784. -moz-transition:color 0.3s ease, transform 0.3s;
  4785. -webkit-transition:color 0.3s ease, transform 0.3s;
  4786. transition:color 0.3s ease, transform 0.3s;
  4787. transform-origin: left;
  4788. -webkit-transform-origin: left;
  4789. }
  4790. .updateDate:hover{
  4791. color:red;
  4792. transform: scale(1.1);
  4793. -webkit-transform: scale(1.1);
  4794. }
  4795. input[type=number]::-webkit-inner-spin-button,
  4796. input[type=number]::-webkit-outer-spin-button {
  4797. -webkit-appearance: none;
  4798. margin: 0;
  4799. }
  4800. input[type=number] {
  4801. -moz-appearance:textfield;
  4802. }
  4803. table td>h3 {
  4804. margin: 16px!important;
  4805. }
  4806. #saveBtn {
  4807. width: 100%;
  4808. position: fixed;
  4809. z-index: 999;
  4810. bottom: 0px;
  4811. left: 0px;
  4812. font-size: x-large;
  4813. opacity: 0.8;
  4814. cursor: pointer;
  4815. -moz-transition:opacity 0.3s ease;
  4816. -webkit-transition:opacity 0.3s ease;
  4817. transition:opacity 0.3s ease;
  4818. }
  4819. #saveBtn:hover {
  4820. opacity: 1;
  4821. }
  4822. `);
  4823. click2import = document.querySelector("[name='user-content-click2import'],[name='click2import']");
  4824. if (click2import) click2import.innerText = i18n("click2ImportRule")
  4825. configCon = document.querySelector(".markdown-body,.theme-default-content");
  4826. if (!configCon) {
  4827. setTimeout(() => {
  4828. location.reload();
  4829. }, 1000);
  4830. return true;
  4831. }
  4832. insertPos = configCon.querySelector("hr,#jsoneditor");
  4833.  
  4834. importUrlPre = document.querySelector("pre[name='user-content-pagetual'],pre[name='pagetual']");
  4835. if (!rulesData.uninited) {
  4836. if (importUrlPre) importUrlPre.style.display = "none";
  4837. if (click2import) click2import.style.display = "none";
  4838. }
  4839. let otherconfig = document.querySelector("a[name='user-content-otherconfig'],a[name='otherconfig']");
  4840. if (otherconfig) otherconfig.parentNode.removeChild(otherconfig);
  4841. let rulesExample = document.querySelector("#user-content-rules-example+a,#rules-example>a");
  4842. if (rulesExample) {
  4843. rulesExample.innerText = i18n("rulesExample");
  4844. if (lang == "zh-CN") {
  4845. rulesExample.href = rulesExample.href.replace("en", "cn");
  4846. } else if (lang == "zh-TW" || lang == "zh-HK") {
  4847. rulesExample.href = rulesExample.href.replace("/en", "");
  4848. }
  4849. }
  4850. } else return false;
  4851. } else return false;
  4852. class Rulebar {
  4853. init(ruleUrl) {
  4854. let id = ruleUrl.id;
  4855. this.ruleUrl = ruleUrl;
  4856. this.item = document.createElement("p");
  4857. this.item.dataset.id = id;
  4858. let url = document.createElement("a");
  4859. url.href = ruleUrl.url;
  4860. url.innerHTML = ruleUrl.url;
  4861. let up = document.createElement("span");
  4862. up.innerHTML = "↑ ";
  4863. up.title = i18n("sortTitle");
  4864. let down = document.createElement("span");
  4865. down.innerHTML = "↓ ";
  4866. down.title = i18n("sortTitle");
  4867. let del = document.createElement("span");
  4868. del.innerHTML = "× ";
  4869. up.onclick = e => {
  4870. this.moveUp();
  4871. };
  4872. down.onclick = e => {
  4873. this.moveDown();
  4874. };
  4875. del.onclick = e => {
  4876. this.del();
  4877. };
  4878. this.item.appendChild(up);
  4879. this.item.appendChild(down);
  4880. this.item.appendChild(del);
  4881. this.item.appendChild(url);
  4882. if (ruleParser.rules) {
  4883. url.style.maxWidth = "80%";
  4884. url.style.overflow = "hidden";
  4885. url.style.display = "inline-block";
  4886. url.style.textOverflow = "ellipsis";
  4887. url.style.verticalAlign = "bottom";
  4888. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == id ? 1 : 0), 0);
  4889. let idSpan = document.createElement("span");
  4890. idSpan.style.float = "right";
  4891. idSpan.innerHTML = `[rules: ${rulesLength}]`;
  4892. this.item.appendChild(idSpan);
  4893. this.idSpan = idSpan;
  4894. }
  4895. configCon.insertBefore(this.item, insertPos);
  4896. }
  4897. updateNum() {
  4898. if (ruleParser.rules) {
  4899. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == this.item.dataset.id ? 1 : 0), 0);
  4900. this.idSpan.innerHTML = `[rules: ${rulesLength}]`;
  4901. }
  4902. }
  4903. saveSort() {
  4904. let sort = [];
  4905. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i => {
  4906. sort.push(i.dataset.id);
  4907. });
  4908. rulesData.sort = sort;
  4909. let urls = [];
  4910. sort.forEach(id => {
  4911. for (let s = 0; s < ruleUrls.length; s++) {
  4912. if (id == ruleUrls[s].id) {
  4913. urls.push(ruleUrls[s]);
  4914. break;
  4915. }
  4916. }
  4917. });
  4918. ruleUrls = urls;
  4919. storage.setItem("rulesData", rulesData);
  4920. }
  4921. moveUp() {
  4922. let preE = this.item.previousElementSibling;
  4923. if (/^P$/i.test(preE.nodeName) && preE.children.length > 1) {
  4924. this.item.parentNode.insertBefore(this.item, preE);
  4925. this.saveSort();
  4926. }
  4927. }
  4928. moveDown() {
  4929. let nextE = this.item.nextElementSibling;
  4930. if (/^P$/i.test(nextE.nodeName) && nextE.children.length > 1) {
  4931. this.item.parentNode.insertBefore(nextE, this.item);
  4932. this.saveSort();
  4933. }
  4934. }
  4935. del() {
  4936. if (this.ruleUrl.id < 2) {
  4937. showTips(i18n("cantDel"));
  4938. } else if (window.confirm(i18n("confirmDel"))) {
  4939. for (let u = 0; u < rulesData.urls.length; u++) {
  4940. if (this.ruleUrl.id == rulesData.urls[u].id) {
  4941. rulesData.urls.splice(u, 1);
  4942. break;
  4943. }
  4944. }
  4945. for (let u = 0; u < ruleUrls.length; u++) {
  4946. if (this.ruleUrl.id == ruleUrls[u].id) {
  4947. ruleUrls.splice(u, 1);
  4948. break;
  4949. }
  4950. }
  4951. for (let u = 0; u < rulesData.sort.length; u++) {
  4952. if (this.ruleUrl.id == rulesData.sort[u]) {
  4953. rulesData.sort.splice(u, 1);
  4954. break;
  4955. }
  4956. }
  4957. storage.setItem("rulesData", rulesData);
  4958. ruleParser.rules = ruleParser.rules.filter(item => {return item.from != this.ruleUrl.id});
  4959. storage.setItem("rules", ruleParser.rules);
  4960. this.item.parentNode.removeChild(this.item);
  4961. //location.reload();
  4962. }
  4963. }
  4964. }
  4965. let langSelect = document.createElement("select");
  4966. langSelect.style.float = "right";
  4967. langSelect.style.position = "relative";
  4968. langSelect.style.zIndex = "1";
  4969. let option = document.createElement("option");
  4970. option.value = "";
  4971. option.innerText = "Language";
  4972. langSelect.appendChild(option);
  4973. for (let key in langList) {
  4974. let option = document.createElement("option");
  4975. option.value = key;
  4976. option.innerText = langList[key];
  4977. langSelect.appendChild(option);
  4978. }
  4979. langSelect.value = rulesData.lang || "";
  4980. configCon.insertBefore(langSelect, insertPos);
  4981.  
  4982. let updateP = document.createElement("p"), i = 0;
  4983. let now = new Date().getTime();
  4984.  
  4985.  
  4986. let pastDate = (new Date(updateDate)).toString(), passStr;
  4987. let passTime = (now - updateDate) / 1000;
  4988. if (isNaN(passTime)) {
  4989. passStr = i18n("firstUpdate");
  4990. } else {
  4991. if (passTime < 60) {
  4992. passStr = i18n("passSec", parseInt(passTime));
  4993. } else if (passTime < 60 * 60) {
  4994. passStr = i18n("passMin", parseInt(passTime / 60));
  4995. } else if (passTime < 60 * 60 * 24) {
  4996. passStr = i18n("passHour", parseInt(passTime / 3600));
  4997. } else {
  4998. passStr = i18n("passDay", parseInt(passTime / 86400));
  4999. }
  5000. passStr += " 🖱 " + i18n("click2update");
  5001. }
  5002.  
  5003. let rulebarList = [], updateFail = false;
  5004. updateP.className = "updateDate";
  5005. updateP.innerHTML = passStr;
  5006. updateP.title = i18n("update") + " - " + pastDate;
  5007. configCon.insertBefore(updateP, insertPos);
  5008. if (ruleUrls) {
  5009. ruleUrls.forEach(ruleUrl => {
  5010. let rulebar = new Rulebar();
  5011. rulebar.init(ruleUrl);
  5012. rulebarList.push(rulebar);
  5013. });
  5014. }
  5015. let customUrlsTitle = document.createElement("h2");
  5016. customUrlsTitle.innerHTML = i18n("customUrls");
  5017. configCon.insertBefore(customUrlsTitle, insertPos);
  5018. let customUrlsInput = document.createElement("textarea");
  5019. customUrlsInput.style.width = "100%";
  5020. customUrlsInput.placeholder = "http://wedata.net/databases/AutoPagerize/items_all.json \nhttps://hoothin.github.io/UserScripts/Pagetual/pagetualRules.json";
  5021. customUrlsInput.spellcheck = false;
  5022. configCon.insertBefore(customUrlsInput, insertPos);
  5023.  
  5024. let btns = document.createElement("div");
  5025. btns.style.display = "flex";
  5026. configCon.insertBefore(btns, insertPos);
  5027. let upBtnImg = document.createElement("div");
  5028. upBtnImg.style.width = "33%";
  5029. let upBtnImgTitle = document.createElement("h2");
  5030. upBtnImgTitle.style.whiteSpace = "nowrap";
  5031. upBtnImgTitle.style.overflow = "auto";
  5032. upBtnImgTitle.innerHTML = i18n("upBtnImg");
  5033. upBtnImg.appendChild(upBtnImgTitle);
  5034. let upBtnImgInput = document.createElement("input");
  5035. upBtnImgInput.style.width = "100%";
  5036. upBtnImgInput.placeholder = "data:image/png;base64,UpBtn";
  5037. upBtnImgInput.value = rulesData.upBtnImg || '';
  5038. upBtnImgInput.spellcheck = false;
  5039. upBtnImg.appendChild(upBtnImgInput);
  5040. btns.appendChild(upBtnImg);
  5041.  
  5042. let downBtnImg = document.createElement("div");
  5043. downBtnImg.style.width = "33%";
  5044. let downBtnImgTitle = document.createElement("h2");
  5045. downBtnImgTitle.style.whiteSpace = "nowrap";
  5046. downBtnImgTitle.style.overflow = "auto";
  5047. downBtnImgTitle.innerHTML = i18n("downBtnImg");
  5048. downBtnImg.appendChild(downBtnImgTitle);
  5049. let downBtnImgInput = document.createElement("input");
  5050. downBtnImgInput.style.width = "100%";
  5051. downBtnImgInput.placeholder = "data:image/png;base64,DownBtn";
  5052. downBtnImgInput.value = rulesData.downBtnImg || '';
  5053. downBtnImgInput.spellcheck = false;
  5054. downBtnImg.appendChild(downBtnImgInput);
  5055. btns.appendChild(downBtnImg);
  5056.  
  5057. let sideControllerIconDiv = document.createElement("div");
  5058. sideControllerIconDiv.style.width = "33%";
  5059. let sideControllerIconTitle = document.createElement("h2");
  5060. sideControllerIconTitle.style.whiteSpace = "nowrap";
  5061. sideControllerIconTitle.style.overflow = "auto";
  5062. sideControllerIconTitle.innerHTML = i18n("sideControllerIcon");
  5063. sideControllerIconDiv.appendChild(sideControllerIconTitle);
  5064. let sideControllerIconInput = document.createElement("input");
  5065. sideControllerIconInput.style.width = "100%";
  5066. sideControllerIconInput.placeholder = "🤍";
  5067. sideControllerIconInput.value = rulesData.sideControllerIcon || '';
  5068. sideControllerIconInput.spellcheck = false;
  5069. sideControllerIconDiv.appendChild(sideControllerIconInput);
  5070. btns.appendChild(sideControllerIconDiv);
  5071.  
  5072. let otherBtns = document.createElement("div");
  5073. otherBtns.style.display = "flex";
  5074. configCon.insertBefore(otherBtns, insertPos);
  5075. let loadingText = document.createElement("div");
  5076. loadingText.style.width = "100%";
  5077. let loadingTextTitle = document.createElement("h2");
  5078. loadingTextTitle.style.whiteSpace = "nowrap";
  5079. loadingTextTitle.style.overflow = "auto";
  5080. loadingTextTitle.innerHTML = i18n("loadingTextTitle");
  5081. loadingText.appendChild(loadingTextTitle);
  5082. let loadingTextInput = document.createElement("input");
  5083. loadingTextInput.value = rulesData.loadingText || '';
  5084. loadingTextInput.placeholder = i18n("loadingText");
  5085. loadingTextInput.style.width = "100%";
  5086. loadingTextInput.style.margin = "0";
  5087. loadingTextInput.spellcheck = false;
  5088. loadingText.appendChild(loadingTextInput);
  5089. otherBtns.appendChild(loadingText);
  5090.  
  5091. let opacity = document.createElement("div");
  5092. let opacityTitle = document.createElement("h2");
  5093. opacityTitle.style.whiteSpace = "nowrap";
  5094. opacityTitle.style.overflow = "visible";
  5095. opacityTitle.innerHTML = i18n("opacity");
  5096. opacity.appendChild(opacityTitle);
  5097. let opacityInput = document.createElement("input");
  5098. opacityInput.value = rulesData.opacity * 100;
  5099. opacityInput.type = "number";
  5100. opacityInput.min = 0;
  5101. opacityInput.max = 100;
  5102. opacityInput.style.width = "110px";
  5103. opacityInput.style.margin = "0";
  5104. opacityInput.placeholder = i18n("opacityPlaceholder");
  5105. opacityInput.spellcheck = false;
  5106. opacityInput.oninput = e => {
  5107. if (opacityInput.value > 100) opacityInput.value = 100;
  5108. else if (opacityInput.value < 0) opacityInput.value = 0;
  5109. };
  5110. opacity.appendChild(opacityInput);
  5111. otherBtns.appendChild(opacity);
  5112.  
  5113. let pageElementCss = document.createElement("div");
  5114. pageElementCss.style.marginBottom = "30px";
  5115. let pageElementCssTitle = document.createElement("h2");
  5116. pageElementCssTitle.innerHTML = i18n("pageElementCss");
  5117. pageElementCss.appendChild(pageElementCssTitle);
  5118. let pageElementCssInput = document.createElement("input");
  5119. pageElementCssInput.value = rulesData.pageElementCss || '';
  5120. pageElementCssInput.style.width = "100%";
  5121. pageElementCssInput.style.margin = "0";
  5122. pageElementCssInput.placeholder = "font-size: xx-large;";
  5123. pageElementCssInput.spellcheck = false;
  5124. pageElementCss.appendChild(pageElementCssInput);
  5125. configCon.insertBefore(pageElementCss, insertPos);
  5126.  
  5127. let customCss = document.createElement("div");
  5128. customCss.style.marginBottom = "50px";
  5129. let customCssTitle = document.createElement("h2");
  5130. customCssTitle.innerHTML = i18n("customCss");
  5131. customCss.appendChild(customCssTitle);
  5132. let customCssInput = document.createElement("textarea");
  5133. customCssInput.value = rulesData.customCss || '';
  5134. customCssInput.style.width = "100%";
  5135. customCssInput.style.margin = "0";
  5136. customCssInput.placeholder = ".pagetual {\n}";
  5137. customCssInput.spellcheck = false;
  5138. customCss.appendChild(customCssInput);
  5139. configCon.insertBefore(customCss, insertPos);
  5140.  
  5141. let configTable = document.createElement("table");
  5142. configTable.style.width = "100%";
  5143. let configTbody = document.createElement("tbody");
  5144. configTbody.style.width = "99%";
  5145. configTbody.style.display = "inline-table";
  5146. configTable.appendChild(configTbody);
  5147. configCon.insertBefore(configTable, insertPos);
  5148. function createCheckbox(innerText, val, tag, parentCheck, otherType) {
  5149. if (typeof val == 'undefined') val = "";
  5150. let title = document.createElement(tag || "h3");
  5151. title.innerHTML = innerText;
  5152. title.style.overflowWrap = "normal";
  5153. let input = document.createElement("input");
  5154. if (otherType === 'key') {
  5155. input.type = 'text';
  5156. input.setAttribute('readOnly', 'readonly');
  5157. input.addEventListener("keydown", e => {
  5158. if (e.key === 'Escape' || e.key === 'Backspace') input.value = '';
  5159. else input.value = e.key;
  5160. e.stopPropagation();
  5161. e.preventDefault();
  5162. });
  5163. } else {
  5164. input.type = otherType || "checkbox";
  5165. }
  5166. input.style.width = "30px";
  5167. input.style.height = "20px";
  5168. input.style.float = "left";
  5169. input.style.margin = "5px";
  5170. input.value = val;
  5171. input.checked = val;
  5172. let td = document.createElement("td");
  5173. td.appendChild(input);
  5174. if (parentCheck) {
  5175. title.style.margin = "0";
  5176. td.appendChild(title);
  5177. let parent = parentCheck.parentNode.nextElementSibling;
  5178. let tr = parent.querySelector("tr");
  5179. if (!tr) {
  5180. tr = document.createElement("tr");
  5181. parent.appendChild(tr);
  5182. }
  5183. tr.appendChild(td);
  5184. if (!parentCheck.checked) {
  5185. td.style.display = "none";
  5186. }
  5187. parentCheck.addEventListener("click", e => {
  5188. td.style.display = parentCheck.checked ? "" : "none";
  5189. });
  5190. } else {
  5191. let tr = document.createElement("tr");
  5192. tr.appendChild(td);
  5193. td = document.createElement("td");
  5194. td.appendChild(title);
  5195. tr.appendChild(td);
  5196. configTable.children[0].appendChild(tr);
  5197. }
  5198. let xNodePos = innerText.indexOf('【X】');
  5199. if (xNodePos !== -1) {
  5200. input.style.float = "";
  5201. let xNode = title.firstChild.splitText(xNodePos);
  5202. xNode.splitText(3);
  5203. xNode.parentNode.replaceChild(input, xNode);
  5204. }
  5205. return input;
  5206. }
  5207.  
  5208. let setConfigPageInput = createCheckbox(i18n("setConfigPage"), false);
  5209. let enableWhiteListInput = createCheckbox(i18n("autoRun"), rulesData.enableWhiteList != true);
  5210. let sideControllerInput = createCheckbox(i18n("sideController"), rulesData.sideController);
  5211. let enableDebugInput = createCheckbox(i18n("enableDebug"), rulesData.enableDebug != false);
  5212. let enableHistoryInput = createCheckbox(i18n("enableHistory"), rulesData.enableHistory === true);
  5213. let enableHistoryAfterInsertInput = createCheckbox(i18n("enableHistoryAfterInsert"), rulesData.enableHistoryAfterInsert === true);
  5214. let openInNewTabInput = createCheckbox(i18n("openInNewTab"), rulesData.openInNewTab != false);
  5215. let hidePageBarInput = createCheckbox(i18n("hideBarTips"), rulesData.opacity == 0);
  5216. let hidePageBarArrowInput = createCheckbox(i18n("hideBarArrow"), rulesData.hideBarArrow);
  5217. let hideLoadingIconInput = createCheckbox(i18n("hideLoadingIcon"), rulesData.hideLoadingIcon != false);
  5218. let initRunInput = createCheckbox(i18n("initRun"), rulesData.initRun != false);
  5219. let autoLoadNumInput = createCheckbox(i18n("autoLoadNum"), rulesData.autoLoadNum, "h4", initRunInput, "number");
  5220. let preloadInput = createCheckbox(i18n("preload"), rulesData.preload != false);
  5221. let rateInput = createCheckbox(i18n("turnRate"), rulesData.rate, "h4", preloadInput, "number");
  5222. let dbClick2StopInput = createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  5223. let manualModeInput = createCheckbox(i18n("manualMode"), rulesData.manualMode);
  5224. let clickModeInput = createCheckbox(i18n("clickMode"), rulesData.clickMode);
  5225. let pageBarMenuInput = createCheckbox(i18n("pageBarMenu"), rulesData.pageBarMenu != false);
  5226. let arrowToScrollInput = createCheckbox(i18n("arrowToScroll"), rulesData.arrowToScroll);
  5227. let contentVisibilityInput = createCheckbox(i18n("contentVisibility"), rulesData.contentVisibility);
  5228. let wedata2githubInput = createCheckbox(i18n("wedata2github"), rulesData.wedata2github);
  5229. let customFirstInput = createCheckbox(i18n("customFirst"), rulesData.customFirst);
  5230. let lastPageTipsInput = createCheckbox(i18n("lastPageTips"), rulesData.lastPageTips);
  5231.  
  5232. let hideBarInput = createCheckbox(i18n("hideBar"), rulesData.hideBar && !rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  5233. hideBarInput.name = 'hideBar';
  5234. let hideBarButNoStopInput = createCheckbox(i18n("hideBarButNoStop"), rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  5235. hideBarButNoStopInput.name = 'hideBar';
  5236. hideBarInput.addEventListener('mouseup', e => {
  5237. if (hideBarInput.checked) {
  5238. setTimeout(() => {hideBarInput.checked = false}, 0);
  5239. }
  5240. });
  5241. hideBarButNoStopInput.addEventListener('mouseup', e => {
  5242. if (hideBarButNoStopInput.checked) {
  5243. setTimeout(() => {hideBarButNoStopInput.checked = false}, 0);
  5244. }
  5245. });
  5246. hidePageBarInput.addEventListener('click', e => {
  5247. opacityInput.value = hidePageBarInput.checked ? 0 : 100;
  5248. });
  5249.  
  5250. let dbClick2StopCtrlInput = createCheckbox(i18n("dbClick2StopCtrl"), rulesData.dbClick2StopCtrl, "h4", dbClick2StopInput);
  5251. let dbClick2StopAltInput = createCheckbox(i18n("dbClick2StopAlt"), rulesData.dbClick2StopAlt, "h4", dbClick2StopInput);
  5252. let dbClick2StopShiftInput = createCheckbox(i18n("dbClick2StopShift"), rulesData.dbClick2StopShift, "h4", dbClick2StopInput);
  5253. let dbClick2StopMetaInput = createCheckbox(i18n("dbClick2StopMeta"), rulesData.dbClick2StopMeta, "h4", dbClick2StopInput);
  5254. let dbClick2StopKeyInput = createCheckbox(i18n("dbClick2StopKey"), rulesData.dbClick2StopKey, "h4", dbClick2StopInput, "key");
  5255.  
  5256. let otherConfigPage = rulesData.configPage ? rulesData.configPage != location.href : configPage[0] != location.href;
  5257. if (!otherConfigPage) {
  5258. setConfigPageInput.parentNode.parentNode.style.display = "none";
  5259. }
  5260.  
  5261. updateP.onclick = e => {
  5262. updateFail = false;
  5263. ruleParser.rules = [];
  5264. showTips(i18n("beginUpdate"), "", 30000);
  5265. updateRules(() => {
  5266. if (!updateFail) {
  5267. showTips(i18n("updateSucc"));
  5268. if (importUrlPre) importUrlPre.style.display = "none";
  5269. if (click2import) click2import.style.display = "none";
  5270. }
  5271. updateP.innerHTML = i18n("passSec", 0);
  5272. updateP.title = i18n("update");
  5273. rulebarList.forEach(rulebar => {
  5274. rulebar.updateNum();
  5275. });
  5276. }, (rule, err) => {
  5277. if (rule.id == 1) {
  5278. showTips(`Failed to update wedata rules! Try to switch to wedata mirror!`);
  5279. wedata2githubInput.scrollIntoView();
  5280. } else {
  5281. showTips(`Failed to update ${rule.url} rules!`);
  5282. }
  5283. debug(err);
  5284. updateFail = true;
  5285. });
  5286. };
  5287. let customRulesTitle = document.createElement("h2");
  5288. 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');
  5289. configCon.insertBefore(customRulesTitle, insertPos);
  5290. let customRulesInput = document.createElement("textarea");
  5291. customRulesInput.spellcheck = false;
  5292. configCon.insertBefore(customRulesInput, insertPos);
  5293. if (rulesData.editTemp) {
  5294. if (!ruleParser.customRules) {
  5295. ruleParser.customRules = [];
  5296. }
  5297. for (let i in ruleParser.customRules) {
  5298. if (ruleParser.customRules[i].url == rulesData.editTemp.url) {
  5299. ruleParser.customRules.splice(i, 1);
  5300. break;
  5301. }
  5302. }
  5303. ruleParser.customRules.unshift(rulesData.editTemp);
  5304. rulesData.editTemp = null;
  5305. storage.setItem("rulesData", rulesData);
  5306. customRulesInput.previousElementSibling.scrollIntoView();
  5307. }
  5308. customRulesInput.style.width = "100%";
  5309. customRulesInput.style.height = "800px";
  5310. 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]`;
  5311. let preCustom = getFormatJSON(ruleParser.customRules);
  5312. customRulesInput.value = preCustom;
  5313. if (isGuidePage) customRulesInput.style.display = "none";
  5314. let blacklistInput = document.createElement("textarea");
  5315. blacklistInput.style.width = "100%";
  5316. blacklistInput.style.height = "500px";
  5317. blacklistInput.style.display = "none";
  5318. blacklistInput.spellcheck = false;
  5319. blacklistInput.placeholder = "http://*.xxx.com/*/y\n/^https?://.*\\.xxx\\.com/i";
  5320. blacklistInput.value = rulesData.blacklist ? rulesData.blacklist.join("\n") : "";
  5321. let blacklistBtn = document.createElement("button");
  5322. blacklistBtn.innerText = i18n("editBlacklist");
  5323. blacklistBtn.style.width = "100%";
  5324. blacklistBtn.onclick = e => {
  5325. blacklistInput.style.display = blacklistInput.style.display == "none" ? "" : "none";
  5326. };
  5327. configCon.insertBefore(blacklistBtn, insertPos);
  5328. configCon.insertBefore(blacklistInput, insertPos);
  5329. let saveBtn = document.createElement("button");
  5330. saveBtn.innerHTML = i18n("save");
  5331. saveBtn.id = "saveBtn";
  5332. configCon.insertBefore(saveBtn, insertPos);
  5333. saveBtn.onclick = e => {
  5334. try {
  5335. let customRules;
  5336. if (editor) {
  5337. if (editorChanged) {
  5338. editorChanged = false;
  5339. storage.setItem("hpRules", []);
  5340. storage.setItem("smartRules", []);
  5341. }
  5342. customRules = editor.get();
  5343. if (!customRules) {
  5344. customRules = "";
  5345. } else {
  5346. if (Array && Array.isArray && !Array.isArray(customRules)) {
  5347. showTips(i18n("errorRulesMustBeArray"));
  5348. return;
  5349. }
  5350. }
  5351. } else {
  5352. if (customRulesInput.value != preCustom) {
  5353. storage.setItem("hpRules", []);
  5354. storage.setItem("smartRules", []);
  5355. }
  5356. if (customRulesInput.value == "") {
  5357. customRules = "";
  5358. } else {
  5359. customRules = JSON.parse(customRulesInput.value);
  5360. if (Array && Array.isArray && !Array.isArray(customRules)) {
  5361. showTips(i18n("errorRulesMustBeArray"));
  5362. return;
  5363. }
  5364. customRulesInput.value = JSON.stringify(customRules, null, 4);
  5365. }
  5366. }
  5367. debug(customRules);
  5368. storage.setItem("customRules", customRules);
  5369. } catch(e) {
  5370. debug(e);
  5371. let pos = e && e.message && e.message.match(/position (\d+)/);
  5372. if (pos && !editor) {
  5373. pos = parseInt(pos[1]);
  5374. customRulesInput.value = customRulesInput.value.slice(0, pos) + "➡️" + customRulesInput.value[pos] + "⬅️" + customRulesInput.value.slice(pos + 1);
  5375. }
  5376. showTips(i18n("errorJson"));
  5377. return;
  5378. }
  5379. rulesData.lang = langSelect.value || "";
  5380. if (setConfigPageInput.checked) rulesData.configPage = location.href;
  5381. rulesData.wedata2github = wedata2githubInput.checked;
  5382. let opacity = parseInt(opacityInput.value) || 0;
  5383. if (opacity > 100) opacity = 100;
  5384. else if (opacity < 0) opacity = 0;
  5385. rulesData.opacity = opacity / 100;
  5386. rulesData.blacklist = blacklistInput.value ? blacklistInput.value.trim().split("\n") : "";
  5387. rulesData.hideBar = hideBarInput.checked;
  5388. rulesData.hideBarButNoStop = hideBarButNoStopInput.checked;
  5389. rulesData.dbClick2Stop = dbClick2StopInput.checked;
  5390. rulesData.enableWhiteList = !enableWhiteListInput.checked;
  5391. rulesData.enableDebug = enableDebugInput.checked;
  5392. rulesData.enableHistory = enableHistoryInput.checked;
  5393. rulesData.enableHistoryAfterInsert = enableHistoryAfterInsertInput.checked;
  5394. rulesData.openInNewTab = openInNewTabInput.checked;
  5395. rulesData.hideLoadingIcon = hideLoadingIconInput.checked;
  5396. rulesData.hideBarArrow = hidePageBarArrowInput.checked;
  5397. rulesData.customFirst = customFirstInput.checked;
  5398. rulesData.lastPageTips = lastPageTipsInput.checked;
  5399. rulesData.initRun = initRunInput.checked;
  5400. rulesData.autoLoadNum = autoLoadNumInput.value !== "0" ? autoLoadNumInput.value : '';
  5401. rulesData.rate = parseInt(rateInput.value) || 1;
  5402. rulesData.preload = preloadInput.checked;
  5403. rulesData.manualMode = manualModeInput.checked;
  5404. rulesData.clickMode = clickModeInput.checked;
  5405. rulesData.pageBarMenu = pageBarMenuInput.checked;
  5406. rulesData.arrowToScroll = arrowToScrollInput.checked;
  5407. rulesData.contentVisibility = contentVisibilityInput.checked;
  5408. if (rulesData.sideController != sideControllerInput.checked) {
  5409. rulesData.sideControllerPos = false;
  5410. }
  5411. rulesData.sideController = sideControllerInput.checked;
  5412. rulesData.pageElementCss = pageElementCssInput.value;
  5413. rulesData.customCss = customCssInput.value;
  5414. rulesData.upBtnImg = upBtnImgInput.value;
  5415. rulesData.downBtnImg = downBtnImgInput.value;
  5416. rulesData.sideControllerIcon = sideControllerIconInput.value;
  5417. rulesData.loadingText = loadingTextInput.value;
  5418. rulesData.dbClick2StopCtrl = dbClick2StopCtrlInput.checked;
  5419. rulesData.dbClick2StopAlt = dbClick2StopAltInput.checked;
  5420. rulesData.dbClick2StopShift = dbClick2StopShiftInput.checked;
  5421. rulesData.dbClick2StopMeta = dbClick2StopMetaInput.checked;
  5422. rulesData.dbClick2StopKey = dbClick2StopKeyInput.value;
  5423. storage.setItem("rulesData", rulesData);
  5424. let customUrls = customUrlsInput.value.trim();
  5425. if (customUrls) {
  5426. customUrls = customUrls.split(/\n/);
  5427. for (let c = 0; c < customUrls.length; c++) {
  5428. let url;
  5429. if (/^0\s*\|/.test(customUrls[c])) {
  5430. url = customUrls[c].replace(/^0\s*\|\s*/, "").trim();
  5431. if (!/^http/.test(url)) {
  5432. showTips(i18n("errorWrongUrl"));
  5433. return;
  5434. }
  5435. } else {
  5436. url = customUrls[c].trim();
  5437. if (!/^http/.test(url)) {
  5438. showTips(i18n("errorWrongUrl"));
  5439. return;
  5440. }
  5441. }
  5442. let maxId = 1, hasUrl = false;
  5443. if (!rulesData.urls) {
  5444. rulesData.urls = [];
  5445. }
  5446. ruleUrls.forEach(u => {
  5447. if (maxId < u.id) {
  5448. maxId = u.id;
  5449. }
  5450. if (u.url == url) {
  5451. hasUrl = true;
  5452. }
  5453. });
  5454. if (hasUrl) break;
  5455. if (!rulesData.sort) rulesData.sort = [1];
  5456. rulesData.urls.push({id: maxId + 1, url: url});
  5457. rulesData.sort.push(maxId + 1);
  5458. storage.setItem("rulesData", rulesData);
  5459. }
  5460. }
  5461. showTips(i18n("settingsSaved"));
  5462. };
  5463. return true;
  5464. }
  5465.  
  5466. function updateRules (success, fail, keepCache) {
  5467. if (!storage.supportCrossSave()) {
  5468. fail({url:''}, "Not support cross storage");
  5469. showTips("Current platform do not support cross storage!");
  5470. return;
  5471. }
  5472. if (inUpdate) return;
  5473. inUpdate = true;
  5474. let ruleIndex = ruleUrls.length - 1;
  5475. if (!keepCache) {
  5476. storage.setItem("hpRules", []);
  5477. storage.setItem("smartRules", []);
  5478. }
  5479. let allOk = true;
  5480. function addNextRule() {
  5481. if (ruleIndex < 0) {
  5482. let now = new Date().getTime();
  5483. storage.setItem("ruleLastUpdate", now);
  5484. storage.setItem("rules", ruleParser.rules);
  5485. inUpdate = false;
  5486. if (allOk) {
  5487. rulesData.uninited = false;
  5488. storage.setItem("rulesData", rulesData);
  5489. }
  5490. success();
  5491. } else {
  5492. let rule = ruleUrls[ruleIndex--];
  5493. ruleParser.addRuleByUrl(rule.url, rule.id, (json, err) => {
  5494. if (!json) {
  5495. allOk = false;
  5496. fail(rule, err);
  5497. }
  5498. addNextRule();
  5499. })
  5500. }
  5501. }
  5502. addNextRule();
  5503. }
  5504.  
  5505. function objIsArr(obj) {
  5506. return obj &&
  5507. typeof obj === 'object' &&
  5508. typeof obj.length === 'number' &&
  5509. !(obj.propertyIsEnumerable('length'));
  5510. }
  5511.  
  5512. function isVisible(el, win) {
  5513. if(!el || !el.offsetParent)return false;
  5514. var loopable = true,
  5515. visible = el.nodeName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  5516. while(loopable && visible) {
  5517. el = el.parentNode;
  5518.  
  5519. if(el && !/^BODY$/i.test(el.nodeName)) {
  5520. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  5521. }else {
  5522. loopable = false;
  5523. }
  5524. }
  5525. return visible;
  5526. }
  5527.  
  5528. function getElementTop(ele) {
  5529. if (!ele) return 0;
  5530. if (ele.getBoundingClientRect) {
  5531. return ele.getBoundingClientRect().top + document.documentElement.scrollTop;
  5532. }
  5533. var actualTop = ele.offsetTop;
  5534. var current = ele.offsetParent;
  5535. while (current) {
  5536. actualTop += current.offsetTop;
  5537. current = current.offsetParent;
  5538. }
  5539. return actualTop;
  5540. }
  5541.  
  5542. function getElementLeft(ele) {
  5543. if (!ele) return 0;
  5544. if (ele.getBoundingClientRect) {
  5545. return ele.getBoundingClientRect().left + document.documentElement.scrollLeft;
  5546. }
  5547. var actualLeft = ele.offsetLeft;
  5548. var current = ele.offsetParent;
  5549. while (current) {
  5550. actualLeft += current.offsetLeft;
  5551. current = current.offsetParent;
  5552. }
  5553. return actualLeft;
  5554. }
  5555.  
  5556. function getElementBottom(ele) {
  5557. return getElementTop(ele) + (ele.offsetHeight || ele.scrollHeight);
  5558. }
  5559.  
  5560. function getFormatJSON(obj){
  5561. if(!objIsArr(obj) || obj.length === 0)return "";
  5562. return JSON.stringify(obj, null, 4);
  5563. }
  5564.  
  5565. function globMatch(first, second) {
  5566. if (first === '*') {
  5567. return true;
  5568. }
  5569. if (first.length == 0 && second.length == 0){
  5570. return true;
  5571. }
  5572.  
  5573. if (first.length > 1 && first[0] == '*' &&
  5574. second.length == 0){
  5575. return false;
  5576. }
  5577.  
  5578. if ((first.length > 1 && first[0] == '?') ||
  5579. (first.length != 0 && second.length != 0 &&
  5580. first[0] == second[0])){
  5581. return globMatch(first.substring(1),
  5582. second.substring(1));
  5583. }
  5584.  
  5585. if (first.length > 0 && first[0] == '*'){
  5586. return globMatch(first.substring(1), second) ||
  5587. globMatch(first, second.substring(1));
  5588. }
  5589.  
  5590. return false;
  5591. }
  5592.  
  5593. let pageReady = false;
  5594. function initRules(callback) {
  5595. storage.getItem("rulesData", data => {
  5596. /*0 wedata格式,1 pagetual格式*/
  5597. ruleUrls = [{
  5598. id: 1,
  5599. url: data && data.wedata2github ? 'https://hoothin.github.io/UserScripts/Pagetual/items_all.json' : 'http://wedata.net/databases/AutoPagerize/items_all.json',
  5600. type: 0,
  5601. }];
  5602. if (data) {
  5603. rulesData = data;
  5604. if (data.urls) ruleUrls = ruleUrls.concat(data.urls);
  5605. if (data.sort) {
  5606. let urls = [];
  5607. data.sort.forEach(id => {
  5608. for (let s = 0; s < ruleUrls.length; s++) {
  5609. if (id == ruleUrls[s].id) {
  5610. urls.push(ruleUrls[s]);
  5611. break;
  5612. }
  5613. }
  5614. });
  5615. ruleUrls = urls;
  5616. }
  5617. }
  5618. if (rulesData.blacklist && rulesData.blacklist.length > 0) {
  5619. let href = location.href.slice(0, 500);
  5620. for (let i = 0; i < rulesData.blacklist.length; i++) {
  5621. let curGlob = rulesData.blacklist[i];
  5622. if (!curGlob) continue;
  5623. if (curGlob.indexOf("/") == 0) {
  5624. let regMatch = curGlob.match(/^\/(.*)\/(\w*)$/);
  5625. if (regMatch && new RegExp(regMatch[1], regMatch[2]).test(href)) {
  5626. forceState == 1;
  5627. return;
  5628. }
  5629. } else if (globMatch(curGlob, href)) {
  5630. forceState == 1;
  5631. return;
  5632. }
  5633. }
  5634. }
  5635. if (rulesData.lang) {
  5636. setLang(rulesData.lang);
  5637. }
  5638. _GM_registerMenuCommand(i18n("configure"), () => {
  5639. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  5640. });
  5641. _GM_registerMenuCommand(i18n("editCurrent"), () => {
  5642. picker.start();
  5643. });
  5644. ruleParser.initSavedRules(() => {
  5645. let upBtnImg = rulesData.upBtnImg, downBtnImg = rulesData.downBtnImg, _sideControllerIcon = rulesData.sideControllerIcon;
  5646. if (upBtnImg && downBtnImg) {
  5647. downSvgCSS = downSvgCSS.replace("transform: rotate(180deg);", "");
  5648. } else if (upBtnImg && !downBtnImg) {
  5649. downBtnImg = upBtnImg;
  5650. } else if(downBtnImg && !upBtnImg) {
  5651. upBtnImg = downBtnImg;
  5652. }
  5653. if (upBtnImg) {
  5654. upSvg = /https?:|data/.test(upBtnImg) ? `<img class="pagetual" src="${upBtnImg}"/>` : `<span>${upBtnImg}</span>`;
  5655. }
  5656. if (downBtnImg) {
  5657. downSvg = /https?:|data/.test(downBtnImg) ? `<img class="pagetual" src="${downBtnImg}"/>` : `<span>${downBtnImg}</span>`;
  5658. }
  5659. if (_sideControllerIcon) {
  5660. sideControllerIcon = /https?:|data/.test(_sideControllerIcon) ? `<img class="pagetual" src="${_sideControllerIcon}"/>` : `<span>${_sideControllerIcon}</span>`;
  5661. }
  5662. setLoadingDiv(rulesData.loadingText || i18n("loadingText"));
  5663. if (typeof(rulesData.opacity) == "undefined") {
  5664. rulesData.opacity = 1;
  5665. }
  5666. if (typeof(rulesData.hideBar) == "undefined") {
  5667. rulesData.hideBar = false;
  5668. }
  5669. if (typeof(rulesData.dbClick2Stop) == "undefined") {
  5670. rulesData.dbClick2Stop = true;
  5671. }
  5672. if (typeof(rulesData.enableWhiteList) == "undefined") {
  5673. rulesData.enableWhiteList = false;
  5674. }
  5675. if (typeof(rulesData.enableHistory) == "undefined") {
  5676. rulesData.enableHistory = false;
  5677. }
  5678. if (typeof(rulesData.openInNewTab) == "undefined") {
  5679. rulesData.openInNewTab = false;
  5680. }
  5681. if (typeof(rulesData.enableDebug) == "undefined") {
  5682. rulesData.enableDebug = true;
  5683. }
  5684. if (typeof(rulesData.initRun) == "undefined") {
  5685. rulesData.initRun = true;
  5686. }
  5687. if (typeof(rulesData.preload) == "undefined") {
  5688. rulesData.preload = true;
  5689. }
  5690. if (typeof(rulesData.customFirst) == "undefined") {
  5691. rulesData.customFirst = false;
  5692. }
  5693. if (typeof(rulesData.manualMode) == "undefined") {
  5694. rulesData.manualMode = false;
  5695. }
  5696. if (typeof(rulesData.clickMode) == "undefined") {
  5697. rulesData.clickMode = false;
  5698. }
  5699. if (typeof(rulesData.pageBarMenu) == "undefined") {
  5700. rulesData.pageBarMenu = true;
  5701. }
  5702. if (typeof(rulesData.arrowToScroll) == "undefined") {
  5703. rulesData.arrowToScroll = false;
  5704. }
  5705. if (typeof(rulesData.hideLoadingIcon) == "undefined") {
  5706. rulesData.hideLoadingIcon = false;
  5707. }
  5708. if (typeof(rulesData.hideBarArrow) == "undefined") {
  5709. rulesData.hideBarArrow = false;
  5710. }
  5711. if (typeof(rulesData.lastPageTips) == "undefined") {
  5712. rulesData.lastPageTips = true;
  5713. }
  5714. if (rulesData.autoLoadNum && rulesData.initRun) {
  5715. autoLoadNum = parseInt(rulesData.autoLoadNum);
  5716. }
  5717. openInNewTab = rulesData.openInNewTab ? 1 : 0;
  5718. enableDebug = rulesData.enableDebug;
  5719. storage.getItem("nextSwitch_" + location.host, i => {
  5720. storage.getItem("forceState_" + location.host, v => {
  5721. storage.getItem("autoScroll_" + location.host + location.pathname, _autoScroll => {
  5722. storage.getItem("ruleLastUpdate", date => {
  5723. autoScroll = _autoScroll || 0;
  5724. if (typeof(i) !== "undefined") {
  5725. nextIndex = i;
  5726. }
  5727. if (typeof(v) == "undefined") {
  5728. v = (rulesData.enableWhiteList ? 1 : 0);
  5729. }
  5730. forceState = v;
  5731. updateDate = date;
  5732.  
  5733. let href = location.href.slice(0, 100);
  5734. try {
  5735. if (_unsafeWindow.initedPagetual) {
  5736. if (ruleImportUrlReg.test(href)) {
  5737. showTips(i18n('duplicate'));
  5738. }
  5739. return;
  5740. }
  5741. _unsafeWindow.initedPagetual = true;
  5742. } catch(e) {showTips(e)}
  5743. listenUrl();
  5744. _GM_registerMenuCommand(i18n("update"), () => {
  5745. showTips(i18n("beginUpdate"), "", 60000);
  5746. updateRules(() => {
  5747. showTips(i18n("updateSucc"));
  5748. location.reload();
  5749. },(rule, err) => {
  5750. showTips(`Failed to update ${rule.url} rules!`);
  5751. debug(err);
  5752. });
  5753. });
  5754. _GM_registerMenuCommand(i18n(forceState == 1 ? "enable" : "disableSite"), () => {
  5755. forceState = (forceState == 1 ? 0 : 1);
  5756. storage.setItem("forceState_" + location.host, forceState);
  5757. showTips(i18n(forceState == 1 ? "disableSiteTips" : "enableSiteTips"));
  5758. if (!ruleParser.curSiteRule.url) location.reload();
  5759. });
  5760. _GM_registerMenuCommand(i18n("toggleAutoScroll"), () => {
  5761. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), 50)) || 0;
  5762. autoScroll = parseInt(autoScroll) || 0;
  5763. if (autoScroll < 0) autoScroll = 0;
  5764. else if (autoScroll > 1000) autoScroll = 1000;
  5765. storage.setItem("autoScroll_" + location.host + location.pathname, autoScroll);
  5766. startAutoScroll();
  5767. });
  5768. startAutoScroll();
  5769.  
  5770.  
  5771. if (initConfig(href)) return;
  5772. pageReady = true;
  5773. if (forceState == 1) return;
  5774. let now = new Date().getTime();
  5775. if (!date || now - date > 2 * 24 * 60 * 60 * 1000) {
  5776. updateRules(() => {
  5777. }, (rule, err) => {}, true);
  5778. storage.setItem("ruleLastUpdate", now);
  5779. }
  5780. callback();
  5781. });
  5782. });
  5783. });
  5784. });
  5785. });
  5786. });
  5787. }
  5788.  
  5789. function requestDoc(url, callback){
  5790. let postParams = url.match(/#p{(.*)}$/);
  5791. if (postParams) {
  5792. postParams = postParams[1];
  5793. url = url.replace(/#p{.*/, "");
  5794. }
  5795. let ruleHeaders = ruleParser.curSiteRule.headers;
  5796. let headers = {
  5797. 'Referer': location.href,
  5798. 'User-Agent': navigator.userAgent,
  5799. 'accept': 'text/html,application/xhtml+xml,application/xml',
  5800. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + (document.characterSet || document.charset || document.inputEncoding),
  5801. };
  5802. if (ruleHeaders) {
  5803. if (ruleHeaders.referer) {
  5804. headers.referer = ruleHeaders.referer;
  5805. }
  5806. if (ruleHeaders.userAgent) {
  5807. headers.userAgent = ruleHeaders.userAgent;
  5808. }
  5809. if (ruleHeaders.accept) {
  5810. headers.accept = ruleHeaders.accept;
  5811. }
  5812. if (ruleHeaders.contentType) {
  5813. headers.contentType = ruleHeaders.contentType;
  5814. }
  5815. if (ruleHeaders.cookie) {
  5816. headers.cookie = ruleHeaders.cookie;
  5817. }
  5818. }
  5819. _GM_xmlhttpRequest({
  5820. url: url,
  5821. method: postParams ? 'POST' : 'GET',
  5822. data: postParams,
  5823. overrideMimeType: 'text/html;charset=' + (document.characterSet || document.charset || document.inputEncoding),
  5824. headers: headers,
  5825. timeout: 20000,
  5826. onload: async function(res) {
  5827. if (isPause) return callback(false);
  5828. var doc = null, response = res.response;
  5829. let preCode = ruleParser.curSiteRule.pageElementPre || ruleParser.curSiteRule.pagePre;
  5830. if (preCode) {
  5831. try {
  5832. if (typeof _unsafeWindow.pagetualPagePre != 'undefined') {
  5833. response = _unsafeWindow.pagetualPagePre(response);
  5834. } else if (preCode.length == 2) {
  5835. response = response.replace(new RegExp(preCode[0], "gi"), preCode[1]);
  5836. } else {
  5837. response = Function("response",'"use strict";' + preCode)(response);
  5838. }
  5839. } catch(e) {
  5840. debug(e);
  5841. }
  5842. }
  5843. try {
  5844. doc = document.implementation.createHTMLDocument('');
  5845. doc.documentElement.innerHTML = response;
  5846. let base = doc.querySelector("base");
  5847. ruleParser.basePath = base ? base.href : url;
  5848. }
  5849. catch (e) {
  5850. debug('parse error:' + e.toString());
  5851. }
  5852. let pageElement = ruleParser.getPageElement(doc);
  5853. if ((!pageElement || pageElement.length == 0) && res.status >= 400) {
  5854. debug(res.status, "Error status");
  5855. return callback(false);
  5856. }
  5857. if (inCors && (!pageElement || pageElement.length == 0) && ruleParser.curSiteRule.singleUrl) {
  5858. let article = doc.querySelectorAll(mainSel);
  5859. if (article && article.length == 1) {
  5860. article = article[0];
  5861. ruleParser.curSiteRule.pageElement = article.nodeName.toLowerCase() + (article.id ? "#" + article.id : "") + (article.className ? "." + article.className.replace(/ /g, ".") : "") + ">*";
  5862. pageElement = article.children;
  5863. } else {
  5864. ruleParser.curSiteRule.pageElement = allOfBody;
  5865. pageElement = ruleParser.getPageElement(doc);
  5866. }
  5867. ruleParser.getInsert(true);
  5868. }
  5869. //只有1的話怕不是圖片哦
  5870. if (pageElement && (pageElement.length > 1 || (pageElement.length == 1 && !/^IMG$/i.test(pageElement[0].nodeName)))) {
  5871. await ruleParser.insertPage(doc, pageElement, url, callback, false);
  5872. if (ruleParser.curSiteRule.action == 1) {
  5873. isLoading = true;
  5874. requestFromIframe(url, (doc, eles) => {
  5875. if (eles) {
  5876. ruleParser.insertPage(doc, eles, url, callback, true);
  5877. } else isLoading = false;
  5878. });
  5879. } else ruleParser.curSiteRule.action = 0;
  5880. } else if ((ruleParser.curSiteRule.singleUrl || curPage == 1) && !inCors) {
  5881. ruleParser.curSiteRule.action = 1;
  5882. requestFromIframe(url, (doc, eles) => {
  5883. if (eles) {
  5884. ruleParser.insertPage(doc, eles, url, callback, true);
  5885. } else isLoading = false;
  5886. });
  5887. } else {
  5888. debug("Stop as no page element");
  5889. ruleParser.noValidContent(url);
  5890. isPause = true;
  5891. callback(false);
  5892. }
  5893. },
  5894. onerror: function(e) {
  5895. debug(e, "NetError");
  5896. callback(false);
  5897. },
  5898. ontimeout: function(e) {
  5899. debug(e, "NetTimeout");
  5900. callback(false);
  5901. }
  5902. });
  5903. }
  5904.  
  5905. function initPage() {
  5906. ruleParser.initPage(() => {
  5907. if (ruleParser.curSiteRule.autoLoadNum) {
  5908. autoLoadNum = ruleParser.curSiteRule.autoLoadNum;
  5909. }
  5910. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  5911. _GM_registerMenuCommand(i18n("nextSwitch"), () => {
  5912. nextSwitch.start();
  5913. });
  5914. }
  5915. if (ruleParser.nextLinkHref) {
  5916. let isJs = ruleParser.hrefIsJs(ruleParser.nextLinkHref);
  5917. if (!isJs) {
  5918. let inForce = (forceState == 2 || forceState == 3);
  5919. _GM_registerMenuCommand(i18n(inForce ? "cancelForceIframe" : "forceIframe"), () => {
  5920. if (inForce) {
  5921. storage.setItem("forceState_" + location.host, "");
  5922. } else {
  5923. let _state = ruleParser.curSiteRule.action > 0 || confirm(i18n("forceAllBody")) ? 2 : 3;
  5924. storage.setItem("forceState_" + location.host, _state);
  5925. }
  5926. location.reload();
  5927. });
  5928. }
  5929. _GM_registerMenuCommand(i18n("loadNow"), () => {
  5930. let loadNum = window.prompt(i18n("loadConfirm"), "1");
  5931. if (loadNum === "" || loadNum === null) return;
  5932. autoLoadNum = Math.abs(parseInt(loadNum));
  5933. nextPage();
  5934. });
  5935. }
  5936. initListener();
  5937. });
  5938. }
  5939.  
  5940. var pageBarStyle, mainStyleEle, mainStyleStyle;
  5941. function initView() {
  5942. if (!mainStyleStyle) {
  5943. mainStyleStyle = `
  5944. .pagetual_pageBar{
  5945. -moz-transition:all 0.3s ease-in-out 0s;
  5946. -webkit-transition:all 0.3s ease-in-out 0s;
  5947. transition:all 0.3s ease-in-out 0s;
  5948. font-family: Arial,sans-serif !important;
  5949. text-align: center !important;
  5950. }
  5951. .pagetual_pageBar.stop {
  5952. -webkit-filter: invert(100%);
  5953. filter: invert(100%);
  5954. opacity: 1!important;
  5955. }
  5956. .pagetual_pageBar.hide {
  5957. display: none!important;
  5958. }
  5959. .pagetual-hide {
  5960. display: none!important;
  5961. }
  5962. .pagetual_pageBar:hover {
  5963. opacity: 1!important;
  5964. box-shadow: 0px 0px 10px 0px #000000aa;
  5965. border-radius: 20px;
  5966. background-color: rgb(240 240 240 / 80%);
  5967. border-color: transparent!important;
  5968. }
  5969. .pagetual_pageBar span {
  5970. vertical-align: super;
  5971. }
  5972. .pagetual_pageBar a::before,
  5973. .pagetual_pageBar a::after {
  5974. content: none;
  5975. }
  5976. .pagetual_pageBar a>span {
  5977. margin-top: 0!important;
  5978. pointer-events: none;
  5979. padding: unset;
  5980. opacity: 0;
  5981. -moz-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  5982. -webkit-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  5983. transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  5984. transform: none;
  5985. left: 0;
  5986. margin-left: calc(50% - 20px);
  5987. }
  5988. .pagetual_pageBar a>span:hover {
  5989. color: red;
  5990. }
  5991. .pagetual_pageBar a:hover>span {
  5992. opacity: 1;
  5993. }
  5994. .pagetual_pageBar span.prevScreen,
  5995. .pagetual_pageBar span.nextScreen {
  5996. display: block!important;
  5997. }
  5998. .pagetual_pageBar a:hover>span.prevScreen {
  5999. margin-top: -${rulesData.opacity == 1 ? 31 : 30}px!important;
  6000. pointer-events: all;
  6001. }
  6002. .pagetual_pageBar a:hover>span.nextScreen {
  6003. margin-top: 30px!important;
  6004. pointer-events: all;
  6005. }
  6006. .pagetual_pageBar span>svg {
  6007. -moz-transition:transform 0.5s ease, opacity 0.3s ease;
  6008. -webkit-transition:transform 0.5s ease, opacity 0.3s ease;
  6009. transition:transform 0.5 ease, opacity 0.3s ease;
  6010. opacity: 0;
  6011. }
  6012. .pagetual_pageBar.stop span>svg{
  6013. opacity: 1;
  6014. }
  6015. .pagetual_pageBar.stop span>svg>path{
  6016. transform: scale(.8);
  6017. transform-origin: center;
  6018. -moz-transition:transform 0.3s ease;
  6019. -webkit-transition:transform 0.3s ease;
  6020. transition:transform 0.3 ease;
  6021. }
  6022. .pagetual_pageBar.stop:hover span>svg>path{
  6023. transform: unset;
  6024. }
  6025. .pagetual_pageBar:hover span>svg {
  6026. opacity: 1;
  6027. }
  6028. .pagetual_pageBar span>svg.upSvg:hover {
  6029. transform: rotate(360deg) scale3d(1.2, 1.2, 1.2);
  6030. }
  6031. .pagetual_pageBar span>svg.downSvg:hover {
  6032. transform: rotate(540deg) scale3d(1.2, 1.2, 1.2)!important;
  6033. }
  6034. .pagetual_pageBar .pagetual_pageNum{
  6035. color: #55555f;
  6036. }
  6037. .pagetual_pageBar .pagetual_pageNum:hover{
  6038. color: #ff6464;
  6039. }
  6040. .pagetual_tipsWords {
  6041. font-size: 50px;
  6042. font-weight: bold;
  6043. font-family: "黑体", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
  6044. "Oxygen", "Ubuntu", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
  6045. "Segoe UI Emoji", "Segoe UI Symbol";
  6046. color: #ffffff;
  6047. min-height: 70px;
  6048. max-width: 80%;
  6049. line-height: 70px;
  6050. position: fixed;
  6051. left: 50%;
  6052. top: 10%;
  6053. margin-left: -99999px;
  6054. padding: 0 15px;
  6055. z-index: 2147483647;
  6056. background-color: #000;
  6057. border: 1px solid #303030;
  6058. border-radius: 10px;
  6059. opacity: 0;
  6060. filter: alpha(opacity=65);
  6061. box-shadow: 5px 5px 20px 0px #000;
  6062. -moz-transition:opacity 0.3s ease-in-out 0s;
  6063. -webkit-transition:opacity 0.3s ease-in-out 0s;
  6064. transition:opacity 0.3s ease-in-out 0s;
  6065. pointer-events: none;
  6066. }
  6067. .pagetual_tipsWords>a {
  6068. color: #ffffff;
  6069. }
  6070. .pagetual_loading {
  6071. width: 50px;
  6072. height: 50px;
  6073. margin: 10px auto;
  6074. border-radius: 100%;
  6075. display: flex;
  6076. -webkit-animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  6077. animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  6078. }
  6079. @-webkit-keyframes pagetual_loading_scaleout {
  6080. 0% { -webkit-transform: scale(0.0) }
  6081. 100% {
  6082. -webkit-transform: scale(1.0);
  6083. opacity: 0;
  6084. }
  6085. }
  6086. @keyframes pagetual_loading_scaleout {
  6087. 0% {
  6088. transform: scale(0.0);
  6089. -webkit-transform: scale(0.0);
  6090. } 100% {
  6091. transform: scale(1.0);
  6092. -webkit-transform: scale(1.0);
  6093. opacity: 0;
  6094. }
  6095. }
  6096. .pagetual_loading_text {
  6097. white-space: nowrap;
  6098. -webkit-animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  6099. animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  6100. }
  6101. @-webkit-keyframes pagetual_loading_opacity {
  6102. 0% { opacity: 1 }
  6103. 50% { opacity: 0.2 }
  6104. 100% { opacity: 1 }
  6105. }
  6106. @keyframes pagetual_loading_opacity {
  6107. 0% { opacity: 1 }
  6108. 50% { opacity: 0.2 }
  6109. 100% { opacity: 1 }
  6110. }
  6111. `;
  6112. let bodyColor
  6113. 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%);"}`;
  6114. }
  6115. if (!mainStyleEle || !mainStyleEle.parentNode) {
  6116. mainStyleEle = _GM_addStyle(mainStyleStyle);
  6117. }
  6118. }
  6119. var loadingDiv = document.createElement("div");
  6120. 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;";
  6121.  
  6122. const loadingCSS = `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;`;
  6123. function setLoadingDiv(loadingText) {
  6124. 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" 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" fill="#6e6e6e"></path></svg></div>`}`);
  6125. }
  6126.  
  6127. 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" 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>`;
  6128. 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;`;
  6129. 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" 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>`;
  6130. 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);`;
  6131.  
  6132. 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;`;
  6133. 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;`;
  6134. var sideControllerIcon = '';
  6135.  
  6136. var tipsWords = document.createElement("div");
  6137. tipsWords.className = "pagetual_tipsWords";
  6138.  
  6139. var isPause = false, isHideBar = false, isLoading = false, curPage = 1, forceState = 0, autoScroll = 0, autoScrollInterval, bottomGap = 1000, autoLoadNum = -1, nextIndex = 0, stopScroll = false, clickMode = false;
  6140. var openInNewTab = 0;
  6141.  
  6142. function changeStop(stop) {
  6143. isPause = stop;
  6144. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar,#pagetual-sideController"), bar => {
  6145. if (isPause) {
  6146. bar.classList.add("stop");
  6147. } else {
  6148. bar.classList.remove("stop");
  6149. }
  6150. });
  6151. if (!isPause) ruleParser.showAddedElements();
  6152. }
  6153.  
  6154. function changeHideBar(hide) {
  6155. isHideBar = hide;
  6156. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar"), bar => {
  6157. if (isHideBar) {
  6158. bar.classList.add("hide");
  6159. } else {
  6160. bar.classList.remove("hide");
  6161. }
  6162. });
  6163. }
  6164.  
  6165. function isInViewPort(element) {
  6166. if (!getBody(document).contains(element)) return false;
  6167. if (_unsafeWindow.getComputedStyle(element).display == "none") return false;
  6168. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  6169. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  6170. const {
  6171. top,
  6172. right,
  6173. bottom,
  6174. left,
  6175. } = element.getBoundingClientRect();
  6176.  
  6177. return (
  6178. top >= 0 &&
  6179. left >= 0 &&
  6180. right <= viewWidth + 1 &&
  6181. top <= viewHeight * (ruleParser.curSiteRule.rate || rulesData.rate || 1)
  6182. );
  6183. }
  6184.  
  6185. function getPageBar() {
  6186. let preBar = null, nextBar = null;
  6187. let pageBars = [].slice.call(document.querySelectorAll(".pagetual_pageBar"));
  6188. for (let i = 0; i < pageBars.length; i++) {
  6189. let pageBar = pageBars[i];
  6190. if (!pageBar || !getBody(document).contains(pageBar)) continue;
  6191. let {
  6192. top,
  6193. right,
  6194. bottom,
  6195. left,
  6196. } = pageBar.getBoundingClientRect();
  6197. if (top > 500) {
  6198. nextBar = pageBar;
  6199. preBar = (i - 1 >= 0 ? pageBars[i - 1] : null);
  6200. if (pageBar && getBody(document).contains(pageBar)) {
  6201. let {
  6202. top,
  6203. right,
  6204. bottom,
  6205. left,
  6206. } = pageBar.getBoundingClientRect();
  6207. if (top < -500) {
  6208. preBar = pageBar;
  6209. } else preBar = (i - 2 >= 0 ? pageBars[i - 2] : null);
  6210. }
  6211. break;
  6212. }
  6213. }
  6214. if (!nextBar) preBar = pageBars[pageBars.length - 2];
  6215. return {preBar: preBar, nextBar: nextBar};
  6216. }
  6217.  
  6218. var urlChanged = false;
  6219. var urlChanging = false;
  6220. var urlchangeHandler = e => {
  6221. if (ruleParser && ruleParser.curSiteRule && ruleParser.curSiteRule.listenUrlChange == false) return;
  6222. isPause = true;
  6223. setTimeout(() => {
  6224. lastActiveUrl = location.href;
  6225. if (urlChanging) return;
  6226. urlChanging = true;
  6227. let href = location.href.slice(0, 60);
  6228. if (href == configPage[0]) {
  6229. setTimeout(() => {
  6230. initConfig(href);
  6231. urlChanging = false;
  6232. }, 1000);
  6233. } else {
  6234. setTimeout(() => {
  6235. if (guidePage.test(href)) {
  6236. setTimeout(() => {
  6237. initConfig(href);
  6238. urlChanging = false;
  6239. }, 1000);
  6240. } else {
  6241. urlChanged = true;
  6242. if (!ruleParser.nextLinkHref) {
  6243. isLoading = false;
  6244. }
  6245. urlChanging = false;
  6246. //if (!pageReady && !ruleImportUrlReg.test(href)) location.reload();
  6247. }
  6248. }, 500);
  6249. }
  6250. }, 1);
  6251. };
  6252. window.addEventListener('pagetual_pushState', urlchangeHandler);
  6253. /*var _wr = function(type) {
  6254. var orig = history[type];
  6255. return function() {
  6256. var rv = orig.apply(this, arguments);
  6257. var e = new Event('pagetual_' + type);
  6258. e.arguments = arguments;
  6259. window.dispatchEvent(e);
  6260. return rv;
  6261. };
  6262. };
  6263. history.pushState = _wr('pushState');*/
  6264.  
  6265. function listenUrl() {
  6266. var prevPathname = window.location.pathname;
  6267. var prevSearch = window.location.search;
  6268. var checkUrlTime = 100;
  6269. var checkUrlTimer;
  6270. var checkFunc = () => {
  6271. if (forceState == 1) return;
  6272. if (checkUrlTime < 5000) {
  6273. checkUrlTime += checkUrlTime>>1;
  6274. }
  6275. clearTimeout(checkUrlTimer);
  6276. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  6277. if (document.hidden) return;
  6278. if ((prevPathname !== window.location.pathname || prevSearch !== window.location.search) && window.location.href != ruleParser.historyUrl) {
  6279. checkUrlTime = 2000;
  6280. prevPathname = window.location.pathname;
  6281. prevSearch = window.location.search;
  6282. var e = new Event('pagetual_pushState');
  6283. e.arguments = arguments;
  6284. window.dispatchEvent(e);
  6285. }
  6286. };
  6287. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  6288.  
  6289. document.addEventListener("click", e => {
  6290. checkUrlTime = 100;
  6291. clearTimeout(checkUrlTimer);
  6292. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  6293. });
  6294. }
  6295.  
  6296. function distToBottom () {
  6297. let scrolly = window.scrollY;
  6298. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  6299. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  6300. return scrollH - scrolly - windowHeight;
  6301. }
  6302.  
  6303. let scrollHandler, clickToResetHandler, dblclickHandler, keydownHandler, hashchangeHandler, manualModeKeyHandler, pagetualNextHandler, keyupHandler;
  6304. function initListener () {
  6305. document.removeEventListener('scroll', scrollHandler, true);
  6306. document.removeEventListener('wheel', scrollHandler, true);
  6307. document.removeEventListener('dblclick', dblclickHandler);
  6308. document.removeEventListener('keydown', keydownHandler);
  6309. window.removeEventListener('hashchange', hashchangeHandler, false);
  6310. document.removeEventListener('keydown', manualModeKeyHandler);
  6311. document.removeEventListener('pagetual.next', pagetualNextHandler, false);
  6312. document.removeEventListener('keyup', keyupHandler);
  6313. let loadmoreBtn, loadingMore = true, lastScroll = 0, checkLoadMoreTimes = 0;
  6314. if (ruleParser.curSiteRule.singleUrl) {
  6315. loadingMore = false;
  6316. } else if (ruleParser.curSiteRule.loadMore) {
  6317. loadingMore = false;
  6318. }
  6319. clickMode = typeof ruleParser.curSiteRule.clickMode == 'undefined' ? rulesData.clickMode : ruleParser.curSiteRule.clickMode;
  6320. let clickingNext = false;
  6321. let clickNext = async () => {
  6322. if (clickingNext) return;
  6323. clickingNext = true;
  6324. setTimeout(() => {
  6325. clickingNext = false;
  6326. }, 1500);
  6327. let nextLink = ruleParser.nextLinkHref;
  6328. if (!nextLink) return;
  6329. let isJs = ruleParser.hrefIsJs(nextLink);
  6330. if (isJs) {
  6331. let nextBtn = ruleParser.nextLinkEle;
  6332. if (!nextBtn || !nextBtn.offsetParent) nextBtn = await ruleParser.getNextLink(document, true);
  6333. if (nextBtn) emuClick(nextBtn);
  6334. } else {
  6335. window.location.href = nextLink;
  6336. }
  6337. };
  6338. let checkScrollReach = () => {
  6339. let dist = distToBottom();
  6340. if (clickMode) {
  6341. if (dist < 10) {
  6342. clickNext();
  6343. }
  6344. } else if (dist < bottomGap) {
  6345. nextPage();
  6346. }
  6347. };
  6348. scrollHandler = e => {
  6349. if (urlChanged && !isLoading) {
  6350. ruleParser.initPage(() => {});
  6351. urlChanged = false;
  6352. loadingMore = false;
  6353. }
  6354. if (isPause) return;
  6355. if (!loadingMore) {
  6356. loadmoreBtn = getLoadMore(document, loadmoreBtn);
  6357. if (loadmoreBtn) {
  6358. if (isInViewPort(loadmoreBtn)) {
  6359. emuClick(loadmoreBtn);
  6360. loadingMore = true;
  6361. setTimeout(() => {loadingMore = false}, 200);
  6362. }
  6363. } else {
  6364. loadingMore = true;
  6365. if (!ruleParser.curSiteRule.singleUrl || checkLoadMoreTimes++ < 3) {
  6366. setTimeout(() => {loadingMore = false}, 200);
  6367. }
  6368. }
  6369. }
  6370. if (!isLoading && !stopScroll) {
  6371. checkScrollReach();
  6372. }
  6373. ruleParser.changeVisibility();
  6374. if (ruleParser.curSiteRule.lockScroll) {
  6375. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  6376. if (isLoading && Math.abs(lastScroll - curScroll) > 350) {
  6377. getBody(document).scrollTop = lastScroll;
  6378. document.documentElement.scrollTop = lastScroll;
  6379. } else {
  6380. lastScroll = curScroll;
  6381. }
  6382. }
  6383. };
  6384. dblclickHandler = e => {
  6385. if (forceState == 1 || /^(INPUT|TEXTAREA|SELECT)$/i.test(e.target.nodeName)) return;
  6386. if (!rulesData.dbClick2StopKey) {
  6387. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  6388. (rulesData.dbClick2StopAlt && !e.altKey) ||
  6389. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  6390. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  6391. return;
  6392. }
  6393. }
  6394. if (!/^BODY$/i.test(e.target.nodeName) && !e.target.classList.contains('pagetual_pageBar')) {
  6395. try {
  6396. let selection = window.getSelection();
  6397. let selStr = selection.toString().trim();
  6398. if (!selStr) {
  6399. selection = selection.getRangeAt(0);
  6400. selStr = selection && selection.cloneContents().children[0];
  6401. if (selStr && !/^IMG$/i.test(selStr.nodeName)) selStr = false;
  6402. }
  6403. if (selStr) {
  6404. return;
  6405. }
  6406. } catch (e) {}
  6407. }
  6408. if (rulesData.dbClick2Stop && (ruleParser.nextLinkHref || loadmoreBtn)) {
  6409. setTimeout(() => {
  6410. if (rulesData.hideBarButNoStop || rulesData.hideBar) {
  6411. changeHideBar(!isHideBar);
  6412. }
  6413. if (!rulesData.hideBarButNoStop) {
  6414. changeStop(!isPause);
  6415. showTips(i18n(isPause ? "disable" : "enable"));
  6416. }
  6417. if (!isPause) {
  6418. checkScrollReach();
  6419. }
  6420. }, 10);
  6421. }
  6422. };
  6423. document.addEventListener('dblclick', dblclickHandler);
  6424. clickToResetHandler = e => {
  6425. if (!ruleParser.nextLinkHref) isLoading = false;
  6426. };
  6427. document.addEventListener('click', clickToResetHandler);
  6428. if (rulesData.dbClick2StopKey) {
  6429. keydownHandler = e => {
  6430. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  6431. (rulesData.dbClick2StopAlt && !e.altKey) ||
  6432. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  6433. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  6434. return;
  6435. }
  6436. if (document.activeElement &&
  6437. (/^(INPUT|TEXTAREA)$/i.test(document.activeElement.nodeName) ||
  6438. document.activeElement.contentEditable == 'true')) {
  6439. return;
  6440. }
  6441. var key = e.key.toLowerCase();
  6442. if (rulesData.dbClick2StopKey.toLowerCase() == key) {
  6443. forceState = (forceState == 1 ? 0 : 1);
  6444. showTips(i18n(forceState == 1 ? "disableSiteTips" : "enableSiteTips"));
  6445. if (!ruleParser.curSiteRule.url) {
  6446. storage.setItem("forceState_" + location.host, forceState);
  6447. location.reload();
  6448. }
  6449. }
  6450. };
  6451. document.addEventListener('keydown', keydownHandler);
  6452. }
  6453. if (ruleParser.curSiteRule.listenHashChange) {
  6454. hashchangeHandler = () => {
  6455. isPause = true;
  6456. urlChanged = true;
  6457. if (!ruleParser.nextLinkHref) isLoading = false;
  6458. };
  6459. window.addEventListener('hashchange', hashchangeHandler, false);
  6460. }
  6461. let manualMode = typeof ruleParser.curSiteRule.manualMode == 'undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode;
  6462. if (manualMode) {
  6463. manualModeKeyHandler = e => {
  6464. if (document.activeElement &&
  6465. (/^(INPUT|TEXTAREA)$/i.test(document.activeElement.nodeName) ||
  6466. document.activeElement.contentEditable == 'true')) {
  6467. return;
  6468. }
  6469. if (e.keyCode == 39) {
  6470. clickNext();
  6471. } else if (e.keyCode == 37) {
  6472. history.back();
  6473. }
  6474. };
  6475. document.addEventListener('keydown', manualModeKeyHandler);
  6476. pagetualNextHandler = () => {
  6477. clickNext();
  6478. };
  6479. document.addEventListener('pagetual.next', pagetualNextHandler, false);
  6480. return;
  6481. }
  6482. if (rulesData.arrowToScroll) {
  6483. keyupHandler = e => {
  6484. if (document.activeElement &&
  6485. (/^(INPUT|TEXTAREA)$/i.test(document.activeElement.nodeName) ||
  6486. document.activeElement.contentEditable == 'true')) {
  6487. return;
  6488. }
  6489. if (e.keyCode == 39) {
  6490. let nextPageBar=getPageBar().nextBar;
  6491. if (nextPageBar) {
  6492. scrollToPageBar(nextPageBar);
  6493. } else {
  6494. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  6495. window.scrollTo({ top: scrollTop + (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  6496. }
  6497. } else if (e.keyCode == 37) {
  6498. let prePageBar = getPageBar().preBar;
  6499. if (prePageBar) {
  6500. scrollToPageBar(prePageBar);
  6501. } else {
  6502. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  6503. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  6504. }
  6505. }
  6506. };
  6507. document.addEventListener('keyup', keyupHandler);
  6508. }
  6509. if (!ruleParser.curSiteRule.wheel) {
  6510. document.addEventListener('scroll', scrollHandler, true);
  6511. }
  6512. document.addEventListener('wheel', scrollHandler, true);
  6513. }
  6514.  
  6515. let hideTipsTimeout;
  6516. function showTips(content, href, time, wordColor, backColor) {
  6517. initView();
  6518. getBody(document).appendChild(tipsWords);
  6519. tipsWords.style.color = wordColor || 0xFFFFFF;
  6520. tipsWords.style.backgroundColor = backColor || 0x000;
  6521. let _time = 1500;
  6522. if (href) {
  6523. _time = 3500;
  6524. tipsWords.innerHTML = createHTML(`<a href='${href}'>${content}</a>`);
  6525. tipsWords.style.pointerEvents = 'all';
  6526. } else {
  6527. tipsWords.innerHTML = createHTML(content);
  6528. }
  6529. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  6530. setTimeout(() => {
  6531. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  6532. }, 0);
  6533. setTimeout(() => {
  6534. tipsWords.style.opacity = 0.8;
  6535. clearTimeout(hideTipsTimeout);
  6536. hideTipsTimeout = setTimeout(() => {
  6537. tipsWords.style.opacity = 0;
  6538. tipsWords.style.pointerEvents = '';
  6539. }, time || _time);
  6540. }, 1);
  6541. }
  6542.  
  6543. const loadmoreReg = /^\s*((点击)?加载更多|(點擊)?加載更多|load\s*more|もっと読み込む)[.…]*\s*$/i;
  6544. const defaultLoadmoreSel = ".loadMore,.LoadMore,[class*='load-more'],button.show_more,.button-show-more,button[data-testid='more-results-button'],#btn_preview_remain";
  6545. function getLoadMore(doc, loadmoreBtn) {
  6546. if (!loadmoreBtn || !getBody(doc).contains(loadmoreBtn) || /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  6547. if (!ruleParser.curSiteRule.singleUrl && !ruleParser.curSiteRule.loadMore) return null;
  6548. if (loadmoreBtn) return loadmoreBtn;
  6549. let btnSel = ruleParser.curSiteRule.loadMore || defaultLoadmoreSel;
  6550. if (btnSel) {
  6551. loadmoreBtn = getElement(btnSel, doc, null, true);
  6552. }
  6553. if (!loadmoreBtn) {
  6554. let buttons = doc.querySelectorAll("input,button,a,div[onclick]");
  6555. for (let i = 0; i < buttons.length; i++) {
  6556. let button = buttons[i];
  6557. if (!button.innerText || button.innerText.length > 20) continue;
  6558. if (button && loadmoreReg.test(button.innerText)) {
  6559. loadmoreBtn = button;
  6560. break;
  6561. }
  6562. }
  6563. }
  6564. if (loadmoreBtn && !ruleParser.curSiteRule.loadMore && loadmoreBtn.dataset.ajax !== "true") {
  6565. let href = loadmoreBtn.getAttribute("href");
  6566. if (href && href != "/" && !ruleParser.hrefIsJs(href)) {
  6567. loadmoreBtn = null;
  6568. }
  6569. }
  6570. if (loadmoreBtn && /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  6571. return loadmoreBtn;
  6572. }
  6573.  
  6574. function scrollToPageBar(bar){
  6575. let yOffset = -20;
  6576. if (typeof ruleParser.curSiteRule.pageBarTop !== 'undefined') {
  6577. yOffset = -ruleParser.curSiteRule.pageBarTop;
  6578. }
  6579. const y = bar.getBoundingClientRect().top + window.pageYOffset + yOffset;
  6580. window.scrollTo({ top: y, behavior: 'smooth'});
  6581. }
  6582.  
  6583. const pageNumReg=/[&\/\?](p=|page[=\/_-]?)\d+|[_-]\d+\./;
  6584. function createPageBar(url) {
  6585. curPage++;
  6586. sideController.setup();
  6587. let posEle = null;
  6588. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  6589. let insert = ruleParser.getInsert();
  6590. if (!insert || !insert.parentNode) return;
  6591. if (forceState == 2) {
  6592. posEle = getBody(document);
  6593. posEle = posEle.children[posEle.children.length - 1];
  6594. } else {
  6595. posEle = insert;
  6596. }
  6597. while (posEle && !posEle.offsetParent) {
  6598. posEle = posEle.previousElementSibling || posEle.parentNode;
  6599. }
  6600. if (posEle) {
  6601. let actualBottom = getElementBottom(posEle);
  6602. bottomGap = scrollH - actualBottom + (window.innerHeight || document.documentElement.clientHeight) * (ruleParser.curSiteRule.rate || rulesData.rate || 1);
  6603. if (bottomGap < 100) bottomGap = 100;
  6604. } else {
  6605. bottomGap = 1000;
  6606. }
  6607. if (rulesData.opacity == 0 || ruleParser.curSiteRule.pageBar === 0) return null;
  6608. url = url.replace(/#p{.*/, "");
  6609. let example = ruleParser.curSiteRule.insertPos == 2 ? insert.children[0] : (insert.parentNode.children[0] || insert);
  6610. while (example && (/^(SCRIPT|STYLE)$/i.test(example.nodeName) || example.className == "pagetual_pageBar")) {
  6611. example = example.nextElementSibling;
  6612. }
  6613. if (!example || !example.parentNode) example = insert;
  6614. if (example.nodeType != 1) {
  6615. example = example.previousElementSibling || example.parentNode;
  6616. if (!example || example.nodeType != 1) return;
  6617. }
  6618. let exampleStyle = _unsafeWindow.getComputedStyle(example);
  6619. let inTable, inLi;
  6620. if (forceState == 2) {
  6621. inTable = inLi = false;
  6622. } else {
  6623. inTable = /^(TABLE|TBODY)$/i.test(example.parentNode.nodeName) ||
  6624. /^(TR|TBODY)$/i.test(example.nodeName) ||
  6625. exampleStyle.display == "table-row" ||
  6626. (example.nextElementSibling && /^(TR|TBODY)$/i.test(example.nextElementSibling.nodeName));
  6627. inLi = /^LI$/i.test(example.nodeName) || (example.nextElementSibling && /^LI$/i.test(example.nextElementSibling.nodeName));
  6628. }
  6629. let pageBar = document.createElement(inTable ? "tr" : (inLi ? "li" : "div"));
  6630. let upSpan = document.createElement("span");
  6631. let downSpan = document.createElement("span");
  6632. let pageText = document.createElement("a");
  6633. let pageNum;
  6634. pageBar.className = isHideBar ? "pagetual_pageBar hide" : "pagetual_pageBar";
  6635. pageBar.id = "pagetual_pageBar" + curPage;
  6636. pageBar.setAttribute("translate", "no");
  6637. if (isPause) {
  6638. pageBar.classList.add("stop");
  6639. }
  6640. pageBar.style.cssText = pageBarStyle;
  6641. pageBar.title = i18n(isPause ? "enable" : "disable");
  6642. upSpan.innerHTML = upSvg;
  6643. upSpan.children[0].style.cssText = upSvgCSS;
  6644. upSpan.title = i18n("toTop");
  6645. downSpan.innerHTML = downSvg;
  6646. downSpan.children[0].style.cssText = downSvgCSS;
  6647. downSpan.title = i18n("toBottom");
  6648. upSpan.style.cssText = initStyle;
  6649. downSpan.style.cssText = initStyle;
  6650. pageText.href = url;
  6651. pageText.style.cssText = pageTextStyle;
  6652. pageText.title = i18n("current");
  6653. if (openInNewTab == 1) pageText.target = "_blank";
  6654. pageBar.appendChild(upSpan);
  6655. pageBar.appendChild(pageText);
  6656. if (rulesData.pageBarMenu) {
  6657. pageText.addEventListener("click", e => {
  6658. e.stopPropagation();
  6659. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  6660. e.preventDefault();
  6661. picker.start();
  6662. });
  6663. }
  6664. let touched = false;
  6665. let touchBodyHandler = e => {
  6666. touched = false;
  6667. getBody(document).removeEventListener('touchstart', touchBodyHandler, { passive: false, capture: false });
  6668. };
  6669. pageText.addEventListener("touchstart", e => {
  6670. if (touched) return;
  6671. touched = true;
  6672. pageText.style.pointerEvents = 'none';
  6673. setTimeout(() => {
  6674. pageText.style.pointerEvents = 'all';
  6675. }, 250);
  6676. getBody(document).addEventListener("touchstart", touchBodyHandler, { passive: false, capture: false });
  6677. }, { passive: false, capture: false });
  6678. if (ruleParser.nextTitle) {
  6679. pageText.innerHTML = ruleParser.nextTitle + " ";
  6680. pageText.title = ruleParser.nextTitle;
  6681. }
  6682. if (ruleParser.curSiteRule.pageNum || pageNumReg.test(url)) {
  6683. pageText.innerHTML += i18n("page");
  6684. pageNum = document.createElement("span");
  6685. let num = ruleParser.getPageNumFromUrl(url, curPage);
  6686. pageNum.innerHTML = num;
  6687. pageNum.className = "pagetual_pageNum";
  6688. pageNum.title = i18n("inputPageNum");
  6689. pageNum.style.cssText = pageTextStyle;
  6690. pageNum.style.cursor = "pointer";
  6691. pageNum.style.color = "";
  6692. pageNum.style.marginLeft = "5px";
  6693. pageNum.addEventListener("click", e => {
  6694. let pageInput = prompt(i18n("inputPageNum"), num || "1");
  6695. if (pageInput) {
  6696. let localPageBar = document.querySelector("#pagetual_pageBar" + pageInput);
  6697. if (localPageBar) {
  6698. scrollToPageBar(localPageBar);
  6699. } else {
  6700. let pageLink = ruleParser.getLinkByPage(url, pageInput);
  6701. if (pageLink) {
  6702. _GM_openInTab(pageLink, {active:true});
  6703. }
  6704. }
  6705. }
  6706. e.preventDefault();
  6707. e.stopPropagation();
  6708. });
  6709. pageBar.appendChild(pageNum);
  6710. } else {
  6711. pageText.innerHTML += i18n("page") + curPage;
  6712. }
  6713. let preBtn = document.createElement("span");
  6714. preBtn.innerHTML = "∧";
  6715. preBtn.title = i18n("prevPage");
  6716. preBtn.className = "prevScreen";
  6717. 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; ";
  6718. let nextBtn = document.createElement("span");
  6719. nextBtn.innerHTML = "∨";
  6720. nextBtn.title = i18n("nextPage");
  6721. nextBtn.className = "nextScreen";
  6722. 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; ";
  6723. let localPage = curPage;
  6724. preBtn.addEventListener("click", e => {
  6725. e.stopPropagation();
  6726. e.preventDefault();
  6727. let prePageBar = document.querySelector("#pagetual_pageBar" + (localPage - 1));
  6728. if (prePageBar) {
  6729. scrollToPageBar(prePageBar);
  6730. } else {
  6731. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  6732. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  6733. }
  6734. });
  6735. nextBtn.addEventListener("click", e => {
  6736. e.stopPropagation();
  6737. e.preventDefault();
  6738. let nextPageBar = document.querySelector("#pagetual_pageBar" + (localPage + 1));
  6739. if (nextPageBar) {
  6740. scrollToPageBar(nextPageBar);
  6741. } else {
  6742. scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  6743. window.scrollTo({ top: scrollH || 9999999, behavior: 'smooth'});
  6744. }
  6745. });
  6746. if (!rulesData.hideBarArrow) {
  6747. pageText.insertBefore(preBtn, pageText.firstChild);
  6748. pageText.insertBefore(nextBtn, pageText.firstChild);
  6749. }
  6750. pageBar.appendChild(downSpan);
  6751. if (forceState == 2) {
  6752. pageBar.style.width = "99%";
  6753. } else {
  6754. let parentStyle = _unsafeWindow.getComputedStyle(example.parentNode);
  6755. let parentWidth = example.parentNode.offsetWidth || parseInt(parentStyle.width);
  6756. pageBar.style.width = parentWidth - parseInt(parentStyle.paddingLeft) - parseInt(parentStyle.paddingRight) - 10 + "px";
  6757. pageBar.style.margin = '10px 5px';
  6758. if (parentStyle.display == "grid" || parentStyle.display == "inline-grid") {
  6759. pageBar.style.gridColumn = "1/-1";
  6760. }
  6761. if (inTable) {
  6762. example = (/^(TR|TBODY)$/i.test(example.nodeName)) ? example : example.nextElementSibling || example;
  6763. if (/^TBODY$/i.test(example.nodeName)) example = example.querySelector("tr");
  6764. let nextTr = example;
  6765. while (nextTr && nextTr.children.length == 0) nextTr = nextTr.nextElementSibling;
  6766. if (nextTr) example = nextTr;
  6767. let tdNum = 0;
  6768. if (exampleStyle.display == "table-row") {
  6769. [].forEach.call(example.children, el => {
  6770. tdNum += el.colSpan || 1;
  6771. });
  6772. } else {
  6773. [].forEach.call(example.children, el => {
  6774. if (/^(TD|TH)$/i.test(el.nodeName)) {
  6775. tdNum += el.colSpan || 1;
  6776. }
  6777. });
  6778. }
  6779. pageBar.style.cssText = "";
  6780. pageBar.style.display = "table-row";
  6781. pageBar.style.backgroundColor = "unset";
  6782. pageBar.style.lineHeight = "20px";
  6783. pageBar.style.boxShadow = "";
  6784. let td = document.createElement("td");
  6785. td.colSpan = tdNum || 1;
  6786. let inTd = document.createElement("div");
  6787. inTd.style.cssText = pageBarStyle;
  6788. inTd.style.display = "";
  6789. inTd.className = pageBar.className;
  6790. pageBar.className = "";
  6791. inTd.appendChild(upSpan);
  6792. inTd.appendChild(pageText);
  6793. if (pageNum) inTd.appendChild(pageNum);
  6794. inTd.appendChild(downSpan);
  6795. td.appendChild(inTd);
  6796. pageBar.appendChild(td);
  6797. } else if (inLi) {
  6798. example = /^LI$/i.test(example.nodeName) ? example : example.nextElementSibling || example;
  6799. pageBar.style.opacity = 1;
  6800. pageBar.style.display = getComputedStyle(example).display;
  6801. pageBar.style.backgroundColor = "unset";
  6802. pageBar.style.lineHeight = "20px";
  6803. pageBar.style.boxShadow = "";
  6804. pageBar.style.border = "";
  6805. pageBar.style.maxWidth = "unset";
  6806. pageBar.style.flex = "auto";
  6807. let inTd = document.createElement("div");
  6808. inTd.style.cssText = pageBarStyle;
  6809. inTd.style.display = "";
  6810. inTd.style.margin = "0"
  6811. inTd.style.padding = "0 0";
  6812. inTd.style.textAlign = "center";
  6813. inTd.style.minWidth = "150px";
  6814. inTd.style.width = 'calc(100% - 20px)';
  6815. inTd.className = pageBar.className;
  6816. pageBar.className = "";
  6817. inTd.appendChild(upSpan);
  6818. inTd.appendChild(pageText);
  6819. if (pageNum) inTd.appendChild(pageNum);
  6820. inTd.appendChild(downSpan);
  6821. if (pageBar.style.display === 'table-row') {
  6822. let td = document.createElement("td");
  6823. td.colSpan = example.children.length;
  6824. td.style.width = '100%';
  6825. td.appendChild(inTd);
  6826. pageBar.appendChild(td);
  6827. } else {
  6828. inTd.style.width = '100%';
  6829. pageBar.appendChild(inTd);
  6830. }
  6831. }
  6832. }
  6833.  
  6834. upSpan.addEventListener("click", e => {
  6835. getBody(document).scrollTop = 0;
  6836. document.documentElement.scrollTop = 0;
  6837. e.preventDefault();
  6838. e.stopPropagation();
  6839. });
  6840. downSpan.addEventListener("click", e => {
  6841. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  6842. changeStop(true);
  6843. }
  6844. pageBar.title = i18n(isPause ? "enable" : "disable");
  6845. scrollH=Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  6846. getBody(document).scrollTop = scrollH || 9999999;
  6847. document.documentElement.scrollTop = scrollH || 9999999;
  6848. e.preventDefault();
  6849. e.stopPropagation();
  6850. });
  6851. pageBar.addEventListener("click", e => {
  6852. changeStop(!isPause);
  6853. pageBar.title = i18n(isPause ? "enable" : "disable");
  6854. });
  6855. ruleParser.insertElement(pageBar);
  6856. if (ruleParser.curSiteRule.pageBar && ruleParser.curSiteRule.pageBar !== 0) {
  6857. try {
  6858. ((typeof _unsafeWindow.pagetualPageBar == 'undefined') ? Function("pageBar",'"use strict";' + ruleParser.curSiteRule.pageBar) : _unsafeWindow.pagetualPageBar)(pageBar);
  6859. } catch(e) {
  6860. debug(e);
  6861. }
  6862. }
  6863.  
  6864. return pageBar;
  6865. }
  6866.  
  6867. async function waitForElement(sel, doc) {
  6868. if (!sel) return null;
  6869. return new Promise((resolve) => {
  6870. let checkInv = setInterval(() => {
  6871. let result = getElement(sel, doc, null, true);
  6872. if (result) {
  6873. clearInterval(checkInv);
  6874. resolve(result);
  6875. }
  6876. }, 100);
  6877. });
  6878. }
  6879.  
  6880. async function clickAction(sel, doc) {
  6881. let btn = await waitForElement(sel, doc);
  6882. emuClick(btn);
  6883. }
  6884.  
  6885. async function enterAction(sel, doc) {
  6886. let btn = await waitForElement(sel, doc);
  6887. let eventParam = { key: "Enter", keyCode: 13, bubbles: true };
  6888. let event = new KeyboardEvent('keydown', eventParam);
  6889. btn.dispatchEvent(event);
  6890. event = new KeyboardEvent('keyup', eventParam);
  6891. btn.dispatchEvent(event);
  6892. event = new KeyboardEvent('keypress', eventParam);
  6893. btn.dispatchEvent(event);
  6894. }
  6895.  
  6896. async function inputAction(sel, v, doc) {
  6897. let input = await waitForElement(sel, doc);
  6898. let event = new Event('focus', { bubbles: true });
  6899. input.dispatchEvent(event);
  6900. let lastValue = input.value;
  6901. if (input.nodeName.toUpperCase() == "INPUT") {
  6902. var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
  6903. nativeInputValueSetter.call(input, v);
  6904. } else if (input.nodeName.toUpperCase() == "TEXTAREA") {
  6905. var nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
  6906. nativeTextareaValueSetter.call(input, v);
  6907. } else {
  6908. input.innerHTML = createHTML(v);
  6909. }
  6910. event = new Event('input', { bubbles: true });
  6911. let tracker = input._valueTracker;
  6912. if (tracker) {
  6913. tracker.setValue(lastValue);
  6914. }
  6915. input.dispatchEvent(event);
  6916. event = new Event('change', { bubbles: true });
  6917. input.dispatchEvent(event);
  6918. debug(input, `input ${sel}`);
  6919. }
  6920.  
  6921. function emuClick(btn) {
  6922. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  6923. let orgHref = btn.getAttribute('href');
  6924. if (orgHref && orgHref.replace(location.origin + location.pathname, "").indexOf("#") === 0) {
  6925. let hashAction = e => {
  6926. e.preventDefault();
  6927. getBody(document).scrollTop = curScroll;
  6928. document.documentElement.scrollTop = curScroll;
  6929. btn.removeEventListener('click', hashAction, false);
  6930. };
  6931. btn.addEventListener('click', hashAction, false);
  6932. }
  6933. if (!PointerEvent) return btn.click();
  6934. let eventParam = {
  6935. isTrusted: true,
  6936. altKey: false,
  6937. azimuthAngle: 0,
  6938. bubbles: true,
  6939. button: 0,
  6940. buttons: 0,
  6941. clientX: 1,
  6942. clientY: 1,
  6943. cancelBubble: false,
  6944. cancelable: true,
  6945. composed: true,
  6946. ctrlKey: false,
  6947. defaultPrevented: false,
  6948. detail: 1,
  6949. eventPhase: 2,
  6950. fromElement: null,
  6951. height: 1,
  6952. isPrimary: false,
  6953. metaKey: false,
  6954. pointerId: 1,
  6955. pointerType: "mouse",
  6956. pressure: 0,
  6957. relatedTarget: null,
  6958. returnValue: true,
  6959. shiftKey: false,
  6960. toElement: null,
  6961. twist: 0,
  6962. which: 1
  6963. };
  6964. let mouseEvent = new PointerEvent("mousedown", eventParam);
  6965. btn.dispatchEvent(mouseEvent);
  6966. mouseEvent = new PointerEvent("mouseup", eventParam);
  6967. btn.dispatchEvent(mouseEvent);
  6968. let dispatchTouchEvent = (ele, type) => {
  6969. let touchEvent;
  6970. try {
  6971. touchEvent = document.createEvent('TouchEvent')
  6972. touchEvent.initTouchEvent(type, true, true)
  6973. } catch (err) {
  6974. try {
  6975. touchEvent = document.createEvent('UIEvent')
  6976. touchEvent.initUIEvent(type, true, true)
  6977. } catch (err) {
  6978. touchEvent = document.createEvent('Event')
  6979. touchEvent.initEvent(type, true, true)
  6980. }
  6981. }
  6982. if (touchEvent) {
  6983. try {
  6984. touchEvent.targetTouches = [{
  6985. pageX: 1,
  6986. pageY: 1,
  6987. clientX: 1,
  6988. clientY: 1,
  6989. target: btn
  6990. }];
  6991. touchEvent.touches = [{
  6992. pageX: 1,
  6993. pageY: 1,
  6994. clientX: 1,
  6995. clientY: 1,
  6996. target: btn
  6997. }];
  6998. touchEvent.changedTouches = [{
  6999. pageX: 1,
  7000. pageY: 1,
  7001. clientX: 1,
  7002. clientY: 1,
  7003. target: btn
  7004. }];
  7005. } catch (err) {}
  7006. ele.dispatchEvent(touchEvent);
  7007. }
  7008. }
  7009. dispatchTouchEvent(btn, "touchstart");
  7010. dispatchTouchEvent(btn, "touchend");
  7011.  
  7012. btn.click();
  7013. }
  7014.  
  7015. var failFromIframe = 0;
  7016. var inCors = false;
  7017. var checkRemoveIntv;
  7018. function requestFromIframe(url, callback){
  7019. if (location.protocol === 'https:' && !/^https:/.test(url)) {
  7020. ruleParser.noValidContent(url);
  7021. }
  7022. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  7023. let iframe = document.createElement('iframe');
  7024. iframe.name = 'pagetual-iframe';
  7025. iframe.width = '100%';
  7026. iframe.height = '1000';
  7027. iframe.frameBorder = '0';
  7028. if (ruleParser.curSiteRule.sandbox != false) {
  7029. iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  7030. }
  7031. 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;';
  7032. let waitTime = 100, checkEval;
  7033. if (ruleParser.curSiteRule.waitElement) {
  7034. checkEval = doc => {
  7035. return ruleParser.waitElement(doc);
  7036. };
  7037. } else if (ruleParser.curSiteRule.wait) {
  7038. if (isNaN(ruleParser.curSiteRule.wait)) {
  7039. try {
  7040. checkEval = (typeof _unsafeWindow.pagetualWait == 'undefined') ? Function("doc",'"use strict";' + ruleParser.curSiteRule.wait) : _unsafeWindow.pagetualWait;
  7041. } catch(e) {
  7042. debug(e);
  7043. }
  7044. } else {
  7045. waitTime = ruleParser.curSiteRule.wait;
  7046. }
  7047. }
  7048. if (checkRemoveIntv) clearInterval(checkRemoveIntv);
  7049. checkRemoveIntv = setInterval(() => {
  7050. if (!iframe || !getBody(document).contains(iframe)) {
  7051. clearInterval(checkRemoveIntv);
  7052. loadPageOver();
  7053. }
  7054. }, 500);
  7055. let loadedHandler = e => {
  7056. if (e.data != 'pagetual-iframe:DOMLoaded' && e.type != 'load') return;
  7057. clearInterval(checkRemoveIntv);
  7058. window.removeEventListener('message', loadedHandler, false);
  7059. iframe.removeEventListener('load', loadedHandler, false);
  7060. let tryTimes = 0;
  7061. function checkIframe() {
  7062. if (urlChanged || isPause) {
  7063. return callback(false, false);
  7064. }
  7065. try {
  7066. let doc = iframe.contentDocument || iframe.contentWindow.document;
  7067. let base = doc.querySelector("base");
  7068. ruleParser.basePath = base ? base.href : url;
  7069. let eles = ruleParser.getPageElement(doc, iframe.contentWindow, tryTimes < 10);
  7070. if (checkEval && !checkEval(doc)) {
  7071. setTimeout(() => {
  7072. checkIframe();
  7073. }, waitTime);
  7074. return;
  7075. } else if (eles && eles.length > 0) {
  7076. callback(doc, eles);
  7077. } else if (tryTimes++ < 100) {
  7078. setTimeout(() => {
  7079. checkIframe();
  7080. }, waitTime);
  7081. return;
  7082. } else {
  7083. if (failFromIframe++ > 2) {
  7084. failFromIframe = 0;
  7085. debug("Stop as failFromIframe");
  7086. isPause = true;
  7087. callback(false, false);
  7088. } else {
  7089. ruleParser.noValidContent(url);
  7090. callback(false, false);
  7091. }
  7092. }
  7093. } catch(e) {
  7094. inCors = true;
  7095. if (forceState === 3) {
  7096. debug("Stop as cors");
  7097. isPause = true;
  7098. }
  7099. if (!ruleParser.curSiteRule.pageElement) {
  7100. ruleParser.curSiteRule.pageElement = allOfBody;
  7101. ruleParser.getInsert(true);
  7102. }
  7103. ruleParser.curSiteRule.action = 0;
  7104. ruleParser.nextLinkHref = url;
  7105. callback(false, false);
  7106. nextPage();
  7107. }
  7108. if (iframe && iframe.parentNode) iframe.parentNode.removeChild(iframe);
  7109. }
  7110. setTimeout(() => {
  7111. checkIframe();
  7112. }, waitTime);
  7113. };
  7114. let code = ruleParser.curSiteRule.iframeInit;
  7115. if (code) {
  7116. let checkReady = setInterval(() => {
  7117. let doc;
  7118. try {
  7119. doc = iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document);
  7120. } catch(e) {
  7121. clearInterval(checkReady);
  7122. return;
  7123. }
  7124. if (doc) {
  7125. try {
  7126. Function('win', 'iframe', '"use strict";' + code)(iframe.contentWindow, iframe);
  7127. clearInterval(checkReady);
  7128. } catch(e) {
  7129. debug(e);
  7130. }
  7131. }
  7132. }, 50);
  7133. }
  7134. window.addEventListener('message', loadedHandler, false);
  7135. iframe.addEventListener('load', loadedHandler, false);
  7136. iframe.src = url;
  7137. try {
  7138. getBody(document).appendChild(iframe);
  7139. } catch (e) {
  7140. return callback(false, false);
  7141. }
  7142. }
  7143.  
  7144. var emuIframe, lastActiveUrl, orgContent, meetCors = false;
  7145. function emuPage(callback) {
  7146. let orgPage = null, preContent = null, iframeDoc, checkTimes = 0, loadmoreBtn, pageEle, nextLink, loadmoreEnd = false, waitTimes = 80, changed = false;
  7147. function returnFalse(log) {
  7148. if (curPage > 1 && rulesData.lastPageTips) showTips(i18n("lastPage"));
  7149. debug(log);
  7150. isPause = true;
  7151. callback(false, false);
  7152. if (emuIframe && emuIframe.parentNode) {
  7153. emuIframe.parentNode.removeChild(emuIframe);
  7154. sideController.remove();
  7155. emuIframe = null;
  7156. }
  7157. }
  7158. async function checkPage() {
  7159. if (isPause) return loadPageOver();
  7160. try {
  7161. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  7162. } catch(e) {
  7163. returnFalse("Stop as cors");
  7164. return;
  7165. }
  7166.  
  7167. let waitTime = 200, checkEval;
  7168. if (ruleParser.curSiteRule.waitElement) {
  7169. checkEval = doc => {
  7170. return ruleParser.waitElement(doc);
  7171. };
  7172. } else if(ruleParser.curSiteRule.wait) {
  7173. if (isNaN(ruleParser.curSiteRule.wait)) {
  7174. try {
  7175. checkEval = (typeof _unsafeWindow.pagetualWait == 'undefined') ? Function("doc", '"use strict";' + ruleParser.curSiteRule.wait) : _unsafeWindow.pagetualWait;
  7176. } catch(e) {
  7177. debug(e);
  7178. }
  7179. } else {
  7180. waitTime = ruleParser.curSiteRule.wait;
  7181. }
  7182. }
  7183.  
  7184. if (!orgPage) {
  7185. if (!loadmoreEnd) {
  7186. loadmoreBtn = getLoadMore(iframeDoc);
  7187. if (loadmoreBtn && isVisible(loadmoreBtn, emuIframe.contentWindow)) {
  7188. emuClick(loadmoreBtn);
  7189. let intv = setInterval(() => {
  7190. loadmoreBtn = getLoadMore(iframeDoc);
  7191. if (!loadmoreBtn || !getBody(document).contains(loadmoreBtn) || !isVisible(loadmoreBtn, emuIframe.contentWindow)) {
  7192. clearInterval(intv);
  7193. loadmoreEnd = true;
  7194. setTimeout(() => {
  7195. checkPage();
  7196. }, 500);
  7197. } else if (isInViewPort(loadmoreBtn)) {
  7198. emuClick(loadmoreBtn);
  7199. }
  7200. }, 200);
  7201. return;
  7202. } else {
  7203. loadmoreEnd = true;
  7204. }
  7205. }
  7206. if (checkEval && !checkEval(iframeDoc)) {
  7207. waitTimes = 50;
  7208. setTimeout(() => {
  7209. checkPage();
  7210. }, waitTime);
  7211. return;
  7212. } else {
  7213. if (!nextLink || !nextLink.offsetParent) nextLink = await ruleParser.getNextLink(iframeDoc, true);
  7214. if (nextLink) pageEle = ruleParser.getPageElement(iframeDoc, emuIframe.contentWindow, true);
  7215. if (!pageEle || pageEle.length == 0 || !nextLink) {
  7216. if (waitTimes-- > 0) {
  7217. setTimeout(() => {
  7218. checkPage();
  7219. }, waitTime);
  7220. return;
  7221. }
  7222. }
  7223. }
  7224. if (!pageEle || pageEle.length == 0) {
  7225. returnFalse("Stop as no page when emu");
  7226. return;
  7227. }
  7228. if (/^UL$/i.test(pageEle[0].nodeName)) pageEle = pageEle[0].children;
  7229. pageEle = pageEle[parseInt((pageEle.length - 1) / 2)];
  7230. while(pageEle && ((pageEle.scrollHeight && pageEle.scrollHeight < 50) || !pageEle.offsetParent || (!/^IMG$/i.test(pageEle.nodeName) && !pageEle.innerHTML.trim()))) {
  7231. if (pageEle.nextElementSibling) pageEle = pageEle.nextElementSibling;
  7232. else break;
  7233. }
  7234. if (ruleParser.curSiteRule.singleUrl && orgContent != pageEle.innerHTML) {
  7235. orgContent = pageEle.innerHTML;
  7236. if (waitTimes-- > 0) {
  7237. setTimeout(() => {
  7238. checkPage();
  7239. }, waitTime);
  7240. return;
  7241. }
  7242. }
  7243. orgPage = pageEle;
  7244. if (nextLink) {
  7245. if (/^IMG$/i.test(orgPage.nodeName)) {
  7246. if (!ruleParser.curSiteRule.lazyImgSrc) ruleParser.curSiteRule.lazyImgSrc = "0";
  7247. if (orgPage.src) {
  7248. orgContent = orgPage.src;
  7249. } else {
  7250. setTimeout(() => {
  7251. checkPage();
  7252. }, 500);
  7253. return;
  7254. }
  7255. } else {
  7256. orgContent = orgPage.innerHTML;
  7257. }
  7258. preContent = orgContent;
  7259. if (!isVisible(nextLink, emuIframe.contentWindow)) {
  7260. returnFalse("Stop as next hide when emu");
  7261. } else {
  7262. emuClick(nextLink);
  7263. setTimeout(() => {
  7264. checkPage();
  7265. }, 500);
  7266. }
  7267. } else {
  7268. returnFalse("Stop as no next when emu");
  7269. }
  7270. return;
  7271. }
  7272. if (!ruleParser.checkStopSign(nextLink, iframeDoc)) {
  7273. return returnFalse("Stop as stopSign");;
  7274. }
  7275. if (checkTimes++ > 200) {
  7276. returnFalse("Stop as timeout when emu");
  7277. return;
  7278. }
  7279. let eles = ruleParser.getPageElement(iframeDoc, emuIframe.contentWindow, true), checkItem;
  7280. if (eles && eles.length > 0) {
  7281. checkItem = eles;
  7282. if (/^UL$/i.test(eles[0].nodeName)) checkItem = eles[0].children;
  7283. checkItem = checkItem[parseInt((checkItem.length - 1) / 2)];
  7284. while(checkItem && ((checkItem.scrollHeight && checkItem.scrollHeight < 50) || !checkItem.offsetParent || (!/^IMG$/i.test(checkItem.nodeName) && !checkItem.innerHTML.trim()))) {
  7285. if (checkItem.nextElementSibling) checkItem = checkItem.nextElementSibling;
  7286. else break;
  7287. }
  7288. }
  7289. if (!checkItem || (checkEval && !checkEval(iframeDoc))) {
  7290. if (checkEval) checkTimes = 0;
  7291. setTimeout(() => {
  7292. checkPage();
  7293. }, waitTime);
  7294. } else {
  7295. let checkInner;
  7296. if (/^IMG$/i.test(checkItem.nodeName)) {
  7297. if (checkItem.src) {
  7298. checkInner = checkItem.src;
  7299. } else {
  7300. setTimeout(() => {
  7301. checkPage();
  7302. }, waitTime);
  7303. return;
  7304. }
  7305. } else {
  7306. checkInner = checkItem.innerHTML;
  7307. }
  7308. if (orgPage != checkItem || checkInner != preContent) {
  7309. changed = true;
  7310. orgPage = checkItem;
  7311. preContent = checkInner;
  7312. setTimeout(() => {
  7313. checkPage();
  7314. }, waitTime);
  7315. } else if (changed) {
  7316. checkTimes = 0;
  7317. if (orgContent == preContent && (ruleParser.curSiteRule.singleUrl || ruleParser.curSiteRule.stopSame)) {
  7318. returnFalse("Stop as same content");
  7319. } else {
  7320. orgContent = preContent;
  7321. callback(iframeDoc, eles);
  7322. }
  7323. } else {
  7324. if (checkTimes % 10 === 5) {
  7325. if (!nextLink || !nextLink.offsetParent) {
  7326. nextLink = await ruleParser.getNextLink(iframeDoc, true);
  7327. }
  7328. if (nextLink) {
  7329. emuClick(nextLink);
  7330. }
  7331. }
  7332. setTimeout(() => {
  7333. checkPage();
  7334. }, waitTime);
  7335. }
  7336. }
  7337. }
  7338. if (!emuIframe) {
  7339. let loaded = false;
  7340. emuIframe = document.createElement('iframe');
  7341. emuIframe.name = 'pagetual-iframe';
  7342. let notSetSandbox = typeof ruleParser.curSiteRule.sandbox == 'undefined';
  7343. if (notSetSandbox || ruleParser.curSiteRule.sandbox == true) {
  7344. emuIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  7345. } else if (ruleParser.curSiteRule.sandbox) {
  7346. emuIframe.sandbox = ruleParser.curSiteRule.sandbox;
  7347. }
  7348. emuIframe.width = '100%';
  7349. emuIframe.height = '100%';
  7350. emuIframe.frameBorder = '0';
  7351. 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;';
  7352. emuIframe.addEventListener("load", e => {
  7353. setTimeout(() => {
  7354. try {
  7355. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  7356. } catch(e) {
  7357. if (e.message && e.message.indexOf("cross-origin") != -1 && notSetSandbox && emuIframe.hasAttribute("sandbox")) {
  7358. emuIframe.removeAttribute("sandbox");
  7359. meetCors = true;
  7360. callback(false, false);
  7361. } else {
  7362. returnFalse("Stop as cors");
  7363. }
  7364. return;
  7365. }
  7366. meetCors = false;
  7367. let code = ruleParser.curSiteRule.init;
  7368. if (code) {
  7369. try {
  7370. new AsyncFunction('doc','win','iframe','click', 'enter', 'input', '"use strict";' + code)(iframeDoc, emuIframe.contentWindow, emuIframe, sel => {clickAction(sel, iframeDoc)}, sel => {enterAction(sel, iframeDoc)}, (sel, v) =>{inputAction(sel, v, iframeDoc)});
  7371. } catch(e) {
  7372. debug(e);
  7373. }
  7374. }
  7375. if (loaded) return;
  7376. loaded = true;
  7377. checkPage();
  7378. }, 500);
  7379. });
  7380. let code = ruleParser.curSiteRule.iframeInit;
  7381. if (code) {
  7382. let checkReady = setInterval(() => {
  7383. try {
  7384. iframeDoc = emuIframe.contentDocument || (emuIframe.contentWindow && emuIframe.contentWindow.document);
  7385. } catch(e) {
  7386. clearInterval(checkReady);
  7387. return;
  7388. }
  7389. if (iframeDoc) {
  7390. try {
  7391. Function('win', 'iframe', '"use strict";' + code)(emuIframe.contentWindow, emuIframe);
  7392. clearInterval(checkReady);
  7393. } catch(e) {
  7394. debug(e);
  7395. }
  7396. }
  7397. }, 50);
  7398. }
  7399. if (!lastActiveUrl) lastActiveUrl = location.href;
  7400. emuIframe.src = lastActiveUrl;
  7401. getBody(document).appendChild(emuIframe);
  7402. } else {
  7403. if (emuIframe.src != lastActiveUrl || meetCors) {
  7404. emuIframe.src = lastActiveUrl;
  7405. return;
  7406. }
  7407. checkPage();
  7408. }
  7409. }
  7410.  
  7411. var scrollToResizeInited = false;
  7412. var resizePool = [];
  7413. var scrollingToResize = false;
  7414.  
  7415. function isTouchViewPort(element) {
  7416. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  7417. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  7418. const {
  7419. top,
  7420. right,
  7421. bottom,
  7422. left,
  7423. } = element.getBoundingClientRect();
  7424.  
  7425. return (
  7426. top < viewHeight &&
  7427. left < viewWidth &&
  7428. right > 0 &&
  7429. bottom > 0
  7430. );
  7431. }
  7432.  
  7433. function resizeIframe(iframe, frameDoc, pageEle) {
  7434. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  7435. if (ruleParser.curSiteRule.singleUrl || forceState === 2) {
  7436. let height = (getBody(frameDoc).scrollHeight || getBody(frameDoc).offsetHeight || 500);
  7437. if (!iframe.style.height || height - parseInt(iframe.style.height) > 50) {
  7438. iframe.style.height = height + "px";
  7439. iframe.style.minHeight = iframe.style.height;
  7440. }
  7441. iframe.style.width = "100%";
  7442. frameDoc.documentElement.scrollTop = 0;
  7443. frameDoc.documentElement.scrollLeft = 0;
  7444. } else {
  7445. if (pageEle) {
  7446. let fitWidth = ruleParser.curSiteRule.fitWidth !== false;
  7447. let targetElement = pageEle[0];
  7448. if (!targetElement) return;
  7449. if (pageEle.length > 1) {
  7450. targetElement = targetElement.parentNode;
  7451. }
  7452. let scrollHeight = targetElement.scrollHeight || targetElement.offsetHeight || 500;
  7453. iframe.style.height = scrollHeight + "px";
  7454. let scrollTop = 0, scrollLeft = 0;
  7455. getBody(frameDoc).scrollTop = 0;
  7456. getBody(frameDoc).scrollLeft = 0;
  7457. while (targetElement && targetElement.offsetParent) {
  7458. targetElement.offsetParent.scrollTop = targetElement.offsetTop;
  7459. if (targetElement.offsetParent.scrollTop == 0) {
  7460. scrollTop += targetElement.offsetTop;
  7461. }
  7462. if (fitWidth) {
  7463. targetElement.offsetParent.scrollLeft = targetElement.offsetLeft;
  7464. if (targetElement.offsetParent.scrollLeft == 0) {
  7465. scrollLeft += targetElement.offsetLeft;
  7466. }
  7467. }
  7468. targetElement = targetElement.offsetParent;
  7469. }
  7470. frameDoc.documentElement.scrollTop = scrollTop;
  7471. frameDoc.documentElement.scrollLeft = scrollLeft;
  7472. if (frameDoc.documentElement.scrollTop == 0 && frameDoc.documentElement.scrollLeft == 0) {
  7473. getBody(frameDoc).scrollTop += scrollTop;
  7474. getBody(frameDoc).scrollLeft += scrollLeft;
  7475. }
  7476. if (!fitWidth && iframe.style.marginLeft == '0px') {
  7477. iframe.style.width = "100vw";
  7478. iframe.style.maxWidth = "100vw";
  7479. iframe.style.minWidth = "100vw";
  7480. var cWidth = document.body.clientWidth || document.documentElement.clientWidth;
  7481. var iWidth = window.innerWidth;
  7482. iframe.style.marginLeft = -iframe.getBoundingClientRect().left - (iWidth - cWidth) / 2 + "px";
  7483. }
  7484. }
  7485. }
  7486. getBody(document).scrollTop = curScroll;
  7487. document.documentElement.scrollTop = curScroll;
  7488. }
  7489.  
  7490. function scrollToResize(e) {
  7491. if (scrollingToResize) return;
  7492. else {
  7493. scrollingToResize = true;
  7494. let resizeHandler = () => {
  7495. let touched = 0;
  7496. for (let i in resizePool) {
  7497. let resizeArr = resizePool[i];
  7498. let iframe = resizeArr[1]();
  7499. if (isTouchViewPort(iframe)) {
  7500. touched++;
  7501. let pageEle = resizeArr[0]();
  7502. let frameDoc = resizeArr[2]();
  7503. resizeIframe(iframe, frameDoc, pageEle);
  7504. } else if (touched) {
  7505. if (touched == 1) {
  7506. let pageEle = resizeArr[0]();
  7507. let frameDoc = resizeArr[2]();
  7508. resizeIframe(iframe, frameDoc, pageEle);
  7509. }
  7510. break;
  7511. } else if (!iframe.parentNode) {
  7512. resizePool.splice(i, 1);
  7513. break;
  7514. }
  7515. }
  7516. };
  7517. setTimeout(() => {
  7518. scrollingToResize = false;
  7519. }, 300);
  7520. resizeHandler();
  7521. }
  7522. }
  7523.  
  7524. function forceIframe(url, callback) {
  7525. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  7526. let curIframe = document.createElement('iframe'), iframeDoc, pageElement = null, isloaded = false, inAction = true;
  7527. let loadedHandler = () => {
  7528. let getPageEle = () => {
  7529. if (ruleParser.curSiteRule.singleUrl) {
  7530. return null;
  7531. } else {
  7532. if (!pageElement || pageElement.length === 0 || !pageElement[0].offsetParent) {
  7533. pageElement = ruleParser.getPageElement(iframeDoc, curIframe.contentWindow);
  7534. }
  7535. return pageElement;
  7536. }
  7537. };
  7538. resizeIframe(curIframe, iframeDoc, getPageEle());
  7539. if (isloaded) return;
  7540. isloaded = true;
  7541. let getIframe = () => {
  7542. return curIframe;
  7543. };
  7544. let getFrameDoc = () => {
  7545. return iframeDoc;
  7546. };
  7547. ruleParser.insertPage(iframeDoc, [], url, ele => {
  7548. callback(curIframe);
  7549. inAction = false;
  7550. }, true);
  7551. resizePool.push([getPageEle, getIframe, getFrameDoc]);
  7552. };
  7553. let checkIframeTimer = setInterval(() => {
  7554. if (!curIframe.parentNode) {
  7555. clearInterval(checkIframeTimer);
  7556. return isloaded || callback(false);
  7557. }
  7558. }, 500);
  7559. let code = ruleParser.curSiteRule.iframeInit;
  7560. if (code) {
  7561. let checkReady = setInterval(() => {
  7562. try {
  7563. iframeDoc = curIframe.contentDocument || (curIframe.contentWindow && curIframe.contentWindow.document);
  7564. } catch(e) {
  7565. clearInterval(checkReady);
  7566. return;
  7567. }
  7568. if (iframeDoc) {
  7569. try {
  7570. Function('win', 'iframe', '"use strict";' + code)(curIframe.contentWindow, curIframe);
  7571. clearInterval(checkReady);
  7572. } catch(e) {
  7573. debug(e);
  7574. }
  7575. }
  7576. }, 50);
  7577. }
  7578. curIframe.name = 'pagetual-iframe';
  7579. curIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  7580. curIframe.frameBorder = '0';
  7581. curIframe.scrolling = "no";
  7582. 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;';
  7583. curIframe.addEventListener("load", e => {
  7584. clearInterval(checkIframeTimer);
  7585. if (isPause) return callback(false);
  7586. try {
  7587. iframeDoc = curIframe.contentDocument || curIframe.contentWindow.document;
  7588. } catch(e) {
  7589. debug("Stop as cors");
  7590. isPause = true;
  7591. callback(false);
  7592. return;
  7593. }
  7594. let css = ruleParser.curSiteRule.css || rulesData.customCss;
  7595. if (css) {
  7596. let cssArr = css.split("inIframe:");
  7597. if (cssArr && cssArr.length > 1) {
  7598. let styleEle = iframeDoc.createElement("style");
  7599. styleEle.innerHTML = cssArr[1];
  7600. iframeDoc.head.appendChild(styleEle);
  7601. }
  7602. }
  7603. loadedHandler();
  7604. let code = ruleParser.curSiteRule.init;
  7605. if (code) {
  7606. try {
  7607. new AsyncFunction('doc', 'win', 'iframe', 'click', 'enter', 'input', '"use strict";' + code)(iframeDoc, curIframe.contentWindow, curIframe, sel => {clickAction(sel, iframeDoc)}, sel => {enterAction(sel, iframeDoc)}, (sel, v) =>{inputAction(sel, v, iframeDoc)});
  7608. } catch(e) {
  7609. debug(e);
  7610. }
  7611. }
  7612. iframeDoc.addEventListener('wheel', e => {
  7613. document.dispatchEvent(new Event('wheel'));
  7614. }, true);
  7615. });
  7616. let checkTimes = 0, findPageEle = false;
  7617. let forceRefresh = e => {
  7618. if (inAction || !iframeDoc) return;
  7619. inAction = true;
  7620. let foundNext = () => {
  7621. document.removeEventListener("scroll", forceRefresh);
  7622. }
  7623. setTimeout(async () => {
  7624. inAction = false;
  7625. if (!ruleParser.nextLinkHref && !isPause) {
  7626. checkTimes++;
  7627. await ruleParser.getNextLink(iframeDoc, true);
  7628. if (ruleParser.nextLinkHref) {
  7629. foundNext();
  7630. if (isLoading) isLoading = false;
  7631. } else if (checkTimes >= 10) {
  7632. foundNext();
  7633. } else if (checkTimes >= 3 && !findPageEle) {
  7634. if (!pageElement) pageElement = ruleParser.getPageElement(iframeDoc, curIframe.contentWindow);
  7635. if (!pageElement) {
  7636. inAction = true;
  7637. curIframe.contentWindow.location.reload();
  7638. } else {
  7639. findPageEle = true;
  7640. }
  7641. }
  7642. } else {
  7643. foundNext();
  7644. }
  7645. }, 100);
  7646. };
  7647. document.addEventListener("scroll", forceRefresh);
  7648. curIframe.src = url;
  7649. let insert = ruleParser.getInsert();
  7650. let body = getBody(document);
  7651. let curScroll = body.scrollTop || document.documentElement.scrollTop;
  7652. if (forceState == 2) {
  7653. body.appendChild(loadingDiv);
  7654. body.appendChild(curIframe);
  7655. let bodyStyle = getComputedStyle(body);
  7656. if (bodyStyle.display == "flex" || bodyStyle.display == "inline-flex") {
  7657. body.style.flexDirection = "column";
  7658. }
  7659. } else {
  7660. ruleParser.insertElement(curIframe);
  7661. }
  7662. body.scrollTop = curScroll;
  7663. document.documentElement.scrollTop = curScroll;
  7664.  
  7665. if (!scrollToResizeInited) {
  7666. scrollToResizeInited = true;
  7667. document.addEventListener("scroll", scrollToResize);
  7668. }
  7669. return curIframe;
  7670. }
  7671.  
  7672. function loadPageOver() {
  7673. isLoading = false;
  7674. stopScroll = true;
  7675. let dist = distToBottom();
  7676. setTimeout(() => {stopScroll = false}, 300);
  7677. if (loadingDiv.parentNode) {
  7678. loadingDiv.parentNode.removeChild(loadingDiv);
  7679. }
  7680. let rate = (ruleParser.curSiteRule.rate || rulesData.rate || 1);
  7681. if (rate != 1 && !clickMode) {
  7682. setTimeout(() => {
  7683. if (dist < bottomGap) {
  7684. nextPage();
  7685. }
  7686. }, 1);
  7687. }
  7688. }
  7689.  
  7690. function checkAutoLoadNum() {
  7691. if (autoLoadNum >= 0) {
  7692. if (autoLoadNum != 0 && --autoLoadNum == 0) {
  7693. autoLoadNum = -1;
  7694. } else {
  7695. setTimeout(() => nextPage(), 1);
  7696. }
  7697. }
  7698. }
  7699.  
  7700. var tryTimes = 0;
  7701. async function nextPage() {
  7702. if (typeof ruleParser.curSiteRule.manualMode == 'undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode) return;
  7703. if (clickMode) return;
  7704. if (isPause || isLoading || forceState == 1) return;
  7705. if (ruleParser.curSiteRule.delay) {
  7706. try {
  7707. let checkDelay = ((typeof _unsafeWindow.pagetualDelay=='undefined') ? Function('"use strict";' + ruleParser.curSiteRule.delay) : _unsafeWindow.pagetualDelay)();
  7708. if (!checkDelay) return;
  7709. } catch(e) {
  7710. debug(e);
  7711. }
  7712. }
  7713. let nextLink = ruleParser.nextLinkHref;
  7714. if (!nextLink) {
  7715. isLoading = true;
  7716. if (curPage == 1) {
  7717. await ruleParser.getNextLink(document, true);
  7718. nextLink = ruleParser.nextLinkHref;
  7719. }
  7720. if (!nextLink) {
  7721. if (curPage == 1 && (ruleParser.curSiteRule.pinUrl || tryTimes++ <= 3)) {
  7722. setTimeout(() => {isLoading = false}, 500);
  7723. } else if (curPage > 1 && rulesData.lastPageTips) {
  7724. showTips(i18n("lastPage"));
  7725. }
  7726. return;
  7727. }
  7728. isLoading = false;
  7729. }
  7730. let pvGallery = document.querySelector("span.pv-gallery-container");
  7731. if (pvGallery && pvGallery.style.display != "none") return;
  7732. let insert = ruleParser.getInsert();
  7733. if (insert) {
  7734. if (curPage == 1) initView();
  7735. sideController.setup();
  7736. /*if (curPage == 1) {
  7737. window.postMessage({
  7738. insert: geneSelector(ruleParser.curSiteRule.insertPos == 2 ? insert : insert.parentNode, true),
  7739. command: 'pagetual.insert'
  7740. }, '*');
  7741. }*/
  7742. let isJs = ruleParser.curSiteRule.action == 3 || ruleParser.hrefIsJs(nextLink);
  7743. if (!isJs) {
  7744. emuIframe = null;
  7745. lastActiveUrl = nextLink;
  7746. if (location.protocol == "https:" && /^http:/.test(nextLink)) {
  7747. nextLink = nextLink.replace(/^http/, "https");
  7748. }
  7749. }
  7750. isLoading = true;
  7751. if (curPage != 1 || !isJs || !ruleParser.curSiteRule.singleUrl) {
  7752. ruleParser.beginLoading(loadingDiv);
  7753. }
  7754. let sleep = ruleParser.curSiteRule.sleep || 0;
  7755. setTimeout(() => {
  7756. if (ruleParser.curSiteRule.pageElementByJs) {
  7757. var over = eles => {
  7758. if (urlChanged || isPause) {
  7759. loadPageOver();
  7760. return;
  7761. }
  7762. if (eles) {
  7763. ruleParser.insertPage(document, eles, nextLink, () => {
  7764. createPageBar(nextLink);
  7765. checkAutoLoadNum();
  7766. }, true);
  7767. } else {
  7768. debug("Stop as no page when get by js");
  7769. isPause = true;
  7770. loadPageOver();
  7771. }
  7772. };
  7773. try {
  7774. ((typeof _unsafeWindow.pagetualPageElementByJs == 'undefined') ? Function("over", "pageNum",'"use strict";' + ruleParser.curSiteRule.pageElementByJs) : _unsafeWindow.pagetualPageElementByJs)(over, curPage);
  7775. } catch(e) {
  7776. debug(e);
  7777. }
  7778. } else if ((forceState == 2 || ruleParser.curSiteRule.action == 2) && !isJs) {
  7779. forceIframe(nextLink, (iframe) => {
  7780. if (urlChanged || isPause) {
  7781. loadPageOver();
  7782. return;
  7783. }
  7784. let pageBar = createPageBar(nextLink);
  7785. if (pageBar && iframe && iframe.parentNode) iframe.parentNode.insertBefore(pageBar, iframe);
  7786. loadPageOver();
  7787. checkAutoLoadNum();
  7788. });
  7789. } else if ((forceState == 3 || ruleParser.curSiteRule.action == 1) && !isJs) {
  7790. requestFromIframe(nextLink, (doc, eles) => {
  7791. if (urlChanged || isPause) {
  7792. loadPageOver();
  7793. return;
  7794. }
  7795. if (eles) {
  7796. ruleParser.insertPage(doc, eles, nextLink, () => {
  7797. createPageBar(nextLink);
  7798. checkAutoLoadNum();
  7799. }, true);
  7800. } else loadPageOver();
  7801. });
  7802. } else {
  7803. if (!isJs) {
  7804. requestDoc(nextLink, (eles) => {
  7805. if (urlChanged || isPause) {
  7806. loadPageOver();
  7807. return;
  7808. }
  7809. if (eles) {
  7810. createPageBar(nextLink);
  7811. checkAutoLoadNum();
  7812. } else loadPageOver();
  7813. });
  7814. } else {
  7815. emuPage((doc, eles) => {
  7816. if (urlChanged || isPause) {
  7817. loadPageOver();
  7818. return;
  7819. }
  7820. if (eles) {
  7821. ruleParser.insertPage(doc, eles, "", () => {
  7822. createPageBar(nextLink);
  7823. checkAutoLoadNum();
  7824. }, true);
  7825. } else loadPageOver();
  7826. });
  7827. }
  7828. }
  7829. }, sleep);
  7830. }
  7831. }
  7832.  
  7833. function init() {
  7834. if (document.readyState == 'loading' || document.readyState == 'uninitialized') {
  7835. let domReady = e => {
  7836. initRules(() => {
  7837. initPage();
  7838. });
  7839. document.removeEventListener("DOMContentLoaded", domReady, false);
  7840. }
  7841. document.addEventListener("DOMContentLoaded", domReady, false);
  7842. } else {
  7843. initRules(() => {
  7844. initPage();
  7845. });
  7846. }
  7847. }
  7848.  
  7849. function visibilitychangeHandler() {
  7850. document.removeEventListener('visibilitychange', visibilitychangeHandler);
  7851. init();
  7852. }
  7853.  
  7854. setTimeout(() => {
  7855. if (document.hidden) {
  7856. document.addEventListener('visibilitychange', visibilitychangeHandler);
  7857. } else {
  7858. init();
  7859. }
  7860. }, 300);
  7861. })();

QingJ © 2025

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