东方永页机

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

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

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