东方永页机

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

当前为 2023-09-17 提交的版本,查看 最新版本

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

QingJ © 2025

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