东方永页机

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

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

  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.73
  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 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 && r.from != 1) {
  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. "[aria-label='next page']",
  2202. ".pagination-nav__item--next>a",
  2203. "a.pageright",
  2204. ".page-numbers.current+a",
  2205. ".page_current+a",
  2206. "input[value='next']",
  2207. "input[value='Next page']",
  2208. "input[value='下一页']",
  2209. "input[value='下一頁']",
  2210. "a#pb_next",
  2211. "a#rightFix",
  2212. "a#btnPreGn",
  2213. "a.page-next",
  2214. "a.pages-next",
  2215. "a.page.right",
  2216. "a#next",
  2217. ".next>a",
  2218. ".next>button",
  2219. "a[alt=next]",
  2220. ".pg_area>em+a",
  2221. "button.next:not([disabled])",
  2222. ".btn_next:not([disabled])",
  2223. ".btn-next:not([disabled])",
  2224. "a#linkNext",
  2225. "a[class*=page__next]"
  2226. ];
  2227. let next = await this.querySelectorList(body, selectorList);
  2228. if (!next) {
  2229. await sleep(1);
  2230. let nexts = body.querySelectorAll("a.next");
  2231. for (i = 0; i < nexts.length; i++) {
  2232. if (nexts[i].style.display !== "none" &&
  2233. nexts[i].parentNode.style.display !== "none" &&
  2234. !this.linkHasNoHref(nexts[i]) &&
  2235. !/^\s*([上前首尾]|previous)/i.test(nexts[i].innerText.trim())) {
  2236. next = nexts[i];
  2237. break;
  2238. }
  2239. }
  2240. }
  2241. if (next && this.linkHasNoHref(next)) {
  2242. jsNext = next;
  2243. next = null;
  2244. }
  2245. if (!next) {
  2246. await sleep(1);
  2247. next = body.querySelectorAll("[aria-label='Next page']");
  2248. if (next && next.length == 1) {
  2249. next = next[0];
  2250. if (this.linkHasNoHref(next)) {
  2251. if (!jsNext) jsNext = next;
  2252. next = null;
  2253. }
  2254. } else {
  2255. next = null;
  2256. }
  2257. }
  2258. if (jsNext) {
  2259. if (jsNext.className) {
  2260. if (/slick|slide|gallery/i.test(jsNext.className)) jsNext = null;
  2261. else if (jsNext.classList && jsNext.classList.contains('disabled')) jsNext = null;
  2262. }
  2263. if (jsNext) {
  2264. let ariaLabel = jsNext.getAttribute("aria-label");
  2265. if (ariaLabel && /slick|slide|gallery/i.test(ariaLabel)) jsNext = null;
  2266. }
  2267. }
  2268. if (next && nextTextReg2.test(next.innerText.trim())) {
  2269. next2 = next;
  2270. next = null;
  2271. }
  2272. if (!next) {
  2273. await sleep(1);
  2274. next = body.querySelector("a.curr+a") ||
  2275. body.querySelector("div.wp-pagenavi>span.current+a,div.page-nav>span.current+a,div.article-paging>span+a") ||
  2276. body.querySelector(".number>ul>li.active+li>a");;
  2277. }
  2278. if (!next) {
  2279. await sleep(1);
  2280. let pageDiv = body.querySelector("div.pages>ul");
  2281. if (pageDiv) {
  2282. cur = pageDiv.querySelector("li>b");
  2283. if (cur) next = cur.parentNode.nextElementSibling;
  2284. if (next) next = next.querySelector("a");
  2285. }
  2286. }
  2287. if (!next) {
  2288. await sleep(1);
  2289. next = body.querySelector(".pages>a[href='javascript:;']+a");
  2290. if (next && (next.href == "javascript:;" || next.getAttribute("href") == "#")) next = null;
  2291. }
  2292. if (!next) {
  2293. await sleep(1);
  2294. let pageDiv = body.querySelector(".pagination");
  2295. if (pageDiv) {
  2296. cur = pageDiv.querySelector("[class*=current]");
  2297. if (cur) next = cur.parentNode.nextElementSibling;
  2298. if (next) next = next.querySelector("a");
  2299. }
  2300. }
  2301. if (!next) {
  2302. await sleep(1);
  2303. let pageDivs = body.querySelectorAll("[class*=pagination],[class*=Pagination]");
  2304. if (pageDivs && pageDivs.length) {
  2305. for (let i = 0; i < pageDivs.length; i++) {
  2306. let p = pageDivs[i];
  2307. if (/(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)/i.test(p.title || p.value || '')) {
  2308. next = p.querySelector('a') || p;
  2309. break;
  2310. } else if (/^(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)$/i.test((p.innerText || '').trim())) {
  2311. next = p.querySelector('a') || p;
  2312. break;
  2313. }
  2314. }
  2315. if (next && this.linkHasNoHref(next)) {
  2316. if (!jsNext) jsNext = next;
  2317. next = null;
  2318. }
  2319. }
  2320. }
  2321. if (!next) {
  2322. let aTags = body.querySelectorAll("a,button,[type='button']");
  2323. for (i = aTags.length - 1; i >= 0; i--) {
  2324. if (next1) break;
  2325. if (i % 100 == 0) {
  2326. await sleep(1);
  2327. }
  2328. let aTag = aTags[i];
  2329. if (aTag.style.display == "none") continue;
  2330. let innerText = (aTag.innerText || aTag.value || aTag.title || '');
  2331. if (innerText) {
  2332. if (innerText == "§") continue;
  2333. innerText = innerText.trim();
  2334. if (innerText.length > 80) continue;
  2335. }
  2336. let availableHref = aTag.href && aTag.href.length < 250 && /^http/.test(aTag.href);
  2337. if (availableHref && /next\-?(page)?$/i.test(aTag.href)) continue;
  2338. if (aTag.className) {
  2339. if (/slick|slide|gallery/i.test(aTag.className)) continue;
  2340. if (aTag.classList && aTag.classList.contains('disabled')) continue;
  2341. }
  2342. if (aTag.dataset && aTag.dataset.preview) continue;
  2343. let ariaLabel = aTag.getAttribute("aria-label");
  2344. if (ariaLabel && /slick|slide|gallery/i.test(ariaLabel)) continue;
  2345.  
  2346. if (aTag.parentNode.className && /slick|slide|gallery/i.test(aTag.parentNode.className)) continue;
  2347. if (aTag.parentNode.parentNode) {
  2348. if (/slick|slide|gallery/i.test(aTag.parentNode.parentNode.className)) continue;
  2349. if (aTag.parentNode.parentNode.parentNode && /slick|slide|gallery/i.test(aTag.parentNode.parentNode.parentNode.className)) continue;
  2350. }
  2351. if (aTag.parentNode.classList && aTag.parentNode.classList.contains('disabled')) continue;
  2352. if (aTag.parentNode.classList && aTag.parentNode.classList.contains('active')) continue;
  2353. if (/^BLOCKQUOTE$/i.test(aTag.parentNode.nodeName)) continue;
  2354.  
  2355. if (aTag.previousElementSibling && /\b(play|volume)\b/.test(aTag.previousElementSibling.className)) continue;
  2356. if (aTag.nextElementSibling && /\b(play|volume)\b/.test(aTag.nextElementSibling.className)) continue;
  2357. let isJs = this.linkHasNoHref(aTag);
  2358. if (exist && isJs && !aTag.offsetParent) continue;
  2359. if (innerText) {
  2360. innerText = innerText.split(/\n/)[0].replace(/ /g, '');
  2361. if (isJs && /^(»|>>|>|›|→|❯)$/.test(innerText)) continue;
  2362. if (innerText && innerText.length <= 25) {
  2363. if (!next1) {
  2364. if (nextTextReg1.test(innerText)) {
  2365. if (isJs) {
  2366. if (!nextJs1) nextJs1 = aTag;
  2367. } else {
  2368. next1 = aTag;
  2369. }
  2370. }
  2371. }
  2372. if (!next4) {
  2373. if (!next2) {
  2374. if (nextTextReg2.test(innerText) || /nextpage|pager\-older/i.test(aTag.className) || /^(»|>>)$/.test(innerText)) {
  2375. if (isJs) {
  2376. if (!nextJs2) nextJs2 = aTag;
  2377. } else {
  2378. next2 = aTag;
  2379. }
  2380. }
  2381. }
  2382. if (!next3) {
  2383. if (/^(next\s*(»|>>|>|›|→|❯)|&gt;|▶|>|›|→|❯)$/i.test(innerText) && aTag.parentNode.hasAttribute && !aTag.parentNode.hasAttribute("jsaction")) {
  2384. if (isJs) {
  2385. if (!nextJs3) nextJs3 = aTag;
  2386. } else {
  2387. next3 = aTag;
  2388. }
  2389. }
  2390. }
  2391. }
  2392. }
  2393. }
  2394. if (isJs) continue;
  2395. if (!next4) {
  2396. let prevEle = aTag.previousElementSibling;
  2397. if (prevEle && (/^(B|SPAN|STRONG)$/i.test(prevEle.nodeName))) {
  2398. if (/^\d+$/.test(aTag.innerText.trim()) && /^\d+$/.test(prevEle.innerText.trim()) && parseInt(aTag.innerText) == parseInt(prevEle.innerText) + 1) {
  2399. next4 = aTag;
  2400. }
  2401. }
  2402. }
  2403. if (!next4 && availableHref) {
  2404. if (aTag.href.indexOf(location.hostname) === -1) continue;
  2405. let _aHref = aTag.href.replace("?&", "?").replace("index.php?", "?").toLowerCase();
  2406. if (preStr || afterStr) {
  2407. let _aHrefTrim = _aHref;
  2408. if (preStr) _aHrefTrim = _aHrefTrim.replace(preStr, "");
  2409. if (afterStr) _aHrefTrim = _aHrefTrim.replace(afterStr, "");
  2410. if (_aHrefTrim == pageNum + 1) {
  2411. next4 = aTag;
  2412. }
  2413. } else if (this.curUrl != aTag.href) {
  2414. _aHref = _aHref.replace(/\.s?html?$/i, "");
  2415. if (_aHref.indexOf(_url) != -1) {
  2416. let pageTwoMatch = _aHref.replace(_url, "").match(pageTwoReg);
  2417. if (pageTwoMatch) {
  2418. afterStr = pageTwoMatch[2];
  2419. next4 = aTag;
  2420. }
  2421. }
  2422. }
  2423. if (next4 && !/page/.test(next4.href)) {
  2424. let curHref = next4.getAttribute("href");
  2425. let curPageReg = new RegExp("(.*)" + (pageNum + 1) + afterStr.replace(/([\.\?])/g, '\\$1'));
  2426. let otherPageHref = curHref.replace(curPageReg, `$1${pageNum}${afterStr}`);
  2427. let otherPageEle = body.querySelector(`a[href='${otherPageHref}']`);
  2428. if (!otherPageEle) {
  2429. otherPageHref = curHref.replace(curPageReg, `$1${pageNum + 2}${afterStr}`);
  2430. otherPageEle = body.querySelector(`a[href='${otherPageHref}']`);
  2431. }
  2432. if (otherPageEle) {
  2433. let parent = otherPageEle.parentNode;
  2434. if (parent && parent.parentNode) {
  2435. parent = parent.parentNode;
  2436. if (parent.parentNode) {
  2437. parent = parent.parentNode;
  2438. }
  2439. }
  2440. if (parent && parent.contains(otherPageEle) && !/^\d+$/.test(otherPageEle.innerText.trim())) {
  2441. next4 = null;
  2442. }
  2443. } else {
  2444. next4 = null;
  2445. }
  2446. }
  2447. }
  2448. }
  2449. if (next2 && doubtTextReg.test(next2.innerText)) {
  2450. next2 = this.verifyNext(next2, doc);
  2451. }
  2452. if (nextJs2 && doubtTextReg.test(nextJs2.innerText)) {
  2453. nextJs2 = this.verifyNext(nextJs2, doc);
  2454. }
  2455. if (next3) {
  2456. next3 = this.verifyNext(next3, doc);
  2457. }
  2458. if (nextJs3) {
  2459. nextJs3 = this.verifyNext(nextJs3, doc);
  2460. }
  2461. }
  2462. if (!next) next = next1 || next4 || next3 || next2;
  2463. if (!next) {
  2464. next = jsNext || nextJs1 || nextJs3 || nextJs2;
  2465. if (next && next.parentNode.className.indexOf('tab') != -1) next = null;
  2466. }
  2467. if (next && next.classList && (next.classList.contains("results-more") || next.classList.contains("no"))) next = null;
  2468. if (next && next.hasAttribute && next.hasAttribute("disabled")) next = null;
  2469. return {next:next, canSave:canSave};
  2470. }
  2471.  
  2472. verifyNext(next, doc) {
  2473. if (!next) return null;
  2474. if (next.previousElementSibling && /^BR$/i.test(next.previousElementSibling.nodeName)) return null;
  2475. let eles = [];
  2476. if (next.innerText && next.innerText.indexOf("\n") == -1) {
  2477. eles = getAllElements(`//${next.nodeName}[text()='${next.innerText}']`, doc);
  2478. }
  2479. if (eles.length >= 2 && eles[0].href != eles[1].href) {
  2480. next = null;
  2481. } else if (doc == document) {
  2482. let left = getElementLeft(next);
  2483. if (left < 20 || (document.documentElement.scrollWidth > 500 && left < 250)) {
  2484. next = null;
  2485. } else {
  2486. let top = getElementTop(next);
  2487. if (top < 20 || (left < window.innerWidth / 3 && top < window.innerHeight / 3)) {
  2488. next = null;
  2489. } else {
  2490. let bottom = top + next.offsetHeight || 0;
  2491. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  2492. if (scrollH - bottom < 10) next = null;
  2493. }
  2494. }
  2495. }
  2496. return next;
  2497. }
  2498.  
  2499. canonicalUri(src) {
  2500. if (!src) {
  2501. return "";
  2502. }
  2503. if (src.charAt(0) == "#") return this.curUrl + src;
  2504. if (src.charAt(0) == "?") return this.curUrl.replace(/^([^\?#]+).*/, "$1" + src);
  2505. let origin = location.protocol + '//' + location.host;
  2506. let url = this.basePath || origin;
  2507. url = url.replace(/(\?|#).*/, "");
  2508. if (/https?:\/\/[^\/]+$/.test(url)) url = url + '/';
  2509. if (url.indexOf("http") !== 0) url = origin + url;
  2510. var root_page = /^[^\?#]*\//.exec(url)[0],
  2511. root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  2512. absolute_regex = /^\w+\:\/\//;
  2513. this.updateUrl = false;
  2514. while (src.indexOf("../") === 0) {
  2515. src = src.substr(3);
  2516. root_page = root_page.replace(/\/[^\/]+\/$/, "/");
  2517. this.updateUrl = true;
  2518. }
  2519. src = src.replace(/\.\//, "");
  2520. if (/^\/\/\/?/.test(src)) {
  2521. src = location.protocol + src;
  2522. }
  2523. return (absolute_regex.test(src) ? src : ((src.charAt(0) == "/" ? root_domain : root_page) + src));
  2524. }
  2525.  
  2526. getLinkByPage(url, pageNum) {
  2527. if (!url) return null;
  2528. if (this.curSiteRule.pageNum) {
  2529. let result = this.curSiteRule.pageNum;
  2530. let strMatch = result.match(/\{.*?}/);
  2531. if (!strMatch) return null;
  2532. let urlReg = new RegExp("(" + result.replace(strMatch[0], ")\\d+(") + ")", "i");
  2533. let code = strMatch[0].replace(/^{/, "").replace(/}$/, "").replace(/\$p/g, pageNum);
  2534. if (code == pageNum) {
  2535. result = url.replace(urlReg, "$1" + code + "$2");
  2536. } else {
  2537. try {
  2538. code = Function('"use strict";return ' + code)();
  2539. if (code && code % 1 == 0) {
  2540. result = url.replace(urlReg, "$1" + code + "$2");
  2541. } else return null;
  2542. } catch(e) {
  2543. debug(e);
  2544. }
  2545. }
  2546. if (result != url) {
  2547. return result;
  2548. }
  2549. }
  2550. return url.replace(/([&\/\?](p=|page[=\/_-]?))\d+/i, "$1" + pageNum).replace(/([_-])\d+\./i, "$1" + pageNum + ".");
  2551. }
  2552.  
  2553. getPageNumFromUrl(url, defaultPage) {
  2554. if (!url) return defaultPage;
  2555. if (this.curSiteRule.pageNum) {
  2556. let result = this.curSiteRule.pageNum;
  2557. let strMatch = result.match(/\{.*?}/);
  2558. if (!strMatch) return defaultPage;
  2559. let urlReg = new RegExp(".*" + result.replace(strMatch[0], "(\\d+)") + ".*", "i");
  2560. let curShowNum = url.replace(urlReg, "$1");
  2561. if (curShowNum != url) {
  2562. let code = strMatch[0].replace(/^{/, "").replace(/}$/, "");
  2563. if (code == "$p") {
  2564. return curShowNum;
  2565. } else {
  2566. try {
  2567. let page1 = parseInt(Function('"use strict";return ' + code.replace("$p", "0"))());
  2568. let page2 = parseInt(Function('"use strict";return ' + code.replace("$p", "1"))());
  2569. let numGap = page2 - page1;
  2570. let _page = (parseInt(curShowNum) - page1) / numGap;
  2571. if (_page && _page % 1 == 0) return _page;
  2572. else {
  2573. this.curSiteRule.pageNum = null;
  2574. return defaultPage;
  2575. }
  2576. } catch(e) {
  2577. debug(e);
  2578. }
  2579. }
  2580. } else {
  2581. return defaultPage;
  2582. }
  2583. }
  2584. let pageNum = url.replace(/.*[&\/\?](p=|page[=\/_-]?)(\d+).*/i, "$2");
  2585. return pageNum == url ? defaultPage : (pageNum.length > 4 ? defaultPage : pageNum);
  2586. }
  2587.  
  2588. async getNextLink(doc, exist) {
  2589. let nextLink = null, page, href;
  2590. let getNextLinkByForm = (form, submitBtn, n) => {
  2591. let params = [];
  2592. let formData = new FormData(form);
  2593. if (submitBtn && submitBtn.getAttribute) {
  2594. let btnValue, btnName;
  2595. btnName = submitBtn.getAttribute("name");
  2596. btnValue = submitBtn.getAttribute("value");
  2597. if (btnName && btnValue) params = [btnName + "=" + encodeURIComponent(btnValue)];
  2598. }
  2599. for (let [key, value] of formData) {
  2600. if (n && /^(p|page)$/i.test(key)) {
  2601. params.push(key + '=' + n);
  2602. } else {
  2603. params.push(key + '=' + encodeURIComponent(value));
  2604. }
  2605. }
  2606. params = params.join('&');
  2607. return form.action + (form.action.indexOf('?') == -1 ? '?' : '&') + params + (form.method == 'post' ? '#p{' + params + '}' : '');
  2608. };
  2609. if (this.curSiteRule.pageElementByJs) {
  2610. this.nextLinkHref = "#";
  2611. return true;
  2612. } else if (this.curSiteRule.nextLinkByJs) {
  2613. try {
  2614. let over = _url => {
  2615. };
  2616. let targetUrl = await ((typeof this.curSiteRule.nextLinkByJs == 'function') ? this.curSiteRule.nextLinkByJs : new AsyncFunction("doc", '"use strict";' + this.curSiteRule.nextLinkByJs))(doc);
  2617. if (targetUrl) nextLink = {href: targetUrl};
  2618. } catch(e) {
  2619. debug(e);
  2620. }
  2621. } else if (this.curSiteRule.nextLinkByUrl) {
  2622. let targetUrl = this.curUrl.replace(new RegExp(this.curSiteRule.nextLinkByUrl[0], "i"), this.curSiteRule.nextLinkByUrl[1]);
  2623. if (targetUrl != this.curUrl) {
  2624. let includeSel = this.curSiteRule.nextLinkByUrl[2];
  2625. let excludeSel = this.curSiteRule.nextLinkByUrl[3];
  2626. if (includeSel) {
  2627. includeSel = includeSel.trim();
  2628. if (!getElement(includeSel, doc)) {
  2629. this.nextLinkHref=false;
  2630. return null;
  2631. }
  2632. }
  2633. if (excludeSel) {
  2634. excludeSel = excludeSel.trim();
  2635. if (getElement(excludeSel, doc)) {
  2636. this.nextLinkHref=false;
  2637. return null;
  2638. }
  2639. }
  2640. let reps = targetUrl.match(/{.*?}/g);
  2641. if (reps) {
  2642. reps.forEach(rep => {
  2643. let code = rep.replace("{", "").replace("}", "").replace(/\(\)/g, "0");
  2644. let result = code.match(/^(\d*)\+1$/);
  2645. if (result) {
  2646. result = parseInt(result[1] || 1) + 1;
  2647. } else {
  2648. try {
  2649. result = Function('"use strict";return ' + code)();
  2650. } catch(e) {
  2651. debug(e);
  2652. }
  2653. }
  2654. targetUrl = targetUrl.replace(rep, result);
  2655. });
  2656. }
  2657. }
  2658. nextLink = {href: targetUrl};
  2659. } else if (typeof this.curSiteRule.nextLink != 'undefined') {
  2660. let nextLinkSel = this.curSiteRule.nextLink;
  2661. if (nextLinkSel != 0) {
  2662. if (Array && Array.isArray && Array.isArray(nextLinkSel)) {
  2663. nextLink = getElement(nextLinkSel[nextIndex], doc, null, true);
  2664. if (!nextLink && curPage == 1 && nextIndex != 0) {
  2665. nextIndex = 0;
  2666. nextLink = getElement(nextLinkSel[nextIndex], doc, null, true);
  2667. }
  2668. } else nextLink = getElement(nextLinkSel, doc, null, true);
  2669. }
  2670. if (nextLink && (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2)) {
  2671. let form = doc.querySelector('#search-form');
  2672. if (!nextLink.href && nextLink.hasAttribute && nextLink.hasAttribute("onclick") && form) {
  2673. if (/^\d+$/.test(nextLink.innerText)) {
  2674. nextLink.href = getNextLinkByForm(form, nextLink, nextLink.innerText);
  2675. }
  2676. } else if (/^INPUT$/i.test(nextLink.nodeName) || nextLink.type == "submit") {
  2677. form = nextLink.parentNode;
  2678. while (form) {
  2679. if (/^FORM$/i.test(form.nodeName)) break;
  2680. else form = form.parentNode;
  2681. }
  2682. if (form) {
  2683. nextLink.href = getNextLinkByForm(form, nextLink);
  2684. }
  2685. }
  2686. if (nextLink.href && this.curSiteRule.action != 0) {
  2687. nextLink.href = nextLink.href.replace(/#p{.*/, "");
  2688. }
  2689. }
  2690. } else {
  2691. page = await this.getPage(doc, exist);
  2692. nextLink = page.next;
  2693. if (nextLink) {
  2694. if (/^INPUT$/i.test(nextLink.nodeName) || nextLink.type == "submit") {
  2695. if (!/next/i.test(nextLink.getAttribute("onclick"))) {
  2696. let form = nextLink.parentNode;
  2697. while (form) {
  2698. if (/^FORM$/i.test(form.nodeName)) break;
  2699. else form = form.parentNode;
  2700. }
  2701. if (form) {
  2702. nextLink.href = getNextLinkByForm(form, nextLink);
  2703. }
  2704. }
  2705. }
  2706. let parent = nextLink;
  2707. while (parent && !/^BODY$/i.test(parent.nodeName)) {
  2708. if (parent.hasAttribute && parent.hasAttribute("disabled")) {
  2709. this.nextLinkHref = false;
  2710. return null;
  2711. }
  2712. if (parent.className && parent.classList) {
  2713. if (parent.classList.contains("noClick") || parent.classList.contains("no-pages") || parent.classList.contains("disabled")) {
  2714. this.nextLinkHref = false;
  2715. return null;
  2716. }
  2717. }
  2718. if (parent.style && parent.style.display === "none") {
  2719. this.nextLinkHref = false;
  2720. return null;
  2721. }
  2722. parent = parent.parentNode;
  2723. }
  2724. if (doc == document) {
  2725. if (this.linkHasNoHref(nextLink) && (clickedSth || !isVisible(nextLink, _unsafeWindow))) {
  2726. this.nextLinkHref = false;
  2727. return null;
  2728. } else {
  2729. let nextLinkCs = _unsafeWindow.getComputedStyle(nextLink);
  2730. if (nextLinkCs.cursor == "not-allowed") {
  2731. this.nextLinkHref = false;
  2732. return null;
  2733. }
  2734. this.initNext = nextLink;
  2735. }
  2736. }
  2737. let form = doc.querySelector('#search-form');
  2738. if (!nextLink.href && nextLink.hasAttribute("onclick") && form) {
  2739. if (form && /^\d+$/.test(nextLink.innerText)) {
  2740. href = getNextLinkByForm(form, nextLink, nextLink.innerText);
  2741. }
  2742. }
  2743. }
  2744. }
  2745. if (nextLink) {
  2746. if (!this.checkStopSign(nextLink, doc)) {
  2747. if (curPage > 1 && rulesData.lastPageTips) showTips(i18n("lastPage"));
  2748. return null;
  2749. }
  2750. if (this.curSiteRule.action == 3) {
  2751. if (doc == document) debug(nextLink, 'Next link');
  2752. this.nextLinkHref = '#';
  2753. } else {
  2754. let needUrl = (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2);
  2755. if (!href) href = nextLink.href;
  2756. if (href && nextLink.getAttribute) {
  2757. let _href = nextLink.getAttribute("href");
  2758. if (_href) {
  2759. if (_href.charAt(0) == "#" || _href == "?"){
  2760. href = "#";
  2761. } else {
  2762. href = _href;
  2763. }
  2764. } else if (_href === "") {
  2765. href = _href;
  2766. }
  2767. }
  2768.  
  2769. if (needUrl && (href === "" || href === null)) {
  2770. this.nextLinkHref = false;
  2771. } else if (needUrl && /^(javascript:|#)/.test(href)) {
  2772. this.nextLinkHref = false;
  2773. } else {
  2774. this.nextLinkHref = (href && !/^(javascript:|#)/.test(href)) ? this.canonicalUri(href) : "#";
  2775. let tempUrl = this.nextLinkHref;
  2776. 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 + "#"))) {
  2777. this.nextLinkHref = false;
  2778. } else if (doc == document) {
  2779. debug(nextLink, 'Next link');
  2780. }
  2781. }
  2782. }
  2783. } else {
  2784. this.nextLinkHref = false;
  2785. }
  2786. this.nextLinkEle = nextLink;
  2787. this.preload();
  2788. return nextLink;
  2789. }
  2790.  
  2791. compareUrl(url1, url2) {
  2792. if (url1 == url2) return true;
  2793. if (!url1 || !url2) return false;
  2794. let url1Arr = url1.split("?");
  2795. let url2Arr = url2.split("?");
  2796. if (url1Arr[0] != url2Arr[0]) return false;
  2797. if (!url1Arr[1] || !url2Arr[1]) return false;
  2798. url1Arr = url1Arr[1].split("&").sort().join("&");
  2799. url2Arr = url2Arr[1].split("&").sort().join("&");
  2800. return url1Arr == url2Arr;
  2801. }
  2802.  
  2803. filterEles(doc, eles) {
  2804. let filter = this.curSiteRule.filter;
  2805. if (!filter || !eles || eles.length === 0) return;
  2806. if (eles.length === 1) {
  2807. eles = eles[0].children;
  2808. if (eles.length === 1) {
  2809. eles = eles[0].children;
  2810. }
  2811. }
  2812. if (typeof filter == "string") {
  2813. if (/^\d+$/.test(filter)) {
  2814. filter = {count: parseInt(filter)};
  2815. } else filter = {words: filter};
  2816. }
  2817. [].forEach.call(eles, ele => {
  2818. if (!ele.parentNode) return;
  2819. let canKeep = (() => {
  2820. let innerText = (ele.innerText && ele.innerText.trim()) || "";
  2821. if (filter.count) {
  2822. if (innerText.length < filter.count) return false;
  2823. }
  2824. if (filter.words) {
  2825. let wordsRegExp = new RegExp(filter.words, "i");
  2826. if (innerText && wordsRegExp.test(innerText)) return false;
  2827. }
  2828. if (filter.link) {
  2829. let linkRegExp = new RegExp(filter.link, "i");
  2830. if (/^A$/i.test(ele.nodeName) && linkRegExp.test(ele.href)) return false;
  2831. let aChildren = ele.querySelectorAll("a");
  2832. for (let i = 0; i < aChildren.length; i++) {
  2833. let child = aChildren[i];
  2834. if (linkRegExp.test(child.href)) return false;
  2835. }
  2836. }
  2837. if (filter.selector) {
  2838. if (getElement(filter.selector, doc, ele)) return false;
  2839. }
  2840. return true;
  2841. })();
  2842. if (!canKeep) {
  2843. ele.parentNode.removeChild(ele);
  2844. }
  2845. });
  2846. }
  2847.  
  2848. checkStopSign(nextLink, doc) {
  2849. if (this.curSiteRule.stopSign) {
  2850. let typeArray = Array && Array.isArray && Array.isArray(this.curSiteRule.stopSign);
  2851. let typeObject = !typeArray && (this.curSiteRule.stopSign.include || this.curSiteRule.stopSign.exclude || this.curSiteRule.stopSign.pageNum);
  2852. if (typeArray || typeObject) {
  2853. let includeSel, excludeSel, curSign, maxSign;
  2854. if (typeArray) {
  2855. includeSel = this.curSiteRule.stopSign[0];
  2856. excludeSel = this.curSiteRule.stopSign[1];
  2857. curSign = this.curSiteRule.stopSign[2];
  2858. maxSign = this.curSiteRule.stopSign[3];
  2859. if (Array && Array.isArray && Array.isArray(includeSel) && !curSign) {
  2860. curSign = includeSel;
  2861. includeSel = false;
  2862. }
  2863. if (excludeSel && Array && Array.isArray && Array.isArray(excludeSel) && !maxSign) {
  2864. maxSign = excludeSel;
  2865. excludeSel = false;
  2866. }
  2867. } else {
  2868. includeSel = this.curSiteRule.stopSign.include;
  2869. excludeSel = this.curSiteRule.stopSign.exclude;
  2870. curSign = this.curSiteRule.stopSign.pageNum;
  2871. }
  2872. if (includeSel) {
  2873. includeSel = includeSel.trim();
  2874. if (!getElement(includeSel, doc)) {
  2875. isPause = true;
  2876. this.nextLinkHref = false;
  2877. return false;
  2878. }
  2879. }
  2880. if (excludeSel) {
  2881. excludeSel = excludeSel.trim();
  2882. if (getElement(excludeSel, doc)) {
  2883. isPause = true;
  2884. this.nextLinkHref = false;
  2885. return false;
  2886. }
  2887. }
  2888. if (curSign) {
  2889. if (!maxSign) maxSign = curSign.slice(2);
  2890. let currentEle = getElement(curSign[0], doc);
  2891. let maxEle = getElement(maxSign[0], doc);
  2892. if (currentEle && maxEle) {
  2893. let currentSignNum, maxSignNum;
  2894. if (/\(.*\)/.test(curSign[1])) {
  2895. currentSignNum = currentEle.innerText.match(new RegExp(curSign[1]));
  2896. if (currentSignNum) currentSignNum = currentSignNum[1];
  2897. } else if (currentEle.getAttribute) {
  2898. currentSignNum = currentEle.getAttribute(curSign[1]);
  2899. }
  2900. if (/\(.*\)/.test(maxSign[1])) {
  2901. maxSignNum = maxEle.innerText.match(new RegExp(maxSign[1]));
  2902. if (maxSignNum) maxSignNum = maxSignNum[1];
  2903. } else if (maxEle.getAttribute) {
  2904. maxSignNum = maxEle.getAttribute(maxSign[1]);
  2905. }
  2906. if (currentSignNum && maxSignNum && currentSignNum == maxSignNum) {
  2907. isPause = true;
  2908. this.nextLinkHref = false;
  2909. return false;
  2910. }
  2911. }
  2912. }
  2913. } else {
  2914. try {
  2915. let stopSign = ((typeof this.curSiteRule.stopSign == 'function') ? this.curSiteRule.stopSign : Function("doc", "nextLink", '"use strict";' + this.curSiteRule.stopSign))(doc, nextLink);
  2916. if (stopSign) {
  2917. isPause = true;
  2918. this.nextLinkHref = false;
  2919. return false;
  2920. }
  2921. } catch(e) {
  2922. debug(e);
  2923. }
  2924. }
  2925. }
  2926. return true;
  2927. }
  2928.  
  2929. preload() {
  2930. if (!rulesData.preload) return;
  2931. if (!this.nextLinkHref || this.nextLinkHref == "#") return;
  2932. let self = this, url = this.nextLinkHref;
  2933. let postParams = url.match(/#p{(.*)}$/);
  2934. if (postParams) {
  2935. postParams = postParams[1];
  2936. url = url.replace(/#p{.*/, "");
  2937. }
  2938. _GM_xmlhttpRequest({
  2939. url: url,
  2940. method: postParams ? 'POST' : 'GET',
  2941. data: postParams,
  2942. overrideMimeType: 'text/html;charset=' + (document.characterSet || document.charset || document.inputEncoding),
  2943. headers: {
  2944. 'Referer': location.href,
  2945. 'User-Agent': navigator.userAgent,
  2946. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + (document.characterSet || document.charset || document.inputEncoding),
  2947. },
  2948. timeout: 10000,
  2949. onload: function(res) {
  2950. var doc = null;
  2951. try {
  2952. doc = document.implementation.createHTMLDocument('');
  2953. doc.documentElement.innerHTML = createHTML(res.response);
  2954. var body = getBody(doc);
  2955. if (body && body.firstChild) {
  2956. self.lazyImgAction(body.children);
  2957. }
  2958. if (!self.preloadDiv) {
  2959. self.preloadDiv = document.createElement('div');
  2960. self.preloadDiv.id = "pagetual-preload";
  2961. self.preloadDiv.style.cssText = 'display:none!important;';
  2962. getBody(document).appendChild(self.preloadDiv);
  2963. self.checkedImgs = {};
  2964. }
  2965. [].forEach.call(doc.images, i => {
  2966. let iSrc = i.src;
  2967. if (iSrc && !self.checkedImgs[iSrc]) {
  2968. self.checkedImgs[iSrc] = true;
  2969. let img = document.createElement('img');
  2970. img.src = iSrc;
  2971. self.preloadDiv.appendChild(img);
  2972. }
  2973. });
  2974. let code = self.curSiteRule.preloadImages;
  2975. if (code) {
  2976. let imgSrcArr = new Function("doc", '"use strict";' + code)(doc);
  2977. if (imgSrcArr && imgSrcArr.length) {
  2978. imgSrcArr.forEach(imgSrc => {
  2979. if (imgSrc && !self.checkedImgs[imgSrc]) {
  2980. self.checkedImgs[imgSrc] = true;
  2981. let img = document.createElement('img');
  2982. img.src = imgSrc;
  2983. self.preloadDiv.appendChild(img);
  2984. }
  2985. });
  2986. }
  2987. }
  2988. }
  2989. catch(e) {
  2990. debug(e);
  2991. return;
  2992. }
  2993. }
  2994. });
  2995. }
  2996.  
  2997. getInsert(refresh) {
  2998. if (refresh) {
  2999. this.insert = null;
  3000. }
  3001. if (this.insert && document.documentElement.contains(this.insert)) {
  3002. return this.insert;
  3003. }
  3004. if (this.curSiteRule.insert) {
  3005. let insertSel = this.curSiteRule.insert;
  3006. if (Array && Array.isArray && Array.isArray(insertSel)) {
  3007. insertSel = insertSel[nextIndex < insertSel.length ? nextIndex : 0];
  3008. }
  3009. this.insert = getElement(insertSel, document, null, true);
  3010. } else {
  3011. this.docPageElement = null;
  3012. let pageElement = this.getPageElement(document, _unsafeWindow);
  3013. if (this.curSiteRule.singleUrl && this.nextLinkHref == "#" && this.curSiteRule.pageElement === 'body') {
  3014. debug("Stop as jsNext & whole body");
  3015. isPause = true;
  3016. return null;
  3017. }
  3018. if (pageElement && pageElement.length > 0) {
  3019. var pELast = pageElement[pageElement.length - 1];
  3020. this.insert = pELast.nextSibling ? pELast.nextSibling : pELast.parentNode.appendChild(document.createTextNode(' '));
  3021. }
  3022. }
  3023. return this.insert;
  3024. }
  3025.  
  3026. pageInit(doc, eles) {
  3027. let code = this.curSiteRule.pageInit;
  3028. if (code) {
  3029. let initFunc = ((typeof code == 'function') ? code : Function("doc", "eles", '"use strict";' + code));
  3030. let checkInit = (resolve) => {
  3031. try {
  3032. if (initFunc(doc, eles) === false) {
  3033. setTimeout(() => {
  3034. checkInit(resolve);
  3035. }, 100);
  3036. } else {
  3037. resolve(true);
  3038. }
  3039. } catch(e) {
  3040. resolve(false);
  3041. debug(e);
  3042. }
  3043. };
  3044. return new Promise((resolve) => {
  3045. checkInit(function(e) {
  3046. resolve(e)
  3047. });
  3048. })
  3049. }
  3050. }
  3051.  
  3052. pageAction(doc, eles) {
  3053. let code = this.curSiteRule.pageAction;
  3054. if (code) {
  3055. try {
  3056. ((typeof code == 'function') ? code : Function("doc", "eles", '"use strict";' + code))(doc, eles);
  3057. } catch(e) {
  3058. debug(e);
  3059. }
  3060. }
  3061. this.openInNewTab(eles);
  3062. this.replaceElement(doc);
  3063. }
  3064.  
  3065. openInNewTab(eles) {
  3066. if (openInNewTab) {
  3067. [].forEach.call(eles, ele => {
  3068. if (/^A$/i.test(ele.nodeName) && ele.href && !/^(mailto:|javascript:)|#/.test(ele.href)) {
  3069. ele.setAttribute('target', openInNewTab == 1 ? '_blank' : '_self');
  3070. } else {
  3071. [].forEach.call(ele.querySelectorAll('a[href]:not([href^="mailto:"]):not([href^="javascript:"]):not([href^="#"])'), a => {
  3072. if (openInNewTab == 1) {
  3073. a.setAttribute('target', '_blank');
  3074. if (a.getAttribute('onclick') == 'atarget(this)') {
  3075. a.removeAttribute('onclick');
  3076. }
  3077. } else a.setAttribute('target', '_self');
  3078. });
  3079. }
  3080. });
  3081. }
  3082. }
  3083.  
  3084. lazyImgAction(eles) {
  3085. if (!eles || eles.length == 0) return;
  3086. let lazyImgSrc = this.curSiteRule.lazyImgSrc;
  3087. if (lazyImgSrc === 0 || lazyImgSrc === '0') return;
  3088. let setLazyImg = img => {
  3089. let realSrc;
  3090. if (lazyImgSrc) {
  3091. if (!Array.isArray(lazyImgSrc)) {
  3092. lazyImgSrc = [lazyImgSrc];
  3093. }
  3094. realSrc = img.getAttribute(lazyImgSrc[0]);
  3095. if (lazyImgSrc.length == 2) {
  3096. let removeProps = lazyImgSrc[1].split(",");
  3097. removeProps.forEach(prop => {
  3098. img.removeAttribute(prop.trim());
  3099. });
  3100. }
  3101. if (realSrc) img.src = realSrc;
  3102. }
  3103. if (!realSrc) {
  3104. let lazyAttr = "";
  3105. if (img.getAttribute("_src") && !img.src) {
  3106. lazyAttr = "_src";
  3107. realSrc = img.getAttribute(lazyAttr);
  3108. } else {
  3109. for (let i in lazyImgAttr) {
  3110. lazyAttr = lazyImgAttr[i];
  3111. let attrValue = img.getAttribute(lazyAttr);
  3112. if (attrValue) {
  3113. realSrc = attrValue;
  3114. break;
  3115. }
  3116. }
  3117. }
  3118. if (!realSrc && img._lazyrias && img._lazyrias.srcset) {
  3119. realSrc = img._lazyrias.srcset[img._lazyrias.srcset.length - 1];
  3120. lazyAttr = "_lazyrias";
  3121. }
  3122. if (!realSrc && img.srcset) {
  3123. lazyAttr = "srcset";
  3124. var srcs = img.srcset.split(/[xw],/i), largeSize = 0;
  3125. srcs.forEach(srci => {
  3126. let srcInfo = srci.trim().split(" "), curSize = parseInt(srcInfo[1]);
  3127. if (srcInfo[1] && curSize > largeSize) {
  3128. largeSize = curSize;
  3129. realSrc = srcInfo[0];
  3130. }
  3131. });
  3132. }
  3133. if (realSrc) {
  3134. img.src = realSrc;
  3135. img.removeAttribute("srcset");
  3136. img.removeAttribute(lazyAttr);
  3137. if (img.style.display == "none") {
  3138. img.style.display = "";
  3139. }
  3140. if (img.style.visibility == "hidden") {
  3141. img.style.visibility = "";
  3142. }
  3143. if (img.style.opacity == 0) {
  3144. img.style.opacity = "";
  3145. }
  3146. }
  3147. }
  3148. };
  3149. [].forEach.call(eles, ele => {
  3150. if (/^IMG$/i.test(ele.nodeName)) {
  3151. setLazyImg(ele);
  3152. } else {
  3153. [].forEach.call(ele.querySelectorAll("img,picture>source"), img => {
  3154. setLazyImg(img);
  3155. });
  3156. [].forEach.call(ele.querySelectorAll("div[data-src][data-thumb],div.img[data-src],div.lazy[data-src]"), div => {
  3157. div.style.setProperty("background-image", "url(" + div.dataset.src + ")", "important");
  3158. });
  3159. }
  3160. if (/^A$/i.test(ele.nodeName) && ele.classList.contains("lazyload")) {
  3161. if (ele.dataset.original) {
  3162. ele.style.backgroundImage = 'url("' + ele.dataset.original + '")';
  3163. }
  3164. } else {
  3165. [].forEach.call(ele.querySelectorAll("a.lazyload"), a => {
  3166. if (a.dataset.original) {
  3167. a.style.backgroundImage = 'url("' + a.dataset.original + '")';
  3168. }
  3169. });
  3170. }
  3171. });
  3172. }
  3173.  
  3174. initPage(callback) {
  3175. let self = this;
  3176. if (self.initing) return;
  3177. self.initing = true;
  3178. setTimeout(() => {
  3179. self.initing = false;
  3180. }, 100);
  3181. curPage = 1;
  3182. urlChanged = false;
  3183. this.clearAddedElements();
  3184. this.insert = null;
  3185. this.visibilityItems = [];
  3186. this.visibleIndex = -1;
  3187. this.pageDoc = document;
  3188. this.nextLinkHref = null;
  3189. this.curUrl = location.href;
  3190. this.oldUrl = "";
  3191. this.initUrl = location.href;
  3192. this.historyUrl = "";
  3193. let base = document.querySelector("base");
  3194. this.basePath = base ? base.href : location.href;
  3195. this.getRule(async () => {
  3196. isPause = manualPause;
  3197. if (self.curSiteRule.enable == 0) {
  3198. debug("Stop as rule disable");
  3199. isPause = true;
  3200. _GM_registerMenuCommand(i18n("enable"), () => {
  3201. showTips(i18n("enableSiteTips"));
  3202. if(!self.customRules) {
  3203. self.customRules = [];
  3204. }
  3205. for (let i in self.customRules) {
  3206. if (self.customRules[i].url == self.curSiteRule.url) {
  3207. self.customRules.splice(i, 1);
  3208. break;
  3209. }
  3210. }
  3211. self.curSiteRule.enable = 1;
  3212. self.customRules.unshift(self.curSiteRule);
  3213. storage.setItem("customRules", self.customRules);
  3214. location.reload();
  3215. });
  3216. return;
  3217. }
  3218. //若是再亂匹配就不緩存wedata,或者只在找完本地規則之後再考慮wedata的緩存
  3219. if (self.curSiteRule.singleUrl) {
  3220. delete self.curSiteRule.pageElement;
  3221. self.smartRules = self.smartRules.filter(item => {return item && item.url != self.curSiteRule.url});
  3222. self.smartRules.unshift(self.curSiteRule);
  3223. if (self.smartRules.length > 100) {
  3224. self.smartRules.pop();
  3225. }
  3226. storage.setItem("smartRules", self.smartRules);
  3227. } else if (self.curSiteRule && self.curSiteRule.url.length > 13) {
  3228. self.addToHpRules();
  3229. }
  3230. let css = self.curSiteRule.css || rulesData.customCss;
  3231. if (css) {
  3232. let cssArr = css.split("inIframe:");
  3233. if (cssArr && cssArr.length) {
  3234. _GM_addStyle(cssArr[0]);
  3235. }
  3236. }
  3237. if (/sidesearch=(1|true)$/.test(self.curUrl)) {
  3238. openInNewTab = 0;
  3239. } else if (typeof self.curSiteRule.openInNewTab !== 'undefined') {
  3240. openInNewTab = self.curSiteRule.openInNewTab ? 1 : 2;
  3241. }
  3242. let autoClick = self.curSiteRule.autoClick;
  3243. if (autoClick) {
  3244. let autoClickBtn;
  3245. autoClickBtn = getElement(autoClick, document, null, true);
  3246. if (autoClickBtn) {
  3247. emuClick(autoClickBtn);
  3248. }
  3249. }
  3250. let code = self.curSiteRule.init;
  3251. if (code) {
  3252. try {
  3253. ((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)});
  3254. } catch(e) {
  3255. debug(e);
  3256. }
  3257. }
  3258. await self.getNextLink(document, true);
  3259. if (self.curSiteRule.pageNum && self.nextLinkHref && self.nextLinkHref != "#") {
  3260. let num1st = self.getPageNumFromUrl(location.href, 1);
  3261. let num2nd = self.getPageNumFromUrl(self.nextLinkHref, 1);
  3262. if (num2nd != num1st + 1) {
  3263. self.curSiteRule.pageNum = null;
  3264. }
  3265. }
  3266. if (self.curSiteRule.singleUrl && self.nextLinkHref == false && self.possibleRule) {
  3267. setTimeout(() => {
  3268. self.initPage(() => {});
  3269. }, 3000);
  3270. }
  3271. self.refreshByClick();
  3272.  
  3273. let pageElementCss = self.curSiteRule.pageElementCss || rulesData.pageElementCss;
  3274. if (pageElementCss && pageElementCss !== '0') {
  3275. self.getPageElement(document, _unsafeWindow);
  3276. }
  3277. callback();
  3278. let initRun = typeof self.curSiteRule.initRun == 'undefined' ? rulesData.initRun : self.curSiteRule.initRun;
  3279. if (self.nextLinkHref) {
  3280. sideController.setup();
  3281. if (initRun && initRun != false) {
  3282. setTimeout(() => {
  3283. nextPage();
  3284. }, 500);
  3285. }
  3286. }
  3287. });
  3288. }
  3289.  
  3290. beginLoading() {
  3291. isLoading = true;
  3292. let lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3293. ruleParser.insertElement(loadingDiv);
  3294. if (forceState == 2) {
  3295. getBody(document).appendChild(loadingDiv);
  3296. } else {
  3297. let parent = loadingDiv.parentNode;
  3298. if (/^TBODY$/i.test(parent.nodeName)) {
  3299. parent = parent.parentNode;
  3300. }
  3301. if (/^TABLE$/i.test(parent.nodeName)) {
  3302. parent.parentNode.appendChild(loadingDiv);
  3303. }
  3304. }
  3305. getBody(document).scrollTop = lastScrollTop;
  3306. document.documentElement.scrollTop = lastScrollTop;
  3307. }
  3308.  
  3309. insertElement(ele) {
  3310. if (!this.insert || !this.insert.parentNode) {
  3311. this.getInsert();
  3312. }
  3313. if (this.insert) {
  3314. let self = this;
  3315. if (ele.nodeName == "#document-fragment") {
  3316. [].forEach.call(ele.children, el => {
  3317. self.addedElePool.push(el);
  3318. });
  3319. } else {
  3320. this.addedElePool.push(ele);
  3321. }
  3322. if (this.curSiteRule.insertPos == 2 || this.curSiteRule.insertPos == "in") {
  3323. this.insert.appendChild(ele);
  3324. } else {
  3325. this.insert.parentNode.insertBefore(ele, this.insert);
  3326. }
  3327. }
  3328. }
  3329.  
  3330. noValidContent(url) {
  3331. if (!this.curSiteRule.nextLinkByUrl) showTips(i18n("noValidContent"), url);
  3332. }
  3333.  
  3334. async insertPage(doc, eles, url, callback, tried) {
  3335. this.oldUrl = this.curUrl;
  3336. let oldTitle = this.pageDoc.title;
  3337. this.pageDoc = doc;
  3338. this.curUrl = url;
  3339. isLoading = true;
  3340. let nextLink = await this.getNextLink(doc);
  3341. this.nextTitle = "";
  3342. if (this.curSiteRule.pageBarText) {
  3343. if (this.curSiteRule.pageBarText == 1 || this.curSiteRule.pageBarText == true) {
  3344. this.nextTitle = doc.title;
  3345. } else {
  3346. try {
  3347. this.nextTitle = ((typeof this.curSiteRule.pageBarText == 'function') ? this.curSiteRule.pageBarText : Function("doc",'"use strict";' + this.curSiteRule.pageBarText))(doc);
  3348. } catch(e) {
  3349. debug(e);
  3350. }
  3351. }
  3352. }
  3353. if (curPage == 1 && !tried && !nextLink && this.curSiteRule.singleUrl && this.curSiteRule.pageElement && this.curSiteRule.action != 0) {
  3354. this.curSiteRule.action = 1;
  3355. this.curUrl = location.href;
  3356. isLoading = false;
  3357. return false;
  3358. }
  3359. let lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3360. this.getInsert();
  3361. var self = this, newEles = [];
  3362. if (!eles || eles.length == 0 || !self.insert || !self.insert.parentNode) {
  3363. if (callback) callback(eles);
  3364. loadPageOver();
  3365. } else {
  3366. await this.pageInit(doc, eles);
  3367. if (callback) callback(eles);
  3368. loadPageOver();
  3369. const collection = document.createDocumentFragment();
  3370. [].forEach.call(eles, ele => {
  3371. let newEle = ele.cloneNode(true);
  3372. let oldCanvass = ele.querySelectorAll("canvas");
  3373. let newCanvass = newEle.querySelectorAll("canvas");
  3374. if (self.updateUrl) {
  3375. [].forEach.call(newEle.querySelectorAll("img"), img => {
  3376. if (img.getAttribute("src")) img.src = self.canonicalUri(img.getAttribute("src"));
  3377. });
  3378. [].forEach.call(newEle.querySelectorAll("a"), a => {
  3379. if (a.getAttribute("href")) a.href = self.canonicalUri(a.getAttribute("href"));
  3380. });
  3381. }
  3382. for (let i = 0; i < oldCanvass.length; i++) {
  3383. let oldCanvas = oldCanvass[i];
  3384. let newCanvas = newCanvass[i];
  3385. newCanvas.getContext('2d').drawImage(oldCanvas, 0, 0);
  3386. }
  3387. if (!/^(STYLE|SCRIPT)$/.test(newEle.nodeName)) self.visibilityItems.push(newEle);
  3388. collection.appendChild(newEle)
  3389. newEles.push(newEle);
  3390. });
  3391. self.insertElement(collection);
  3392. }
  3393. getBody(document).scrollTop = lastScrollTop;
  3394. document.documentElement.scrollTop = lastScrollTop;
  3395. this.pageAction(doc, newEles);
  3396. let enableHistory = this.curSiteRule.history;
  3397. let enableHistoryAfterInsert = false;
  3398. if (enableHistory == 1) {
  3399. enableHistory = true;
  3400. } else if (enableHistory == 2) {
  3401. enableHistory = true;
  3402. enableHistoryAfterInsert = true;
  3403. } else if (enableHistory == 0) {
  3404. enableHistory = false;
  3405. } else {
  3406. enableHistory = rulesData.enableHistory;
  3407. enableHistoryAfterInsert = rulesData.enableHistoryAfterInsert;
  3408. }
  3409. if (enableHistory) {
  3410. this.historyUrl = enableHistoryAfterInsert ? this.curUrl : this.oldUrl;
  3411. if(this.historyUrl != location.href) {
  3412. let isJs = this.hrefIsJs(this.historyUrl);
  3413. if (!isJs) {
  3414. let historyTitle = enableHistoryAfterInsert ? doc.title : oldTitle;
  3415. _unsafeWindow.history.replaceState(undefined, historyTitle, this.historyUrl);
  3416. document.title = historyTitle;
  3417. }
  3418. }
  3419. }
  3420. isLoading = false;
  3421. return true;
  3422. }
  3423. }
  3424. var ruleParser = new RuleParser();
  3425.  
  3426. class SideController {
  3427. //static controller;
  3428. constructor() {
  3429. this.inited = false;
  3430. }
  3431.  
  3432. /*static getInstance() {
  3433. if (!SideController.controller) {
  3434. SideController.controller = new SideController();
  3435. }
  3436. return SideController.controller;
  3437. }*/
  3438.  
  3439. setup() {
  3440. if (ruleParser.curSiteRule.sideController === false) return;
  3441. if (!rulesData.sideController && !ruleParser.curSiteRule.sideController) return;
  3442. this.addToStage();
  3443. }
  3444.  
  3445. init() {
  3446. if (this.inited) return;
  3447. this.inited = true;
  3448. let self = this;
  3449. this.cssText = `
  3450. #pagetual-sideController {
  3451. position: fixed;
  3452. top: calc(50% - 83px);
  3453. left: calc(99% - 40px);
  3454. width: 40px;
  3455. border-radius: 20px;
  3456. box-shadow: rgb(0 0 0) 0px 0px 10px;
  3457. text-align: center;
  3458. background: #ffffffd0!important;
  3459. user-select: none;
  3460. z-index: 2147483646!important;
  3461. padding: 0!important;
  3462. opacity: 0.35;
  3463. transition: opacity .5s ease, background .5s, box-shadow .5s;
  3464. }
  3465. #pagetual-sideController:hover {
  3466. opacity: 1;
  3467. }
  3468. #pagetual-sideController * {
  3469. font-weight: bold;
  3470. font-family: arial;
  3471. font-style: normal;
  3472. font-size: 20px!important;
  3473. color: black!important;
  3474. line-height: normal;
  3475. float: none;
  3476. }
  3477. #pagetual-sideController.stop {
  3478. -webkit-filter: invert(100%);
  3479. filter: invert(100%);
  3480. }
  3481. .pagetual-sideController-btn {
  3482. padding: 5px 0;
  3483. cursor: pointer;
  3484. transition: transform .15s ease-in-out, opacity .3s ease;
  3485. }
  3486. #pagetual-sideController .pagetual-sideController-btn:hover {
  3487. transform: scale(1.5);
  3488. color: red!important;
  3489. }
  3490. #pagetual-sideController.minSize {
  3491. box-shadow: rgb(0 0 0 / 0%) 0px 0px 0px;
  3492. background: #00000000!important;
  3493. }
  3494. #pagetual-sideController.minSize .pagetual-sideController-btn {
  3495. opacity: 0;
  3496. }
  3497. #pagetual-sideController #pagetual-sideController-move > svg {
  3498. transition: transform .3s ease;
  3499. }
  3500. #pagetual-sideController #pagetual-sideController-move > svg:hover {
  3501. transform: scale(1.2);
  3502. }
  3503. #pagetual-sideController.minSize #pagetual-sideController-move > svg {
  3504. background: white;
  3505. opacity: 0;
  3506. }
  3507. #pagetual-sideController #pagetual-sideController-move > img,
  3508. #pagetual-sideController #pagetual-sideController-move > span {
  3509. width: 35px;
  3510. height: 35px;
  3511. cursor: pointer;
  3512. }
  3513. #pagetual-sideController.minSize #pagetual-sideController-move > img,
  3514. #pagetual-sideController.minSize #pagetual-sideController-move > span {
  3515. border-radius: 50px;
  3516. text-shadow: rgb(255 255 255) 0px 0px 10px;
  3517. }
  3518. #pagetual-sideController #pagetual-sideController-pagenum {
  3519. font-size: 15px!important;
  3520. line-height: 30px;
  3521. text-align: center;
  3522. position: absolute;
  3523. right: calc(50% - 15px);
  3524. top: calc(50% - 15px);
  3525. border: 1px solid #00000099;
  3526. display: inline-block;
  3527. width: 30px;
  3528. height: 30px;
  3529. box-sizing: border-box;
  3530. border-radius: 50%;
  3531. background: white;
  3532. opacity: 0;
  3533. transition: opacity .5s ease;
  3534. pointer-events: none;
  3535. }
  3536. #pagetual-sideController.minSize #pagetual-sideController-pagenum {
  3537. opacity: 0.8;
  3538. }
  3539. `;
  3540. let frame = document.createElement("div");
  3541. frame.id = "pagetual-sideController";
  3542. frame.innerHTML = createHTML(`
  3543. <div id="pagetual-sideController-top" class="pagetual-sideController-btn">⊼</div>
  3544. <div>
  3545. <div id="pagetual-sideController-pre" class="pagetual-sideController-btn">∧</div>
  3546. <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>
  3547. <div id="pagetual-sideController-next" class="pagetual-sideController-btn">∨</div>
  3548. </div>
  3549. <div id="pagetual-sideController-bottom" class="pagetual-sideController-btn">⊻</div>
  3550. `);
  3551. frame.classList.add("stop");
  3552. let top = frame.querySelector("#pagetual-sideController-top");
  3553. let pre = frame.querySelector("#pagetual-sideController-pre");
  3554. let move = frame.querySelector("#pagetual-sideController-move");
  3555. let next = frame.querySelector("#pagetual-sideController-next");
  3556. let bottom = frame.querySelector("#pagetual-sideController-bottom");
  3557. let pagenum = frame.querySelector("#pagetual-sideController-pagenum");
  3558. if (sideControllerIcon) move.innerHTML = sideControllerIcon;
  3559.  
  3560. frame.addEventListener("dblclick", e => {
  3561. e.preventDefault();
  3562. e.stopPropagation();
  3563. });
  3564.  
  3565. frame.addEventListener("mouseenter", e => {
  3566. clearTimeout(self.hideTimer);
  3567. frame.classList.remove("minSize");
  3568. });
  3569.  
  3570. frame.addEventListener("mouseleave", e => {
  3571. clearTimeout(self.hideTimer);
  3572. self.hideTimer = setTimeout(() => {
  3573. frame.classList.add("minSize");
  3574. }, 800);
  3575. });
  3576.  
  3577. pre.addEventListener("click", e => {
  3578. let prePageBar = getPageBar().preBar;
  3579. if (prePageBar) {
  3580. scrollToPageBar(prePageBar);
  3581. } else {
  3582. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3583. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  3584. }
  3585. }, true);
  3586.  
  3587. next.addEventListener("click", e => {
  3588. let pageBarObj = getPageBar();
  3589. let nextPageBar = pageBarObj.nextBar;
  3590. if (nextPageBar) {
  3591. scrollToPageBar(nextPageBar);
  3592. } else {
  3593. if (pageBarObj.preBar) {
  3594. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  3595. window.scrollTo({ top: (scrollH || 9999999), behavior: 'smooth'});
  3596. } else {
  3597. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3598. window.scrollTo({ top: scrollTop + (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  3599. }
  3600. }
  3601. }, true);
  3602.  
  3603. top.addEventListener("click", e => {
  3604. getBody(document).scrollTop=0;
  3605. document.documentElement.scrollTop=0;
  3606. e.preventDefault();
  3607. e.stopPropagation();
  3608. }, true);
  3609.  
  3610. bottom.addEventListener("click", e => {
  3611. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  3612. changeStop(true);
  3613. }
  3614. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  3615. getBody(document).scrollTop = scrollH || 9999999;
  3616. document.documentElement.scrollTop = scrollH || 9999999;
  3617. e.preventDefault();
  3618. e.stopPropagation();
  3619. }, true);
  3620.  
  3621. let initX, initY, moving = false;
  3622. let removeTimer;
  3623. move.addEventListener("click", e => {
  3624. if (!moving) {
  3625. changeStop(!isPause);
  3626. }
  3627. }, true);
  3628. move.addEventListener("dblclick", e => {
  3629. clearTimeout(removeTimer);
  3630. document.removeEventListener("mousemove", mouseMoveHandler, true);
  3631. document.removeEventListener("mouseup", mouseUpHandler, true);
  3632. changeStop(!isPause);
  3633. if (isPause) {
  3634. ruleParser.hideAddedElements();
  3635. } else {
  3636. ruleParser.showAddedElements();
  3637. }
  3638. }, true);
  3639.  
  3640. move.oncontextmenu = e => {
  3641. e.preventDefault();
  3642. picker.start();
  3643. };
  3644.  
  3645. let mouseMoveHandler = e => {
  3646. if (moving) {
  3647. let windowHeight=window.innerHeight || document.documentElement.clientHeight;
  3648. let windowWidth=window.innerWidth || document.documentElement.clientWidth;
  3649. initX = (e.clientX - 10 + 40) / windowWidth * 100;
  3650. initY = (e.clientY - 83 + 83) / windowHeight * 100;
  3651. this.frame.style.top = `calc(${initY}% - 83px)`;
  3652. this.frame.style.left = `calc(${initX}% - 40px)`;
  3653. } else if (Math.abs(e.clientX - initX) + Math.abs(e.clientY - initY) > 20) {
  3654. moving = true;
  3655. clearTimeout(removeTimer);
  3656. }
  3657. };
  3658. let mouseUpHandler = e => {
  3659. clearTimeout(removeTimer);
  3660. document.removeEventListener("mousemove", mouseMoveHandler, true);
  3661. document.removeEventListener("mouseup", mouseUpHandler, true);
  3662. if (moving) {
  3663. rulesData.sideControllerPos = {x: parseInt(initX), y: parseInt(initY)};
  3664. storage.setItem("rulesData", rulesData);
  3665. }
  3666. };
  3667.  
  3668. move.addEventListener("mousedown", e => {
  3669. initX = e.clientX;
  3670. initY = e.clientY;
  3671. moving = false;
  3672. clearTimeout(removeTimer);
  3673. removeTimer = setTimeout(() => {
  3674. self.remove();
  3675. }, 1500);
  3676. document.addEventListener("mousemove", mouseMoveHandler, true);
  3677. document.addEventListener("mouseup", mouseUpHandler, true);
  3678. }, true);
  3679.  
  3680. this.frame = frame;
  3681. this.pagenum = pagenum;
  3682. if (rulesData.sideControllerPos) {
  3683. this.frame.style.top = `calc(${rulesData.sideControllerPos.y}% - 83px)`;
  3684. this.frame.style.left = `calc(${rulesData.sideControllerPos.x}% - 40px)`;
  3685. }
  3686. }
  3687.  
  3688. addToStage() {
  3689. this.init();
  3690. if (!this.styleEle || !this.styleEle.parentNode) {
  3691. this.styleEle = _GM_addStyle(this.cssText);
  3692. }
  3693. if (!isPause) {
  3694. this.frame.classList.remove("stop");
  3695. }
  3696. this.pagenum.innerHTML = createHTML(curPage);
  3697. this.frame.title = i18n("page") + curPage;
  3698. if (this.frame.parentNode) return;
  3699. getBody(document).appendChild(this.frame);
  3700. clearTimeout(this.hideTimer);
  3701. this.frame.classList.add("minSize");
  3702. }
  3703.  
  3704. remove() {
  3705. if (this.frame && this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  3706. }
  3707. }
  3708. const sideController = new SideController();
  3709.  
  3710. class NextSwitch {
  3711. //static nextSwitch;
  3712. constructor() {
  3713. this.inited = false;
  3714. }
  3715.  
  3716. /*static getInstance() {
  3717. if (!NextSwitch.nextSwitch) {
  3718. NextSwitch.nextSwitch = new NextSwitch();
  3719. }
  3720. return NextSwitch.nextSwitch;
  3721. }*/
  3722.  
  3723. init() {
  3724. if (this.inited) return;
  3725. this.inited = true;
  3726. let self = this;
  3727. this.cssText = `
  3728. #pagetual-nextSwitch {
  3729. position: fixed;
  3730. top: 10px;
  3731. left: calc(50% - 160px);
  3732. background: aliceblue;
  3733. padding: 10px;
  3734. border-radius: 5px;
  3735. text-align: center;
  3736. opacity: 0.95;
  3737. color: #161616;
  3738. z-index: 2147483647;
  3739. font-size: 16px;
  3740. box-shadow: rgb(0 0 0) 0px 0px 10px;
  3741. }
  3742. #pagetual-nextSwitch>.title {
  3743. margin: -5px 45px 10px 45px;
  3744. font-size: 20px;
  3745. font-weight: bold;
  3746. border-bottom: 1px solid black;
  3747. user-select: none;
  3748. color: orangered;
  3749. }
  3750. #pagetual-nextSwitch>.group {
  3751. display: flex;
  3752. flex-direction: column;
  3753. }
  3754. #pagetual-nextSwitch>.group>span {
  3755. color: #161616;
  3756. cursor: pointer;
  3757. margin: 3px;
  3758. font-size: larger;
  3759. }
  3760. #pagetual-nextSwitch>.group>span:hover {
  3761. color: red;
  3762. }
  3763. #pagetual-nextSwitch>.group>span.current {
  3764. border: 2px dotted red;
  3765. border-radius: 10px;
  3766. }
  3767. #pagetual-nextSwitch>.closeSwitch {
  3768. position: absolute;
  3769. top: 3px;
  3770. right: 10px;
  3771. background: none;
  3772. border: none;
  3773. vertical-align: top;
  3774. transition: transform .15s ease-in-out;
  3775. float: right;
  3776. cursor: pointer;
  3777. }
  3778. #pagetual-nextSwitch svg {
  3779. width: 30px;
  3780. height: 30px;
  3781. vertical-align: middle;
  3782. fill: #161616;
  3783. overflow: hidden;
  3784. }
  3785. #pagetual-nextSwitch button:hover {
  3786. transform: scale(1.2);
  3787. }
  3788. `;
  3789. let frame = document.createElement("div");
  3790. frame.id = "pagetual-nextSwitch";
  3791. frame.innerHTML = createHTML(`
  3792. <div class="title">${i18n("nextSwitch")}</div>
  3793. <button type="button" class="closeSwitch">
  3794. <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2754">
  3795. <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">
  3796. </path>
  3797. </svg>
  3798. </button>
  3799. <div class="group"></div>
  3800. `);
  3801. let group = frame.querySelector(".group");
  3802. let closeBtn = frame.querySelector(".closeSwitch");
  3803. closeBtn.addEventListener("click", e => {
  3804. self.close();
  3805. }, true);
  3806. this.frame = frame;
  3807. let currentSpan;
  3808. ruleParser.curSiteRule.nextLink.forEach((link, i) => {
  3809. let span = document.createElement("span");
  3810. let target = getElement(link, document);
  3811. let index = "<b>" + (i + 1) + "</b>: ";
  3812. if (target) {
  3813. let targetInner = target.innerText.trim();
  3814. span.innerHTML = index + (targetInner || link);
  3815. } else {
  3816. span.innerHTML = index + "Not Found";
  3817. }
  3818. span.title = link;
  3819. span.addEventListener("click", e => {
  3820. if (currentSpan) currentSpan.classList.remove("current");
  3821. span.classList.add("current");
  3822. currentSpan = span;
  3823. nextIndex = i;
  3824. storage.setItem("nextSwitch_" + location.host, nextIndex === 0 ? "" : nextIndex);
  3825. ruleParser.curUrl += "#pagetual";
  3826. ruleParser.oldUrl = ruleParser.curUrl;
  3827. autoLoadNum = -1;
  3828. if (!ruleParser.nextLinkHref) {
  3829. isLoading = false;
  3830. }
  3831. ruleParser.getNextLink(ruleParser.pageDoc || document);
  3832. self.close();
  3833. }, true);
  3834. if (i == nextIndex) {
  3835. span.classList.add("current");
  3836. currentSpan = span;
  3837. }
  3838. group.appendChild(span);
  3839. });
  3840. }
  3841.  
  3842. start() {
  3843. this.init();
  3844. if (!this.styleEle || !this.styleEle.parentNode) {
  3845. this.styleEle = _GM_addStyle(this.cssText);
  3846. }
  3847. document.documentElement.appendChild(this.frame);
  3848. }
  3849.  
  3850. close() {
  3851. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  3852. }
  3853. }
  3854. const nextSwitch = new NextSwitch();
  3855.  
  3856. class Picker {
  3857. //static picker;
  3858. constructor() {
  3859. this.inited = false;
  3860. }
  3861.  
  3862. /*static getInstance() {
  3863. if (!Picker.picker) {
  3864. Picker.picker = new Picker();
  3865. }
  3866. return Picker.picker;
  3867. }*/
  3868.  
  3869. init() {
  3870. if (this.inited) return;
  3871. this.inited = true;
  3872. let self = this;
  3873. this.signList = [];
  3874. this.cssText = `
  3875. body.pagetual-picker,
  3876. body.pagetual-picker *:hover,
  3877. body.pagetual-picker a:hover {
  3878. cursor: crosshair !important;
  3879. }
  3880. #pagetual-picker {
  3881. position: fixed;
  3882. top: 10px;
  3883. left: calc(50% - 178px);
  3884. background: aliceblue;
  3885. padding: 10px;
  3886. border-radius: 5px;
  3887. text-align: center;
  3888. opacity: 0.95;
  3889. color: #161616;
  3890. z-index: 2147483646;
  3891. font-size: 16px;
  3892. overflow: hidden;
  3893. box-shadow: rgb(0 0 0) 0px 0px 10px;
  3894. }
  3895. #pagetual-picker * {
  3896. margin: 0;
  3897. padding: 0;
  3898. font-family: Times New Roman;
  3899. overflow: initial;
  3900. user-select: none;
  3901. }
  3902. #pagetual-picker>.title {
  3903. margin: -5px 45px 10px 45px;
  3904. font-size: 20px;
  3905. font-weight: bold;
  3906. cursor: move;
  3907. border-bottom: 1px solid black;
  3908. user-select: none;
  3909. color: orangered;
  3910. height: initial;
  3911. width: initial;
  3912. position: initial;
  3913. }
  3914. #pagetual-picker button {
  3915. background: none;
  3916. border: none;
  3917. vertical-align: top;
  3918. transition: transform .15s ease-in-out;
  3919. float: right;
  3920. cursor: pointer;
  3921. overflow: hidden;
  3922. background-color: unset!important;
  3923. }
  3924. #pagetual-picker button:hover {
  3925. transform: scale(1.2);
  3926. }
  3927. #pagetual-picker>.closePicker {
  3928. position: absolute;
  3929. top: 3px;
  3930. right: 10px;
  3931. }
  3932. #pagetual-picker>.logoIcon {
  3933. position: absolute;
  3934. top: 3px;
  3935. left: 10px;
  3936. }
  3937. #pagetual-picker>.logoIcon.showSign>svg>path {
  3938. fill: gray;
  3939. }
  3940. #pagetual-picker textarea{
  3941. display: inline-block;
  3942. width: calc(100% - 65px);
  3943. height: 20px;
  3944. min-width: 290px;
  3945. max-width: calc(65vw - 50px);
  3946. min-height: unset;
  3947. padding: 6px 12px;
  3948. font-size: 16px;
  3949. font-weight: 400;
  3950. line-height: 1.5;
  3951. color: #495057;
  3952. background-color: #fff;
  3953. background-clip: padding-box;
  3954. border: 1px solid #ced4da;
  3955. border-radius: 4px;
  3956. transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
  3957. box-sizing: content-box;
  3958. margin-right: 5px;
  3959. resize: both;
  3960. box-shadow: 0 1px 5px 1px #ddd;
  3961. }
  3962. #pagetual-picker textarea:focus {
  3963. color: black;
  3964. background-color: #fff;
  3965. border-color: #80bdff;
  3966. outline: 0;
  3967. box-shadow: 0 0 0 3.2px rgb(0 123 255 / 25%);
  3968. }
  3969. #pagetual-picker [type=checkbox],
  3970. #pagetual-picker [type=radio] {
  3971. line-height: 20px;
  3972. height: 25px;
  3973. width: 25px;
  3974. margin-left: 5px;
  3975. vertical-align: middle;
  3976. appearance: auto;
  3977. display: inline-block;
  3978. position: initial;
  3979. }
  3980. #pagetual-picker label {
  3981. font-size: 18px;
  3982. line-height: 25px;
  3983. vertical-align: middle;
  3984. display: inline-block;
  3985. color: black;
  3986. position: initial;
  3987. cursor: pointer;
  3988. }
  3989. #pagetual-picker .bottom {
  3990. text-align: left;
  3991. margin: 10px 0;
  3992. width: 100%;
  3993. }
  3994. #pagetual-picker .bottom>button {
  3995. float: right;
  3996. }
  3997. #pagetual-picker svg {
  3998. width: 30px;
  3999. height: 30px;
  4000. vertical-align: middle;
  4001. fill: #161616;
  4002. overflow: hidden;
  4003. }
  4004. #pagetual-picker svg * {
  4005. pointer-events: none;
  4006. }
  4007. #pagetual-picker .allpath {
  4008. font-size: 18px;
  4009. margin: 10px auto;
  4010. max-width: 330px;
  4011. word-break: break-all;
  4012. cursor: context-menu;
  4013. overflow: hidden;
  4014. max-height: 42px;
  4015. -moz-transition:max-height 1s ease-in;
  4016. -webkit-transition:max-height 1s ease-in;
  4017. transition:max-height 1s ease-in;
  4018. color: black;
  4019. }
  4020. #pagetual-picker .allpath:hover {
  4021. max-height: calc(100vh - 130px);
  4022. overflow: auto;
  4023. }
  4024. #pagetual-picker .allpath>span.path {
  4025. cursor: pointer;
  4026. }
  4027. #pagetual-picker .allpath>span.path:hover {
  4028. color: orangered;
  4029. }
  4030. #pagetual-picker .moreConfig {
  4031. display: flex;
  4032. justify-content: space-between;
  4033. border-top: 1px solid;
  4034. padding-top: 10px;
  4035. width: 100%;
  4036. }
  4037. #pagetual-picker .command {
  4038. width: 100%;
  4039. color: black!important;
  4040. text-align: center;
  4041. font-size: large;
  4042. margin-top: 10px;
  4043. box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.12);
  4044. border-radius: 5px;
  4045. }
  4046. #pagetual-picker .command:hover {
  4047. color: orangered;
  4048. }
  4049. #pagetual-picker #showDetail {
  4050. float: initial;
  4051. margin-top: 10px;
  4052. }
  4053. #pagetual-picker.showDetail #showDetail {
  4054. float: right;
  4055. }
  4056. #pagetual-picker #showDetail>svg {
  4057. -moz-transition:transform 0.3s ease;
  4058. -webkit-transition:transform 0.3s ease;
  4059. transition:transform 0.3 ease;
  4060. }
  4061. #pagetual-picker.showDetail #showDetail>svg {
  4062. transform: rotate(180deg);
  4063. }
  4064. #pagetual-picker .tempRule {
  4065. display: none;
  4066. margin-top: 10px;
  4067. height: 300px;
  4068. min-height: 150px;
  4069. }
  4070. #pagetual-picker.showDetail .tempRule {
  4071. display: inline-block;
  4072. }
  4073. #pagetual-picker #saveDetail {
  4074. display: none;
  4075. position: absolute;
  4076. bottom: 10px;
  4077. right: 8px;
  4078. }
  4079. #pagetual-picker.showDetail #saveDetail {
  4080. display: inline-block;
  4081. }
  4082. #pagetual-picker #saveDetail svg {
  4083. width: 35px;
  4084. height: 35px;
  4085. }
  4086. #pagetual-picker .addProp {
  4087. display: none;
  4088. flex-direction: column;
  4089. position: absolute;
  4090. bottom: 45px;
  4091. right: 12px;
  4092. }
  4093. #pagetual-picker.showDetail .addProp {
  4094. display: flex;
  4095. }
  4096. #pagetual-picker .addProp>button {
  4097. font-size: 30px;
  4098. font-family: Arial,sans-serif;
  4099. line-height: 35px;
  4100. color: #161616;
  4101. }
  4102. `;
  4103. this.mainSignDiv = this.createSignDiv();
  4104. this.allSignDiv = [];
  4105. let frame = document.createElement("div");
  4106. frame.id = "pagetual-picker";
  4107. frame.innerHTML = createHTML(`
  4108. <button title="Pagetual" type="button" class="logoIcon">
  4109. <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>
  4110. </button>
  4111. <div class="title" title="${i18n("configure")}">${i18n("picker")}</div>
  4112. <button title="${i18n("closePicker")}" type="button" class="closePicker">
  4113. <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>
  4114. </button>
  4115. <div class="allpath" title="${i18n("switchSelector")}"></div>
  4116. <div>
  4117. <textarea class="selector" spellcheck="false" name="selector" placeholder="${i18n("pickerPlaceholder")}"></textarea>
  4118. <button id="check" title="${i18n("pickerCheck")}" type="button">
  4119. <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>
  4120. </button>
  4121. </div>
  4122. <div class="bottom">
  4123. <input name="xpath" id="checkbox_id" type="checkbox" />
  4124. <label for="checkbox_id">XPath</label>
  4125. <button id="edit" title="${i18n("gotoEdit")}" type="button">
  4126. <svg viewBox="0 0 1024 1024" style="color: orangered;fill: orangered;" version="1.1" xmlns="http://www.w3.org/2000/svg">
  4127. <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">
  4128. </path>
  4129. </svg>
  4130. </button>
  4131. </div>
  4132. <div class="moreConfig">
  4133. <div title="${i18n('forceStateIframe')}">
  4134. <input name="forceState" id="forceStateIframe" type="radio" />
  4135. <label for="forceStateIframe">${i18n('iframe')}</label>
  4136. </div>
  4137. <div title="${i18n('forceStateDynamic')}">
  4138. <input name="forceState" id="forceStateDynamic" type="radio" />
  4139. <label for="forceStateDynamic">${i18n('dynamic')}</label>
  4140. </div>
  4141. <div title="${i18n('forceStateDisable')}">
  4142. <input name="forceState" id="forceStateDisable" type="radio" />
  4143. <label for="forceStateDisable">${i18n('disable')}</label>
  4144. </div>
  4145. </div>
  4146. <button id="nextSwitch" class="command" title="${i18n("nextSwitch")}" type="button">${i18n("nextSwitch")}</button>
  4147. <button id="loadNow" class="command" title="${i18n("loadNow")}" type="button">${i18n("loadNow")}</button>
  4148. <button id="autoScroll" class="command" title="${i18n("toggleAutoScroll")}" type="button"></button>
  4149. <div>
  4150. <textarea class="tempRule" spellcheck="false" placeholder="{Rule object}" title="Rule for current site"></textarea>
  4151. <button id="showDetail" title="" type="button">
  4152. <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>
  4153. </button>
  4154. <div class="addProp">
  4155. <button id="addOtherProp" title="${i18n("addOtherProp")}" type="button">+</button>
  4156. <button id="addNextSelector" title="${i18n("addNextSelector")}" type="button">></button>
  4157. <button id="addPageSelector" title="${i18n("addPageSelector")}" type="button">❏</button>
  4158. </div>
  4159. <button id="saveDetail" title="${i18n("save")}" type="button">
  4160. <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>
  4161. </button>
  4162. </div>
  4163. `);
  4164. let forceStateIframe = frame.querySelector("#forceStateIframe");//forceState 1 禁用 2 强嵌 3 动态
  4165. let forceStateDynamic = frame.querySelector("#forceStateDynamic");
  4166. let forceStateDisable = frame.querySelector("#forceStateDisable");
  4167. let clickRadio = e => {
  4168. let radio = e.currentTarget.querySelector('input');
  4169. if (radio.checked) {
  4170. forceState = "";
  4171. } else {
  4172. switch (radio.id) {
  4173. case "forceStateIframe":
  4174. forceState = 2;
  4175. break;
  4176. case "forceStateDynamic":
  4177. forceState = 3;
  4178. break;
  4179. case "forceStateDisable":
  4180. forceState = 1;
  4181. break;
  4182. default:
  4183. return;
  4184. }
  4185. }
  4186. storage.setItem("forceState_" + location.host, forceState);
  4187. self.close();
  4188. location.reload();
  4189. };
  4190. forceStateIframe.parentNode.addEventListener("mousedown", clickRadio);
  4191. forceStateDynamic.parentNode.addEventListener("mousedown", clickRadio);
  4192. forceStateDisable.parentNode.addEventListener("mousedown", clickRadio);
  4193. if (forceState == 1) forceStateDisable.checked = true;
  4194. else if (forceState == 2) forceStateIframe.checked = true;
  4195. else if (forceState == 3) forceStateDynamic.checked = true;
  4196. let closeBtn = frame.querySelector(".closePicker");
  4197. let logoBtn = frame.querySelector(".logoIcon");
  4198. let title = frame.querySelector(".title");
  4199. let allpath = frame.querySelector(".allpath");
  4200. let selectorInput = frame.querySelector(".selector");
  4201. let xpath = frame.querySelector("#checkbox_id");
  4202. let checkBtn = frame.querySelector("#check");
  4203. let editBtn = frame.querySelector("#edit");
  4204. let nextSwitchBtn = frame.querySelector("#nextSwitch");
  4205. let autoScrollBtn = frame.querySelector("#autoScroll");
  4206. let loadNow = frame.querySelector("#loadNow");
  4207. let tempRule = frame.querySelector(".tempRule");
  4208. let showDetailBtn = frame.querySelector("#showDetail");
  4209. let saveDetailBtn = frame.querySelector("#saveDetail");
  4210. let addOtherProp = frame.querySelector("#addOtherProp");
  4211. let addNextSelector = frame.querySelector("#addNextSelector");
  4212. let addPageSelector = frame.querySelector("#addPageSelector");
  4213. autoScrollBtn.addEventListener("click", e => {
  4214. self.close();
  4215. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), 50)) || 0;
  4216. autoScroll = parseInt(autoScroll) || 0;
  4217. if (autoScroll < 0) autoScroll = 0;
  4218. else if (autoScroll > 1000) autoScroll = 1000;
  4219. storage.setItem("autoScroll_" + location.host + location.pathname, autoScroll);
  4220. startAutoScroll();
  4221. }, true);
  4222. addOtherProp.addEventListener("click", e => {
  4223. let propName = prompt(i18n("propName"));
  4224. if (!propName) return;
  4225. let propValue = prompt(i18n("propValue"));
  4226. if (!propValue) return;
  4227. if (propValue === "true") propValue = true;
  4228. else if (propValue === "false") propValue = false;
  4229. else if (/^\d+$/.test(propValue)) propValue = parseInt(propValue);
  4230. let editTemp = self.getTempRule();
  4231. if (!editTemp) return;
  4232. editTemp[propName] = propValue;
  4233. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  4234. }, true);
  4235. addNextSelector.addEventListener("click", e => {
  4236. let editTemp = self.getTempRule();
  4237. if (!editTemp) return;
  4238. let selector = self.selectorInput.value;
  4239. if (selector) {
  4240. editTemp.nextLink = selector;
  4241. }
  4242. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  4243. }, true);
  4244. addPageSelector.addEventListener("click", e => {
  4245. let editTemp = self.getTempRule();
  4246. if (!editTemp) return;
  4247. let selector = self.selectorInput.value;
  4248. if (selector) {
  4249. editTemp.pageElement = selector;
  4250. }
  4251. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  4252. }, true);
  4253. showDetailBtn.addEventListener("click", e => {
  4254. frame.classList.toggle("showDetail");
  4255. }, true);
  4256. saveDetailBtn.addEventListener("click", e => {
  4257. let editTemp = self.getTempRule(true);
  4258. if (tempRule.value && !editTemp) {
  4259. return;
  4260. }
  4261. if(!ruleParser.customRules) {
  4262. ruleParser.customRules = [];
  4263. }
  4264. for (let i in ruleParser.customRules) {
  4265. if (ruleParser.customRules[i].url == editTemp.url) {
  4266. ruleParser.customRules.splice(i, 1);
  4267. break;
  4268. }
  4269. }
  4270. if (tempRule.value) {
  4271. ruleParser.customRules.unshift(editTemp);
  4272. ruleParser.curSiteRule = editTemp;
  4273. } else {
  4274. ruleParser.curSiteRule = {};
  4275. isPause = true;
  4276. }
  4277. storage.setItem("customRules", ruleParser.customRules);
  4278. if (ruleParser.hpRules && ruleParser.curSiteRule && !ruleParser.curSiteRule.singleUrl) {
  4279. ruleParser.addToHpRules(true);
  4280. }
  4281. if (window.confirm(i18n("reloadPage"))) {
  4282. setTimeout(() => {location.reload()}, 100);
  4283. }
  4284. }, true);
  4285. nextSwitchBtn.addEventListener("click", e => {
  4286. self.close();
  4287. nextSwitch.start();
  4288. }, true);
  4289. loadNow.addEventListener("click", e => {
  4290. self.close();
  4291. let loadNum = window.prompt(i18n("loadConfirm"), "1");
  4292. if (loadNum === "" || loadNum === null) return;
  4293. autoLoadNum = Math.abs(parseInt(loadNum));
  4294. nextPage();
  4295. }, true);
  4296. closeBtn.addEventListener("click", e => {
  4297. self.close();
  4298. }, true);
  4299. this.showSign = true;
  4300. logoBtn.addEventListener("click", e => {
  4301. logoBtn.classList.toggle("showSign");
  4302. self.showSign = !self.showSign;
  4303. getBody(document).classList.toggle("pagetual-picker");
  4304. }, true);
  4305. let moving = false;
  4306. let initX = 0, initY = 0, initPos = {x: 0, y: 0};
  4307. let moveHanlder = e => {
  4308. if (moving) {
  4309. frame.style.left = e.clientX - initX + "px";
  4310. frame.style.top = e.clientY - initY + "px";
  4311. e.stopPropagation();
  4312. e.preventDefault();
  4313. } else if(Math.abs(e.clientX - initPos.x) + Math.abs(e.clientY - initPos.y) > 20) {
  4314. moving = true;
  4315. }
  4316. };
  4317. let upHanlder = e => {
  4318. if (moving) {
  4319. moving = false;
  4320. } else {
  4321. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  4322. }
  4323. document.removeEventListener("mousemove", moveHanlder, true);
  4324. title.removeEventListener("mouseup", upHanlder, true);
  4325. e.stopPropagation();
  4326. e.preventDefault();
  4327. };
  4328. title.addEventListener("mousedown", e => {
  4329. initPos = {x: e.clientX, y: e.clientY};
  4330. initX = e.clientX - parseInt(getComputedStyle(frame).left);
  4331. initY = e.clientY - parseInt(getComputedStyle(frame).top);
  4332. document.addEventListener("mousemove", moveHanlder, true);
  4333. title.addEventListener("mouseup", upHanlder, true);
  4334. });
  4335. frame.addEventListener("mouseenter", e => {
  4336. if (!self.showSign || moving) return;
  4337. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  4338. self.checkInputSelector();
  4339. });
  4340. frame.addEventListener("mouseleave", e => {
  4341. if (!self.showSign) {
  4342. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  4343. self.clearSigns();
  4344. return;
  4345. }
  4346. if (moving) return;
  4347. getBody(document).appendChild(self.mainSignDiv);
  4348. self.clearSigns();
  4349. });
  4350. checkBtn.addEventListener("click", e => {
  4351. self.checkInputSelector();
  4352. if (this.selectorInput.value) _GM_setClipboard(this.selectorInput.value);
  4353. showTips(i18n("copied"));
  4354. });
  4355. xpath.addEventListener("click", e => {
  4356. if (!selectorInput.value) {
  4357. self.setSelectorDiv("");
  4358. return;
  4359. }
  4360. let element = getElement(selectorInput.value, document);
  4361. let selector = self.getSelectorFromEle(element);
  4362. self.setSelectorDiv(selector);
  4363. selectorInput.value = selector;
  4364. });
  4365. editBtn.addEventListener("click", e => {
  4366. rulesData.editTemp = self.getTempRule();
  4367. storage.setItem("rulesData", rulesData);
  4368. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  4369. });
  4370. editBtn.oncontextmenu = e => {
  4371. e.preventDefault();
  4372. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  4373. };
  4374. this.frame = frame;
  4375. this.xpath = xpath;
  4376. this.allpath = allpath;
  4377. this.selectorInput = selectorInput;
  4378. this.nextSwitchBtn = nextSwitchBtn;
  4379. this.autoScrollBtn = autoScrollBtn;
  4380. this.loadNow = loadNow;
  4381. this.tempRule = tempRule;
  4382. this.logoBtn = logoBtn;
  4383. let setTitleTimer;
  4384. this.moveHandler = e => {
  4385. if (!self.showSign || e.target === document) return;
  4386. let target = self.getTarget(e.target);
  4387. self.adjustSignDiv(self.mainSignDiv, target);
  4388. clearTimeout(setTitleTimer);
  4389. setTitleTimer = setTimeout(() => {
  4390. if (self.inPicker && target.hasAttributes()) {
  4391. let title = target.nodeName.toLowerCase() + "\n";
  4392. for (const attr of target.attributes) {
  4393. title += `【${attr.name}】${attr.value ? " ➡️ " + attr.value : ""}\n`;
  4394. }
  4395. getBody(document).title = title;
  4396. }
  4397. }, 100);
  4398. };
  4399. this.clickHandler = e => {
  4400. if (!self.showSign) return;
  4401. if (self.inPicker) {
  4402. e.stopPropagation();
  4403. e.preventDefault();
  4404. }
  4405. let target = self.getTarget(e.target);
  4406. let selector = self.getSelectorFromEle(target);
  4407. selectorInput.value = selector;
  4408. self.setSelectorDiv(selector);
  4409. };
  4410. }
  4411.  
  4412. getTempRule(detail) {
  4413. if (this.tempRule.value) {
  4414. try {
  4415. this.editTemp = JSON.parse(this.tempRule.value);
  4416. } catch (e) {
  4417. this.editTemp = null;
  4418. if (detail) {
  4419. let pos = e && e.message && e.message.match(/position (\d+)/);
  4420. if (pos) {
  4421. pos = parseInt(pos[1]);
  4422. this.tempRule.value = this.tempRule.value.slice(0, pos) + "➡️" + this.tempRule.value[pos] + "⬅️" + this.tempRule.value.slice(pos + 1);
  4423. }
  4424. showTips(i18n("errorJson"));
  4425. return null;
  4426. }
  4427. }
  4428. }
  4429. if (!this.editTemp) {
  4430. if (ruleParser.curSiteRule.url && !ruleParser.curSiteRule.singleUrl) {
  4431. this.editTemp = ruleParser.curSiteRule;
  4432. } else {
  4433. this.editTemp = {
  4434. name: document.title,
  4435. url: "^" + (location.origin + location.pathname).replace(/[^\/]*$/, "").replace(/^https?/, "https?").replace(/\./g, "\\."),
  4436. example: location.href
  4437. };
  4438. }
  4439. delete this.editTemp.from;
  4440. delete this.editTemp.type;
  4441. delete this.editTemp.updatedAt;
  4442. }
  4443. if (this.selectorInput.value && !this.frame.classList.contains("showDetail")) {
  4444. this.editTemp.pageElement = this.selectorInput.value;
  4445. }
  4446. return this.editTemp;
  4447. }
  4448.  
  4449. getTarget(ele) {
  4450. while (ele.parentNode && (ele.offsetWidth === 0 || ele.offsetHeight === 0)) {
  4451. ele = ele.parentNode;
  4452. }
  4453. return ele;
  4454. }
  4455.  
  4456. close() {
  4457. this.clearSigns();
  4458. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  4459. if (this.mainSignDiv.parentNode) this.mainSignDiv.parentNode.removeChild(this.mainSignDiv);
  4460. getBody(document).classList.remove("pagetual-picker");
  4461. getBody(document).removeEventListener("mousemove", this.moveHandler, true);
  4462. getBody(document).removeEventListener("click", this.clickHandler, true);
  4463. getBody(document).title = "";
  4464. this.inPicker = false;
  4465. }
  4466.  
  4467. setImportant(ele, prop, value) {
  4468. ele.style.setProperty(prop, value, "important");
  4469. }
  4470.  
  4471. createSignDiv() {
  4472. let signDiv = document.createElement("div");
  4473. this.setImportant(signDiv, "position", "absolute");
  4474. this.setImportant(signDiv, "pointer-events", "none");
  4475. this.setImportant(signDiv, "z-index", "2147483646");
  4476. this.setImportant(signDiv, "background", "rgba(120, 170, 210, 0.6)");
  4477. this.setImportant(signDiv, "transition", "all 0.15s ease-out");
  4478. this.setImportant(signDiv, "box-shadow", "rgb(0 0 0) 0px 0px 3px 0px");
  4479. return signDiv;
  4480. }
  4481.  
  4482. adjustSignDiv(div, target) {
  4483. let rect = target.getBoundingClientRect();
  4484. this.setImportant(div, "width", rect.width + "px");
  4485. this.setImportant(div, "height", rect.height + "px");
  4486. this.setImportant(div, "left", rect.left + window.scrollX + "px");
  4487. this.setImportant(div, "top", rect.top + window.scrollY + "px");
  4488. }
  4489.  
  4490. getSelectorFromEle(ele) {
  4491. return this.xpath.checked ? createXPathFromElement(ele) : geneSelector(ele, true);
  4492. }
  4493.  
  4494. fillTempRuleTextarea() {
  4495. if (!this.frame.classList.contains("showDetail")) this.tempRule.value = JSON.stringify(this.getTempRule(), null, 4);
  4496. }
  4497.  
  4498. setSelectorDiv(selector) {
  4499. this.fillTempRuleTextarea();
  4500. let self = this;
  4501. this.allpath.innerHTML = createHTML("");
  4502. if (!selector) return;
  4503. if (this.xpath.checked) {
  4504. let span = document.createElement("span");
  4505. span.innerText = selector;
  4506. span.addEventListener("click", e => {
  4507. self.selectorInput.value = selector;
  4508. self.checkInputSelector();
  4509. }, true);
  4510. this.allpath.appendChild(span);
  4511. } else {
  4512. selector.split(">").forEach((item, index) => self.geneSelectorItem(item, index));
  4513. }
  4514. }
  4515.  
  4516. geneSelectorItem(item, index) {
  4517. let self = this;
  4518. item = item.trim();
  4519. if (!item) return;
  4520. if (index !== 0) {
  4521. let span = document.createElement("span");
  4522. span.innerText = " > ";
  4523. this.allpath.appendChild(span);
  4524. }
  4525. let span = document.createElement("span");
  4526. span.className = "path";
  4527. span.innerText = item;
  4528. span.addEventListener("click", e => {
  4529. let selector = "";
  4530. let target = e.target;
  4531. while (target) {
  4532. selector = target.innerText + selector;
  4533. target = target.previousElementSibling;
  4534. }
  4535. self.selectorInput.value = selector;
  4536. self.checkInputSelector();
  4537. }, true);
  4538. this.allpath.appendChild(span);
  4539. }
  4540.  
  4541. checkInputSelector() {
  4542. let self = this;
  4543. this.clearSigns();
  4544. if (!this.selectorInput.value) return;
  4545. let eles = getAllElements(this.selectorInput.value, document);
  4546. if (eles && eles.length > 0) {
  4547. eles.forEach(ele => {
  4548. let sign = self.createSignDiv();
  4549. getBody(document).appendChild(sign);
  4550. self.adjustSignDiv(sign, ele);
  4551. self.signList.push(sign);
  4552. });
  4553. this.fillTempRuleTextarea();
  4554. }
  4555. }
  4556.  
  4557. clearSigns() {
  4558. this.signList.forEach(sign => {
  4559. if (sign.parentNode) sign.parentNode.removeChild(sign);
  4560. });
  4561. this.signList = [];
  4562. }
  4563.  
  4564. start() {
  4565. this.init();
  4566. if (this.inPicker) return;
  4567. this.inPicker = true;
  4568. if (!this.styleEle || !this.styleEle.parentNode) {
  4569. this.styleEle = _GM_addStyle(this.cssText);
  4570. }
  4571. document.documentElement.appendChild(this.frame);
  4572. getBody(document).appendChild(this.mainSignDiv);
  4573. getBody(document).classList.add("pagetual-picker");
  4574.  
  4575. this.logoBtn.classList.remove("showSign");
  4576. this.showSign = true;
  4577.  
  4578. getBody(document).addEventListener("mousemove", this.moveHandler, true);
  4579. getBody(document).addEventListener("click", this.clickHandler, true);
  4580. this.xpath.checked = isXPath(ruleParser.curSiteRule.pageElement);
  4581. this.tempRule.value = "";
  4582. this.editTemp = null;
  4583. this.frame.classList.remove("showDetail");
  4584.  
  4585. this.loadNow.style.display = ruleParser.nextLinkHref ? "block" : "none";
  4586. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  4587. this.nextSwitchBtn.style.display = "block";
  4588. } else {
  4589. this.nextSwitchBtn.style.display = "none";
  4590. }
  4591. this.autoScrollBtn.innerText = i18n(autoScroll ? "disableAutoScroll" : "enableAutoScroll");
  4592.  
  4593. let pageElementSel = ruleParser.curSiteRule.pageElement || "";
  4594. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  4595. pageElementSel = pageElementSel[nextIndex < pageElementSel.length ? nextIndex : 0];
  4596. }
  4597. this.setSelectorDiv(pageElementSel);
  4598. }
  4599. }
  4600. const picker = new Picker();
  4601.  
  4602. var editor, editorChanged = false;
  4603. function createEdit() {
  4604. var options = {
  4605. mode: 'code',
  4606. modes: ['code', 'tree'],
  4607. templates: [
  4608. {
  4609. text: 'New site',
  4610. title: 'Insert a new site',
  4611. className: 'jsoneditor-type-object',
  4612. field: 'SiteTemplate',
  4613. value: {
  4614. 'name': 'Site name',
  4615. 'url': 'Site url'
  4616. }
  4617. }
  4618. ],
  4619. schema: {
  4620. "title": "Sites data",
  4621. "description": "Object containing site config",
  4622. "type": "array",
  4623. "items": {
  4624. "type": 'object',
  4625. "properties": {
  4626. "name": {
  4627. "title": "Site Name",
  4628. "description": "The site's name.",
  4629. "examples": [
  4630. "Google"
  4631. ],
  4632. "type": "string"
  4633. },
  4634. "url": {
  4635. "title": "Site Url",
  4636. "description": "The Regexp of site's url.",
  4637. "examples": [
  4638. "^https:\/\/yande\\.re\/"
  4639. ],
  4640. "type": "string"
  4641. }
  4642. },
  4643. "required": ["name", "url"]
  4644. }
  4645. },
  4646. onChange: () => {
  4647. editorChanged = true;
  4648. }
  4649. };
  4650. setTimeout(() => {
  4651. var container = document.getElementById("jsoneditor");
  4652. container.style.height = '800px';
  4653. container.innerHTML = "";
  4654. editor = new JSONEditor(container, options);
  4655. editor.set(ruleParser.customRules);
  4656. }, 500);
  4657. }
  4658.  
  4659. function checkGuidePage(href) {
  4660. if (guidePage.test(href)) {
  4661. if (typeof JSONEditor !== 'undefined') {
  4662. createEdit();
  4663. } else {
  4664. let checkEditorReady = setInterval(() => {
  4665. if (typeof JSONEditor !== 'undefined') {
  4666. createEdit();
  4667. clearInterval(checkEditorReady);
  4668. }
  4669. }, 100);
  4670. }
  4671. [].forEach.call(getBody(document).querySelectorAll('a'), ele => {
  4672. ele.target = "_blank";
  4673. });
  4674. return true;
  4675. }
  4676. return false;
  4677. }
  4678.  
  4679. function startAutoScroll() {
  4680. clearInterval(autoScrollInterval);
  4681. if (autoScroll <= 0) return;
  4682. autoScrollInterval = setInterval(() => {
  4683. if (isPause) return;
  4684. window.scroll(window.scrollX, window.scrollY + 1);
  4685. }, parseInt(1000 / autoScroll));
  4686. }
  4687.  
  4688. var inUpdate = false;
  4689. function initConfig(href) {
  4690. let isGuidePage = checkGuidePage(href);
  4691. if (!isGuidePage) {
  4692. if (href.indexOf("PagetualGuide") != -1) return true;
  4693. if (location.hostname === "pagetual.hoothin.com") return true;
  4694. }
  4695.  
  4696. var configCon, insertPos, click2import, importUrlPre;
  4697.  
  4698. let inConfig = isGuidePage;
  4699. if (!inConfig) {
  4700. for (let i = 0; i < configPage.length; i++) {
  4701. if (configPage[i] == location.href) {
  4702. inConfig = true;
  4703. break;
  4704. }
  4705. }
  4706. }
  4707. if (ruleImportUrlReg.test(href) || inConfig) {
  4708. let importing = false;
  4709. if (!inUpdate && rulesData.uninited) {
  4710. setTimeout(() => {
  4711. if (!inUpdate && !importing) showTips(i18n("firstAlert"));
  4712. }, 3000);
  4713. setTimeout(() => {
  4714. if (!inUpdate && !importing) showTips(i18n("firstAlert"));
  4715. }, 6000);
  4716. showTips(i18n("firstAlert"));
  4717. }
  4718. let defaultOption = document.querySelector('#discussion_rating_4');
  4719. if (defaultOption) defaultOption.checked = true;
  4720. let createImportBtn = (pre) => {
  4721. let importBtn = document.createElement("button");
  4722. importBtn.id = "pagetualImport";
  4723. importBtn.innerText = i18n("import");
  4724. importBtn.style.marginTop = "100px";
  4725. importBtn.style.float = "right";
  4726. importBtn.style.position = "relative";
  4727. importBtn.style.display = "block";
  4728. importBtn.style.fontSize = "20px";
  4729. importBtn.addEventListener("click", e => {
  4730. let parentNode = importBtn.parentNode;
  4731. if (!parentNode) return;
  4732. parentNode.removeChild(importBtn);
  4733. try {
  4734. let rules = parentNode.innerText.trim();
  4735. let isContent = /['"]name['"]/i.test(rules);
  4736. if (isContent) {
  4737. let ruleList = JSON.parse(`[${rules}]`);
  4738. for (let i in ruleList) {
  4739. let hasRule = false;
  4740. let r = ruleList[i];
  4741. for (let j in ruleParser.customRules) {
  4742. if (ruleParser.customRules[j].name == r.name) {
  4743. ruleParser.customRules[j] = r;
  4744. hasRule = true;
  4745. break;
  4746. }
  4747. }
  4748. if (!hasRule) ruleParser.customRules.push(r);
  4749. ruleParser.hpRules.unshift(r);
  4750. }
  4751. storage.setItem("customRules", ruleParser.customRules);
  4752. storage.setItem("hpRules", ruleParser.hpRules);
  4753. storage.setItem("smartRules", []);
  4754. showTips(i18n("importSucc"));
  4755. } else {
  4756. rules = rules.split("\n");
  4757. let diff = false;
  4758. for (let c = 0; c < rules.length; c++) {
  4759. let urlArr = rules[c].split("|"), url, type = 1;
  4760. if (urlArr.length == 1) {
  4761. url = urlArr[0].trim();
  4762. if (!/^http/.test(url)) {
  4763. showTips(i18n("errorWrongUrl"));
  4764. return;
  4765. }
  4766. } else if (urlArr.length == 2) {
  4767. type = urlArr[0].trim();
  4768. url = urlArr[1].trim();
  4769. if (!/^http/.test(url)) {
  4770. showTips(i18n("errorWrongUrl"));
  4771. return;
  4772. }
  4773. } else {
  4774. break;
  4775. }
  4776. let maxId = 1, hasUrl = false;
  4777. if (!rulesData.urls) {
  4778. rulesData.urls = [];
  4779. maxId = 1;
  4780. } else {
  4781. rulesData.urls.forEach(u => {
  4782. if (maxId < u.id) {
  4783. maxId = u.id;
  4784. }
  4785. if (u.url == url) {
  4786. hasUrl = true;
  4787. }
  4788. });
  4789. if (hasUrl) break;
  4790. }
  4791. diff = true;
  4792. if (!rulesData.sort) rulesData.sort = [1];
  4793. rulesData.urls.push({id: maxId + 1, url: url, type: type});
  4794. rulesData.sort.unshift(maxId + 1);
  4795. }
  4796. if (!diff) {
  4797. showTips(i18n("errorAlreadyExists"));
  4798. setTimeout(() => {
  4799. showTips(i18n("beginUpdate"), "", 30000);
  4800. updateRules(() => {
  4801. showTips(i18n("updateSucc"));
  4802. location.reload();
  4803. }, (rule, err) => {
  4804. showTips(`Failed to update ${rule.url} rules!`);
  4805. debug(err);
  4806. });
  4807. }, 500);
  4808. return;
  4809. }
  4810. storage.setItem("rulesData", rulesData);
  4811.  
  4812. if (rulesData.urls) ruleUrls = ruleUrls.concat(rulesData.urls);
  4813. if (rulesData.sort) {
  4814. let urls = [];
  4815. rulesData.sort.forEach(id => {
  4816. for (let s = 0; s < ruleUrls.length; s++) {
  4817. if (id == ruleUrls[s].id) {
  4818. urls.push(ruleUrls[s]);
  4819. break;
  4820. }
  4821. }
  4822. });
  4823. ruleUrls = urls;
  4824. }
  4825. showTips(i18n("beginUpdate"), "", 30000);
  4826. updateRules(() => {
  4827. showTips(i18n("updateSucc"));
  4828. location.reload();
  4829. }, (rule, err) => {
  4830. showTips(`Failed to update ${rule.url} rules!`);
  4831. debug(err);
  4832. });
  4833. importing = true;
  4834. }
  4835. } catch (e) {
  4836. _GM_notification(e.toString());
  4837. }
  4838. });
  4839. if (pre) {
  4840. let clientHeight = 35 - pre.clientHeight;
  4841. if (clientHeight > -20) clientHeight = -20;
  4842. importBtn.style.marginTop = `${clientHeight}px`;
  4843. pre.appendChild(importBtn);
  4844. }
  4845. return importBtn;
  4846. };
  4847. [].forEach.call(document.querySelectorAll('pre[name=pagetual],pre[name=user-content-pagetual]'), pre => {
  4848. let importBtn = createImportBtn(pre);
  4849. });
  4850. document.addEventListener("mouseover", e => {
  4851. if (/^PRE$/i.test(e.target.nodeName)) {
  4852. let nameAttr = e.target.getAttribute("name");
  4853. if (nameAttr == "pagetual" || nameAttr == "user-content-pagetual") {
  4854. if (e.target.querySelector('#pagetualImport')) return;
  4855. let importBtn = createImportBtn(e.target);
  4856. }
  4857. }
  4858. });
  4859.  
  4860. if (inConfig) {
  4861. if (!inUpdate && _GM_info.script && _GM_info.script.version && _GM_info.script.version !== '1.0.0') {
  4862. let versionEle = document.querySelector('.markdown-body>h1[id],article>h1');
  4863. let latestVer = versionEle && versionEle.innerText.match(/\d[\d\.]+/)[0];
  4864. if (latestVer && latestVer != _GM_info.script.version) {
  4865. showTips(i18n('outOfDate'), "", 3000);
  4866. }
  4867. }
  4868. _GM_addStyle(`
  4869. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  4870. cursor: pointer;
  4871. user-select: none;
  4872. display: inline-block;
  4873. margin-right: 5px;
  4874. -moz-transition:color 0.3s ease, transform 0.3s;
  4875. -webkit-transition:color 0.3s ease, transform 0.3s;
  4876. transition:color 0.3s ease, transform 0.3s;
  4877. }
  4878. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  4879. color:red;
  4880. transform: scale(1.5);
  4881. -webkit-transform: scale(1.5);
  4882. }
  4883. .updateDate{
  4884. cursor: pointer;
  4885. user-select: none;
  4886. -moz-transition:color 0.3s ease, transform 0.3s;
  4887. -webkit-transition:color 0.3s ease, transform 0.3s;
  4888. transition:color 0.3s ease, transform 0.3s;
  4889. transform-origin: left;
  4890. -webkit-transform-origin: left;
  4891. }
  4892. .updateDate:hover{
  4893. color:red;
  4894. transform: scale(1.1);
  4895. -webkit-transform: scale(1.1);
  4896. }
  4897. input[type=number]::-webkit-inner-spin-button,
  4898. input[type=number]::-webkit-outer-spin-button {
  4899. -webkit-appearance: none;
  4900. margin: 0;
  4901. }
  4902. input[type=number] {
  4903. -moz-appearance:textfield;
  4904. }
  4905. table td>h3 {
  4906. margin: 16px!important;
  4907. }
  4908. #saveBtn {
  4909. width: 100%;
  4910. position: fixed;
  4911. z-index: 999;
  4912. bottom: 0px;
  4913. left: 0px;
  4914. font-size: x-large;
  4915. opacity: 0.8;
  4916. cursor: pointer;
  4917. -moz-transition:opacity 0.3s ease;
  4918. -webkit-transition:opacity 0.3s ease;
  4919. transition:opacity 0.3s ease;
  4920. }
  4921. #saveBtn:hover {
  4922. opacity: 1;
  4923. }
  4924. `);
  4925. click2import = document.querySelector("[name='user-content-click2import'],[name='click2import']");
  4926. if (click2import) click2import.innerText = i18n("click2ImportRule")
  4927. configCon = document.querySelector(".markdown-body,.theme-default-content");
  4928. if (!configCon) {
  4929. setTimeout(() => {
  4930. location.reload();
  4931. }, 1000);
  4932. return true;
  4933. }
  4934. insertPos = configCon.querySelector("hr,#jsoneditor");
  4935.  
  4936. importUrlPre = document.querySelector("pre[name='user-content-pagetual'],pre[name='pagetual']");
  4937. if (!rulesData.uninited) {
  4938. if (importUrlPre) importUrlPre.style.display = "none";
  4939. if (click2import) click2import.style.display = "none";
  4940. }
  4941. let otherconfig = document.querySelector("a[name='user-content-otherconfig'],a[name='otherconfig']");
  4942. if (otherconfig) otherconfig.parentNode.removeChild(otherconfig);
  4943. let rulesExample = document.querySelector("#user-content-rules-example+a,#rules-example>a");
  4944. if (rulesExample) {
  4945. rulesExample.innerText = i18n("rulesExample");
  4946. if (lang == "zh-CN") {
  4947. rulesExample.href = rulesExample.href.replace("en", "cn");
  4948. } else if (lang == "zh-TW" || lang == "zh-HK") {
  4949. rulesExample.href = rulesExample.href.replace("/en", "");
  4950. }
  4951. }
  4952. } else return false;
  4953. } else return false;
  4954. class Rulebar {
  4955. init(ruleUrl) {
  4956. let id = ruleUrl.id;
  4957. this.ruleUrl = ruleUrl;
  4958. this.item = document.createElement("p");
  4959. this.item.dataset.id = id;
  4960. let url = document.createElement("a");
  4961. url.href = ruleUrl.url;
  4962. url.innerHTML = ruleUrl.url;
  4963. url.title = ruleUrl.url;
  4964. let up = document.createElement("span");
  4965. up.innerHTML = "↑ ";
  4966. up.title = i18n("sortTitle");
  4967. let down = document.createElement("span");
  4968. down.innerHTML = "↓ ";
  4969. down.title = i18n("sortTitle");
  4970. let del = document.createElement("span");
  4971. del.innerHTML = "× ";
  4972. up.onclick = e => {
  4973. this.moveUp();
  4974. };
  4975. down.onclick = e => {
  4976. this.moveDown();
  4977. };
  4978. del.onclick = e => {
  4979. this.del();
  4980. };
  4981. this.item.appendChild(up);
  4982. this.item.appendChild(down);
  4983. this.item.appendChild(del);
  4984. this.item.appendChild(url);
  4985. if (ruleParser.rules) {
  4986. url.style.maxWidth = "calc(100% - 140px)";
  4987. url.style.overflow = "hidden";
  4988. url.style.display = "inline-block";
  4989. url.style.textOverflow = "ellipsis";
  4990. url.style.verticalAlign = "bottom";
  4991. url.style.whiteSpace = "nowrap";
  4992. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == id ? 1 : 0), 0);
  4993. let idSpan = document.createElement("span");
  4994. idSpan.style.float = "right";
  4995. idSpan.innerHTML = `[rules: ${rulesLength}]`;
  4996. this.item.appendChild(idSpan);
  4997. this.idSpan = idSpan;
  4998. }
  4999. configCon.insertBefore(this.item, insertPos);
  5000. }
  5001. updateNum() {
  5002. if (ruleParser.rules) {
  5003. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == this.item.dataset.id ? 1 : 0), 0);
  5004. this.idSpan.innerHTML = `[rules: ${rulesLength}]`;
  5005. }
  5006. }
  5007. saveSort() {
  5008. let sort = [];
  5009. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i => {
  5010. sort.push(i.dataset.id);
  5011. });
  5012. rulesData.sort = sort;
  5013. let urls = [];
  5014. sort.forEach(id => {
  5015. for (let s = 0; s < ruleUrls.length; s++) {
  5016. if (id == ruleUrls[s].id) {
  5017. urls.push(ruleUrls[s]);
  5018. break;
  5019. }
  5020. }
  5021. });
  5022. ruleUrls = urls;
  5023. storage.setItem("rulesData", rulesData);
  5024. }
  5025. moveUp() {
  5026. let preE = this.item.previousElementSibling;
  5027. if (/^P$/i.test(preE.nodeName) && preE.children.length > 1) {
  5028. this.item.parentNode.insertBefore(this.item, preE);
  5029. this.saveSort();
  5030. }
  5031. }
  5032. moveDown() {
  5033. let nextE = this.item.nextElementSibling;
  5034. if (/^P$/i.test(nextE.nodeName) && nextE.children.length > 1) {
  5035. this.item.parentNode.insertBefore(nextE, this.item);
  5036. this.saveSort();
  5037. }
  5038. }
  5039. del() {
  5040. if (this.ruleUrl.id < 2) {
  5041. showTips(i18n("cantDel"));
  5042. } else if (window.confirm(i18n("confirmDel"))) {
  5043. for (let u = 0; u < rulesData.urls.length; u++) {
  5044. if (this.ruleUrl.id == rulesData.urls[u].id) {
  5045. rulesData.urls.splice(u, 1);
  5046. break;
  5047. }
  5048. }
  5049. for (let u = 0; u < ruleUrls.length; u++) {
  5050. if (this.ruleUrl.id == ruleUrls[u].id) {
  5051. ruleUrls.splice(u, 1);
  5052. break;
  5053. }
  5054. }
  5055. for (let u = 0; u < rulesData.sort.length; u++) {
  5056. if (this.ruleUrl.id == rulesData.sort[u]) {
  5057. rulesData.sort.splice(u, 1);
  5058. break;
  5059. }
  5060. }
  5061. storage.setItem("rulesData", rulesData);
  5062. ruleParser.rules = ruleParser.rules.filter(item => {return item.from != this.ruleUrl.id});
  5063. storage.setItem("rules", ruleParser.rules);
  5064. this.item.parentNode.removeChild(this.item);
  5065. //location.reload();
  5066. }
  5067. }
  5068. }
  5069. let langSelect = document.createElement("select");
  5070. langSelect.style.float = "right";
  5071. langSelect.style.position = "relative";
  5072. langSelect.style.zIndex = "1";
  5073. let option = document.createElement("option");
  5074. option.value = "";
  5075. option.innerText = "Language";
  5076. langSelect.appendChild(option);
  5077. for (let key in langList) {
  5078. let option = document.createElement("option");
  5079. option.value = key;
  5080. option.innerText = langList[key];
  5081. langSelect.appendChild(option);
  5082. }
  5083. langSelect.value = rulesData.lang || "";
  5084. configCon.insertBefore(langSelect, insertPos);
  5085.  
  5086. let updateP = document.createElement("p"), i = 0;
  5087. let now = new Date().getTime();
  5088.  
  5089.  
  5090. let pastDate = (new Date(updateDate)).toString(), passStr;
  5091. let passTime = (now - updateDate) / 1000;
  5092. if (isNaN(passTime)) {
  5093. passStr = i18n("firstUpdate");
  5094. } else {
  5095. if (passTime < 60) {
  5096. passStr = i18n("passSec", parseInt(passTime));
  5097. } else if (passTime < 60 * 60) {
  5098. passStr = i18n("passMin", parseInt(passTime / 60));
  5099. } else if (passTime < 60 * 60 * 24) {
  5100. passStr = i18n("passHour", parseInt(passTime / 3600));
  5101. } else {
  5102. passStr = i18n("passDay", parseInt(passTime / 86400));
  5103. }
  5104. passStr += " 🖱 " + i18n("click2update");
  5105. }
  5106.  
  5107. let rulebarList = [], updateFail = false;
  5108. updateP.className = "updateDate";
  5109. updateP.innerHTML = passStr;
  5110. updateP.title = i18n("update") + " - " + pastDate;
  5111. configCon.insertBefore(updateP, insertPos);
  5112. if (ruleUrls) {
  5113. ruleUrls.forEach(ruleUrl => {
  5114. let rulebar = new Rulebar();
  5115. rulebar.init(ruleUrl);
  5116. rulebarList.push(rulebar);
  5117. });
  5118. }
  5119. let customUrlsTitle = document.createElement("h2");
  5120. customUrlsTitle.innerHTML = i18n("customUrls");
  5121. configCon.insertBefore(customUrlsTitle, insertPos);
  5122. let customUrlsInput = document.createElement("textarea");
  5123. customUrlsInput.style.width = "100%";
  5124. customUrlsInput.placeholder = "http://wedata.net/databases/AutoPagerize/items_all.json \nhttps://hoothin.github.io/UserScripts/Pagetual/pagetualRules.json";
  5125. customUrlsInput.spellcheck = false;
  5126. configCon.insertBefore(customUrlsInput, insertPos);
  5127.  
  5128. let btns = document.createElement("div");
  5129. btns.style.display = "flex";
  5130. configCon.insertBefore(btns, insertPos);
  5131. let upBtnImg = document.createElement("div");
  5132. upBtnImg.style.width = "33%";
  5133. let upBtnImgTitle = document.createElement("h2");
  5134. upBtnImgTitle.style.whiteSpace = "nowrap";
  5135. upBtnImgTitle.style.overflow = "auto";
  5136. upBtnImgTitle.innerHTML = i18n("upBtnImg");
  5137. upBtnImg.appendChild(upBtnImgTitle);
  5138. let upBtnImgInput = document.createElement("input");
  5139. upBtnImgInput.style.width = "100%";
  5140. upBtnImgInput.placeholder = "data:image/png;base64,UpBtn";
  5141. upBtnImgInput.value = rulesData.upBtnImg || '';
  5142. upBtnImgInput.spellcheck = false;
  5143. upBtnImg.appendChild(upBtnImgInput);
  5144. btns.appendChild(upBtnImg);
  5145.  
  5146. let downBtnImg = document.createElement("div");
  5147. downBtnImg.style.width = "33%";
  5148. let downBtnImgTitle = document.createElement("h2");
  5149. downBtnImgTitle.style.whiteSpace = "nowrap";
  5150. downBtnImgTitle.style.overflow = "auto";
  5151. downBtnImgTitle.innerHTML = i18n("downBtnImg");
  5152. downBtnImg.appendChild(downBtnImgTitle);
  5153. let downBtnImgInput = document.createElement("input");
  5154. downBtnImgInput.style.width = "100%";
  5155. downBtnImgInput.placeholder = "data:image/png;base64,DownBtn";
  5156. downBtnImgInput.value = rulesData.downBtnImg || '';
  5157. downBtnImgInput.spellcheck = false;
  5158. downBtnImg.appendChild(downBtnImgInput);
  5159. btns.appendChild(downBtnImg);
  5160.  
  5161. let sideControllerIconDiv = document.createElement("div");
  5162. sideControllerIconDiv.style.width = "33%";
  5163. let sideControllerIconTitle = document.createElement("h2");
  5164. sideControllerIconTitle.style.whiteSpace = "nowrap";
  5165. sideControllerIconTitle.style.overflow = "auto";
  5166. sideControllerIconTitle.innerHTML = i18n("sideControllerIcon");
  5167. sideControllerIconDiv.appendChild(sideControllerIconTitle);
  5168. let sideControllerIconInput = document.createElement("input");
  5169. sideControllerIconInput.style.width = "100%";
  5170. sideControllerIconInput.placeholder = "🤍";
  5171. sideControllerIconInput.value = rulesData.sideControllerIcon || '';
  5172. sideControllerIconInput.spellcheck = false;
  5173. sideControllerIconDiv.appendChild(sideControllerIconInput);
  5174. btns.appendChild(sideControllerIconDiv);
  5175.  
  5176. let otherBtns = document.createElement("div");
  5177. otherBtns.style.display = "flex";
  5178. configCon.insertBefore(otherBtns, insertPos);
  5179. let loadingText = document.createElement("div");
  5180. loadingText.style.width = "100%";
  5181. let loadingTextTitle = document.createElement("h2");
  5182. loadingTextTitle.style.whiteSpace = "nowrap";
  5183. loadingTextTitle.style.overflow = "auto";
  5184. loadingTextTitle.innerHTML = i18n("loadingTextTitle");
  5185. loadingText.appendChild(loadingTextTitle);
  5186. let loadingTextInput = document.createElement("input");
  5187. loadingTextInput.value = rulesData.loadingText || '';
  5188. loadingTextInput.placeholder = i18n("loadingText");
  5189. loadingTextInput.style.width = "100%";
  5190. loadingTextInput.style.margin = "0";
  5191. loadingTextInput.spellcheck = false;
  5192. loadingText.appendChild(loadingTextInput);
  5193. otherBtns.appendChild(loadingText);
  5194.  
  5195. let opacity = document.createElement("div");
  5196. let opacityTitle = document.createElement("h2");
  5197. opacityTitle.style.whiteSpace = "nowrap";
  5198. opacityTitle.style.overflow = "visible";
  5199. opacityTitle.innerHTML = i18n("opacity");
  5200. opacity.appendChild(opacityTitle);
  5201. let opacityInput = document.createElement("input");
  5202. opacityInput.value = rulesData.opacity * 100;
  5203. opacityInput.type = "number";
  5204. opacityInput.min = 0;
  5205. opacityInput.max = 100;
  5206. opacityInput.style.width = "110px";
  5207. opacityInput.style.margin = "0";
  5208. opacityInput.placeholder = i18n("opacityPlaceholder");
  5209. opacityInput.spellcheck = false;
  5210. opacityInput.oninput = e => {
  5211. if (opacityInput.value > 100) opacityInput.value = 100;
  5212. else if (opacityInput.value < 0) opacityInput.value = 0;
  5213. };
  5214. opacity.appendChild(opacityInput);
  5215. otherBtns.appendChild(opacity);
  5216.  
  5217. let pageElementCss = document.createElement("div");
  5218. pageElementCss.style.marginBottom = "30px";
  5219. let pageElementCssTitle = document.createElement("h2");
  5220. pageElementCssTitle.innerHTML = i18n("pageElementCss");
  5221. pageElementCss.appendChild(pageElementCssTitle);
  5222. let pageElementCssInput = document.createElement("input");
  5223. pageElementCssInput.value = rulesData.pageElementCss || '';
  5224. pageElementCssInput.style.width = "100%";
  5225. pageElementCssInput.style.margin = "0";
  5226. pageElementCssInput.placeholder = "font-size: xx-large;";
  5227. pageElementCssInput.spellcheck = false;
  5228. pageElementCss.appendChild(pageElementCssInput);
  5229. configCon.insertBefore(pageElementCss, insertPos);
  5230.  
  5231. let customCss = document.createElement("div");
  5232. customCss.style.marginBottom = "50px";
  5233. let customCssTitle = document.createElement("h2");
  5234. customCssTitle.innerHTML = i18n("customCss");
  5235. customCss.appendChild(customCssTitle);
  5236. let customCssInput = document.createElement("textarea");
  5237. customCssInput.value = rulesData.customCss || '';
  5238. customCssInput.style.width = "100%";
  5239. customCssInput.style.margin = "0";
  5240. customCssInput.placeholder = ".pagetual {\n}";
  5241. customCssInput.spellcheck = false;
  5242. customCss.appendChild(customCssInput);
  5243. configCon.insertBefore(customCss, insertPos);
  5244.  
  5245. let configTable = document.createElement("table");
  5246. configTable.style.width = "100%";
  5247. let configTbody = document.createElement("tbody");
  5248. configTbody.style.width = "99%";
  5249. configTbody.style.display = "inline-table";
  5250. configTable.appendChild(configTbody);
  5251. configCon.insertBefore(configTable, insertPos);
  5252. function createCheckbox(innerText, val, tag, parentCheck, otherType) {
  5253. if (typeof val == 'undefined') val = "";
  5254. let title = document.createElement(tag || "h3");
  5255. title.innerHTML = innerText;
  5256. title.style.overflowWrap = "normal";
  5257. let input = document.createElement("input");
  5258. if (otherType === 'key') {
  5259. input.type = 'text';
  5260. input.setAttribute('readOnly', 'readonly');
  5261. input.addEventListener("keydown", e => {
  5262. if (e.key === 'Escape' || e.key === 'Backspace') input.value = '';
  5263. else input.value = e.key;
  5264. e.stopPropagation();
  5265. e.preventDefault();
  5266. });
  5267. } else {
  5268. input.type = otherType || "checkbox";
  5269. }
  5270. input.style.width = "30px";
  5271. input.style.height = "20px";
  5272. input.style.float = "left";
  5273. input.style.margin = "5px";
  5274. input.value = val;
  5275. input.checked = val;
  5276. let td = document.createElement("td");
  5277. td.appendChild(input);
  5278. if (parentCheck) {
  5279. title.style.margin = "0";
  5280. td.appendChild(title);
  5281. let parent = parentCheck.parentNode.nextElementSibling;
  5282. let tr = parent.querySelector("tr");
  5283. if (!tr) {
  5284. tr = document.createElement("tr");
  5285. parent.appendChild(tr);
  5286. }
  5287. tr.appendChild(td);
  5288. if (!parentCheck.checked) {
  5289. td.style.display = "none";
  5290. }
  5291. parentCheck.addEventListener("click", e => {
  5292. td.style.display = parentCheck.checked ? "" : "none";
  5293. });
  5294. } else {
  5295. let tr = document.createElement("tr");
  5296. tr.appendChild(td);
  5297. td = document.createElement("td");
  5298. td.appendChild(title);
  5299. tr.appendChild(td);
  5300. configTable.children[0].appendChild(tr);
  5301. }
  5302. let xNodePos = innerText.indexOf('【X】');
  5303. if (xNodePos !== -1) {
  5304. input.style.float = "";
  5305. let xNode = title.firstChild.splitText(xNodePos);
  5306. xNode.splitText(3);
  5307. xNode.parentNode.replaceChild(input, xNode);
  5308. }
  5309. return input;
  5310. }
  5311.  
  5312. let setConfigPageInput = createCheckbox(i18n("setConfigPage"), false);
  5313. let enableWhiteListInput = createCheckbox(i18n("autoRun"), rulesData.enableWhiteList != true);
  5314. let sideControllerInput = createCheckbox(i18n("sideController"), rulesData.sideController);
  5315. let enableDebugInput = createCheckbox(i18n("enableDebug"), rulesData.enableDebug != false);
  5316. let enableHistoryInput = createCheckbox(i18n("enableHistory"), rulesData.enableHistory === true);
  5317. let enableHistoryAfterInsertInput = createCheckbox(i18n("enableHistoryAfterInsert"), rulesData.enableHistoryAfterInsert === true, "h4", enableHistoryInput);
  5318. let openInNewTabInput = createCheckbox(i18n("openInNewTab"), rulesData.openInNewTab != false);
  5319. let hidePageBarInput = createCheckbox(i18n("hideBarTips"), rulesData.opacity == 0);
  5320. let hidePageBarArrowInput = createCheckbox(i18n("hideBarArrow"), rulesData.hideBarArrow);
  5321. let hideLoadingIconInput = createCheckbox(i18n("hideLoadingIcon"), rulesData.hideLoadingIcon != false);
  5322. let initRunInput = createCheckbox(i18n("initRun"), rulesData.initRun != false);
  5323. let autoLoadNumInput = createCheckbox(i18n("autoLoadNum"), rulesData.autoLoadNum, "h4", initRunInput, "number");
  5324. let preloadInput = createCheckbox(i18n("preload"), rulesData.preload != false);
  5325. let rateInput = createCheckbox(i18n("turnRate"), rulesData.rate, "h4", preloadInput, "number");
  5326. let dbClick2StopInput = createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  5327. let manualModeInput = createCheckbox(i18n("manualMode"), rulesData.manualMode);
  5328. let clickModeInput = createCheckbox(i18n("clickMode"), rulesData.clickMode);
  5329. let pageBarMenuInput = createCheckbox(i18n("pageBarMenu"), rulesData.pageBarMenu != false);
  5330. let arrowToScrollInput = createCheckbox(i18n("arrowToScroll"), rulesData.arrowToScroll);
  5331. let contentVisibilityInput = createCheckbox(i18n("contentVisibility"), rulesData.contentVisibility);
  5332. let wedata2githubInput = createCheckbox(i18n("wedata2github"), rulesData.wedata2github);
  5333. let customFirstInput = createCheckbox(i18n("customFirst"), rulesData.customFirst);
  5334. let lastPageTipsInput = createCheckbox(i18n("lastPageTips"), rulesData.lastPageTips);
  5335.  
  5336. let hideBarInput = createCheckbox(i18n("hideBar"), rulesData.hideBar && !rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  5337. hideBarInput.name = 'hideBar';
  5338. let hideBarButNoStopInput = createCheckbox(i18n("hideBarButNoStop"), rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  5339. hideBarButNoStopInput.name = 'hideBar';
  5340. hideBarInput.addEventListener('mouseup', e => {
  5341. if (hideBarInput.checked) {
  5342. setTimeout(() => {hideBarInput.checked = false}, 0);
  5343. }
  5344. });
  5345. hideBarButNoStopInput.addEventListener('mouseup', e => {
  5346. if (hideBarButNoStopInput.checked) {
  5347. setTimeout(() => {hideBarButNoStopInput.checked = false}, 0);
  5348. }
  5349. });
  5350. hidePageBarInput.addEventListener('click', e => {
  5351. opacityInput.value = hidePageBarInput.checked ? 0 : 100;
  5352. });
  5353.  
  5354. let dbClick2StopCtrlInput = createCheckbox(i18n("dbClick2StopCtrl"), rulesData.dbClick2StopCtrl, "h4", dbClick2StopInput);
  5355. let dbClick2StopAltInput = createCheckbox(i18n("dbClick2StopAlt"), rulesData.dbClick2StopAlt, "h4", dbClick2StopInput);
  5356. let dbClick2StopShiftInput = createCheckbox(i18n("dbClick2StopShift"), rulesData.dbClick2StopShift, "h4", dbClick2StopInput);
  5357. let dbClick2StopMetaInput = createCheckbox(i18n("dbClick2StopMeta"), rulesData.dbClick2StopMeta, "h4", dbClick2StopInput);
  5358. let dbClick2StopKeyInput = createCheckbox(i18n("dbClick2StopKey"), rulesData.dbClick2StopKey, "h4", dbClick2StopInput, "key");
  5359.  
  5360. let otherConfigPage = rulesData.configPage ? rulesData.configPage != location.href : configPage[0] != location.href;
  5361. if (!otherConfigPage) {
  5362. setConfigPageInput.parentNode.parentNode.style.display = "none";
  5363. }
  5364.  
  5365. updateP.onclick = e => {
  5366. updateFail = false;
  5367. ruleParser.rules = [];
  5368. showTips(i18n("beginUpdate"), "", 30000);
  5369. updateRules(() => {
  5370. if (!updateFail) {
  5371. showTips(i18n("updateSucc"));
  5372. if (importUrlPre) importUrlPre.style.display = "none";
  5373. if (click2import) click2import.style.display = "none";
  5374. }
  5375. updateP.innerHTML = i18n("passSec", 0);
  5376. updateP.title = i18n("update");
  5377. rulebarList.forEach(rulebar => {
  5378. rulebar.updateNum();
  5379. });
  5380. }, (rule, err) => {
  5381. if (rule.id == 1) {
  5382. showTips(`Failed to update wedata rules! Try to switch to wedata mirror!`);
  5383. wedata2githubInput.scrollIntoView();
  5384. } else {
  5385. showTips(`Failed to update ${rule.url} rules!`);
  5386. }
  5387. debug(err);
  5388. updateFail = true;
  5389. });
  5390. };
  5391. let customRulesTitle = document.createElement("h2");
  5392. 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');
  5393. configCon.insertBefore(customRulesTitle, insertPos);
  5394. let customRulesInput = document.createElement("textarea");
  5395. customRulesInput.spellcheck = false;
  5396. configCon.insertBefore(customRulesInput, insertPos);
  5397. if (rulesData.editTemp) {
  5398. if (!ruleParser.customRules) {
  5399. ruleParser.customRules = [];
  5400. }
  5401. for (let i in ruleParser.customRules) {
  5402. if (ruleParser.customRules[i].url == rulesData.editTemp.url) {
  5403. ruleParser.customRules.splice(i, 1);
  5404. break;
  5405. }
  5406. }
  5407. ruleParser.customRules.unshift(rulesData.editTemp);
  5408. rulesData.editTemp = null;
  5409. storage.setItem("rulesData", rulesData);
  5410. customRulesInput.previousElementSibling.scrollIntoView();
  5411. }
  5412. customRulesInput.style.width = "100%";
  5413. customRulesInput.style.height = "800px";
  5414. 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]`;
  5415. let preCustom = getFormatJSON(ruleParser.customRules);
  5416. customRulesInput.value = preCustom;
  5417. if (isGuidePage) customRulesInput.style.display = "none";
  5418. let blacklistInput = document.createElement("textarea");
  5419. blacklistInput.style.width = "100%";
  5420. blacklistInput.style.height = "500px";
  5421. blacklistInput.style.display = "none";
  5422. blacklistInput.spellcheck = false;
  5423. 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";
  5424. blacklistInput.value = rulesData.blacklist ? rulesData.blacklist.join("\n") : "";
  5425. let blacklistBtn = document.createElement("button");
  5426. blacklistBtn.innerText = i18n("editBlacklist");
  5427. blacklistBtn.style.width = "100%";
  5428. blacklistBtn.onclick = e => {
  5429. blacklistInput.style.display = blacklistInput.style.display == "none" ? "" : "none";
  5430. };
  5431. configCon.insertBefore(blacklistBtn, insertPos);
  5432. configCon.insertBefore(blacklistInput, insertPos);
  5433. let saveBtn = document.createElement("button");
  5434. saveBtn.innerHTML = i18n("save");
  5435. saveBtn.id = "saveBtn";
  5436. configCon.insertBefore(saveBtn, insertPos);
  5437. saveBtn.onclick = e => {
  5438. try {
  5439. let customRules;
  5440. if (editor) {
  5441. if (editorChanged) {
  5442. editorChanged = false;
  5443. storage.setItem("hpRules", []);
  5444. storage.setItem("smartRules", []);
  5445. }
  5446. customRules = editor.get();
  5447. if (!customRules) {
  5448. customRules = "";
  5449. } else {
  5450. if (Array && Array.isArray && !Array.isArray(customRules)) {
  5451. showTips(i18n("errorRulesMustBeArray"));
  5452. return;
  5453. }
  5454. }
  5455. } else {
  5456. if (customRulesInput.value != preCustom) {
  5457. storage.setItem("hpRules", []);
  5458. storage.setItem("smartRules", []);
  5459. }
  5460. if (customRulesInput.value == "") {
  5461. customRules = "";
  5462. } else {
  5463. customRules = JSON.parse(customRulesInput.value);
  5464. if (Array && Array.isArray && !Array.isArray(customRules)) {
  5465. showTips(i18n("errorRulesMustBeArray"));
  5466. return;
  5467. }
  5468. customRulesInput.value = JSON.stringify(customRules, null, 4);
  5469. }
  5470. }
  5471. debug(customRules);
  5472. storage.setItem("customRules", customRules);
  5473. } catch(e) {
  5474. debug(e);
  5475. let pos = e && e.message && e.message.match(/position (\d+)/);
  5476. if (pos && !editor) {
  5477. pos = parseInt(pos[1]);
  5478. customRulesInput.value = customRulesInput.value.slice(0, pos) + "➡️" + customRulesInput.value[pos] + "⬅️" + customRulesInput.value.slice(pos + 1);
  5479. }
  5480. showTips(i18n("errorJson"));
  5481. return;
  5482. }
  5483. rulesData.lang = langSelect.value || "";
  5484. if (setConfigPageInput.checked) rulesData.configPage = location.href;
  5485. rulesData.wedata2github = wedata2githubInput.checked;
  5486. let opacity = parseInt(opacityInput.value) || 0;
  5487. if (opacity > 100) opacity = 100;
  5488. else if (opacity < 0) opacity = 0;
  5489. rulesData.opacity = opacity / 100;
  5490. rulesData.blacklist = blacklistInput.value ? blacklistInput.value.trim().split("\n") : "";
  5491. rulesData.hideBar = hideBarInput.checked;
  5492. rulesData.hideBarButNoStop = hideBarButNoStopInput.checked;
  5493. rulesData.dbClick2Stop = dbClick2StopInput.checked;
  5494. rulesData.enableWhiteList = !enableWhiteListInput.checked;
  5495. rulesData.enableDebug = enableDebugInput.checked;
  5496. rulesData.enableHistory = enableHistoryInput.checked;
  5497. rulesData.enableHistoryAfterInsert = enableHistoryAfterInsertInput.checked;
  5498. rulesData.openInNewTab = openInNewTabInput.checked;
  5499. rulesData.hideLoadingIcon = hideLoadingIconInput.checked;
  5500. rulesData.hideBarArrow = hidePageBarArrowInput.checked;
  5501. rulesData.customFirst = customFirstInput.checked;
  5502. rulesData.lastPageTips = lastPageTipsInput.checked;
  5503. rulesData.initRun = initRunInput.checked;
  5504. rulesData.autoLoadNum = autoLoadNumInput.value !== "0" ? autoLoadNumInput.value : '';
  5505. rulesData.rate = parseInt(rateInput.value) || 1;
  5506. rulesData.preload = preloadInput.checked;
  5507. rulesData.manualMode = manualModeInput.checked;
  5508. rulesData.clickMode = clickModeInput.checked;
  5509. rulesData.pageBarMenu = pageBarMenuInput.checked;
  5510. rulesData.arrowToScroll = arrowToScrollInput.checked;
  5511. rulesData.contentVisibility = contentVisibilityInput.checked;
  5512. if (rulesData.sideController != sideControllerInput.checked) {
  5513. rulesData.sideControllerPos = false;
  5514. }
  5515. rulesData.sideController = sideControllerInput.checked;
  5516. rulesData.pageElementCss = pageElementCssInput.value;
  5517. rulesData.customCss = customCssInput.value;
  5518. rulesData.upBtnImg = upBtnImgInput.value;
  5519. rulesData.downBtnImg = downBtnImgInput.value;
  5520. rulesData.sideControllerIcon = sideControllerIconInput.value;
  5521. rulesData.loadingText = loadingTextInput.value;
  5522. rulesData.dbClick2StopCtrl = dbClick2StopCtrlInput.checked;
  5523. rulesData.dbClick2StopAlt = dbClick2StopAltInput.checked;
  5524. rulesData.dbClick2StopShift = dbClick2StopShiftInput.checked;
  5525. rulesData.dbClick2StopMeta = dbClick2StopMetaInput.checked;
  5526. rulesData.dbClick2StopKey = dbClick2StopKeyInput.value;
  5527. storage.setItem("rulesData", rulesData);
  5528. let customUrls = customUrlsInput.value.trim();
  5529. if (customUrls) {
  5530. customUrls = customUrls.split(/\n/);
  5531. for (let c = 0; c < customUrls.length; c++) {
  5532. let url;
  5533. if (/^0\s*\|/.test(customUrls[c])) {
  5534. url = customUrls[c].replace(/^0\s*\|\s*/, "").trim();
  5535. if (!/^http/.test(url)) {
  5536. showTips(i18n("errorWrongUrl"));
  5537. return;
  5538. }
  5539. } else {
  5540. url = customUrls[c].trim();
  5541. if (!/^http/.test(url)) {
  5542. showTips(i18n("errorWrongUrl"));
  5543. return;
  5544. }
  5545. }
  5546. let maxId = 1, hasUrl = false;
  5547. if (!rulesData.urls) {
  5548. rulesData.urls = [];
  5549. }
  5550. ruleUrls.forEach(u => {
  5551. if (maxId < u.id) {
  5552. maxId = u.id;
  5553. }
  5554. if (u.url == url) {
  5555. hasUrl = true;
  5556. }
  5557. });
  5558. if (hasUrl) break;
  5559. if (!rulesData.sort) rulesData.sort = [1];
  5560. rulesData.urls.push({id: maxId + 1, url: url});
  5561. rulesData.sort.push(maxId + 1);
  5562. storage.setItem("rulesData", rulesData);
  5563. }
  5564. }
  5565. showTips(i18n("settingsSaved"));
  5566. };
  5567. return true;
  5568. }
  5569.  
  5570. function updateRules (success, fail, keepCache) {
  5571. if (!storage.supportCrossSave()) {
  5572. fail({url:''}, "Not support cross storage");
  5573. showTips("Current platform do not support cross storage!");
  5574. return;
  5575. }
  5576. if (inUpdate) return;
  5577. inUpdate = true;
  5578. let ruleIndex = ruleUrls.length - 1;
  5579. if (!keepCache) {
  5580. storage.setItem("hpRules", []);
  5581. storage.setItem("smartRules", []);
  5582. }
  5583. let allOk = true;
  5584. function addNextRule() {
  5585. if (ruleIndex < 0) {
  5586. let now = new Date().getTime();
  5587. storage.setItem("ruleLastUpdate", now);
  5588. storage.setItem("rules", ruleParser.rules);
  5589. inUpdate = false;
  5590. if (allOk) {
  5591. rulesData.uninited = false;
  5592. storage.setItem("rulesData", rulesData);
  5593. }
  5594. success();
  5595. } else {
  5596. let rule = ruleUrls[ruleIndex--];
  5597. ruleParser.addRuleByUrl(rule.url, rule.id, (json, err) => {
  5598. if (!json) {
  5599. allOk = false;
  5600. fail(rule, err);
  5601. }
  5602. addNextRule();
  5603. })
  5604. }
  5605. }
  5606. addNextRule();
  5607. }
  5608.  
  5609. function objIsArr(obj) {
  5610. return obj &&
  5611. typeof obj === 'object' &&
  5612. typeof obj.length === 'number' &&
  5613. !(obj.propertyIsEnumerable('length'));
  5614. }
  5615.  
  5616. function isVisible(el, win) {
  5617. if(!el || !el.offsetParent)return false;
  5618. var loopable = true,
  5619. visible = el.nodeName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  5620. while(loopable && visible) {
  5621. el = el.parentNode;
  5622.  
  5623. if(el && !/^BODY$/i.test(el.nodeName)) {
  5624. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  5625. }else {
  5626. loopable = false;
  5627. }
  5628. }
  5629. return visible;
  5630. }
  5631.  
  5632. function getElementTop(ele) {
  5633. if (!ele) return 0;
  5634. if (ele.getBoundingClientRect) {
  5635. return ele.getBoundingClientRect().top + document.documentElement.scrollTop;
  5636. }
  5637. var actualTop = ele.offsetTop;
  5638. var current = ele.offsetParent;
  5639. while (current) {
  5640. actualTop += current.offsetTop;
  5641. current = current.offsetParent;
  5642. }
  5643. return actualTop;
  5644. }
  5645.  
  5646. function getElementLeft(ele) {
  5647. if (!ele) return 0;
  5648. if (ele.getBoundingClientRect) {
  5649. return ele.getBoundingClientRect().left + document.documentElement.scrollLeft;
  5650. }
  5651. var actualLeft = ele.offsetLeft;
  5652. var current = ele.offsetParent;
  5653. while (current) {
  5654. actualLeft += current.offsetLeft;
  5655. current = current.offsetParent;
  5656. }
  5657. return actualLeft;
  5658. }
  5659.  
  5660. function getElementBottom(ele) {
  5661. return getElementTop(ele) + (ele.offsetHeight || ele.scrollHeight);
  5662. }
  5663.  
  5664. function getFormatJSON(obj){
  5665. if(!objIsArr(obj) || obj.length === 0)return "";
  5666. return JSON.stringify(obj, null, 4);
  5667. }
  5668.  
  5669. function globMatch(first, second) {
  5670. if (first === '*') {
  5671. return true;
  5672. }
  5673. if (first.length == 0 && second.length == 0){
  5674. return true;
  5675. }
  5676.  
  5677. if (first.length > 1 && first[0] == '*' &&
  5678. second.length == 0){
  5679. return false;
  5680. }
  5681.  
  5682. if ((first.length > 1 && first[0] == '?') ||
  5683. (first.length != 0 && second.length != 0 &&
  5684. first[0] == second[0])){
  5685. return globMatch(first.substring(1),
  5686. second.substring(1));
  5687. }
  5688.  
  5689. if (first.length > 0 && first[0] == '*'){
  5690. return globMatch(first.substring(1), second) ||
  5691. globMatch(first, second.substring(1));
  5692. }
  5693.  
  5694. return false;
  5695. }
  5696.  
  5697. let pageReady = false;
  5698. function initRules(callback) {
  5699. storage.getItem("rulesData", data => {
  5700. /*0 wedata格式,1 pagetual格式*/
  5701. ruleUrls = [{
  5702. id: 1,
  5703. url: data && data.wedata2github ? 'https://hoothin.github.io/UserScripts/Pagetual/items_all.json' : 'http://wedata.net/databases/AutoPagerize/items_all.json',
  5704. type: 0,
  5705. }];
  5706. if (data) {
  5707. rulesData = data;
  5708. if (data.urls) ruleUrls = ruleUrls.concat(data.urls);
  5709. if (data.sort) {
  5710. let urls = [];
  5711. data.sort.forEach(id => {
  5712. for (let s = 0; s < ruleUrls.length; s++) {
  5713. if (id == ruleUrls[s].id) {
  5714. urls.push(ruleUrls[s]);
  5715. break;
  5716. }
  5717. }
  5718. });
  5719. ruleUrls = urls;
  5720. }
  5721. }
  5722. if (rulesData.blacklist && rulesData.blacklist.length > 0) {
  5723. let href = location.href.slice(0, 500);
  5724. let commentStart = false;
  5725. for (let i = 0; i < rulesData.blacklist.length; i++) {
  5726. let curGlob = rulesData.blacklist[i];
  5727. if (!curGlob) continue;
  5728. if (curGlob.indexOf("//") == 0) continue;
  5729. if (commentStart) {
  5730. if (/\*\/$/.test(curGlob)) {
  5731. commentStart = false;
  5732. }
  5733. continue;
  5734. }
  5735. if (curGlob.indexOf("/*") == 0) {
  5736. commentStart = true;
  5737. continue;
  5738. }
  5739. if (curGlob.indexOf("/") == 0) {
  5740. let regMatch = curGlob.match(/^\/(.*)\/(\w*)$/);
  5741. if (regMatch && new RegExp(regMatch[1], regMatch[2]).test(href)) {
  5742. forceState == 1;
  5743. return;
  5744. }
  5745. } else if (globMatch(curGlob, href)) {
  5746. forceState == 1;
  5747. return;
  5748. }
  5749. }
  5750. }
  5751. if (rulesData.lang) {
  5752. setLang(rulesData.lang);
  5753. }
  5754. _GM_registerMenuCommand(i18n("configure"), () => {
  5755. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  5756. });
  5757. _GM_registerMenuCommand(i18n("editCurrent"), () => {
  5758. picker.start();
  5759. });
  5760. ruleParser.initSavedRules(async () => {
  5761. let upBtnImg = rulesData.upBtnImg, downBtnImg = rulesData.downBtnImg, _sideControllerIcon = rulesData.sideControllerIcon;
  5762. if (upBtnImg && downBtnImg) {
  5763. downSvgCSS = downSvgCSS.replace("transform: rotate(180deg);", "");
  5764. } else if (upBtnImg && !downBtnImg) {
  5765. downBtnImg = upBtnImg;
  5766. } else if(downBtnImg && !upBtnImg) {
  5767. upBtnImg = downBtnImg;
  5768. }
  5769. if (upBtnImg) {
  5770. upSvg = /https?:|data/.test(upBtnImg) ? `<img class="pagetual" src="${upBtnImg}"/>` : `<span>${upBtnImg}</span>`;
  5771. }
  5772. if (downBtnImg) {
  5773. downSvg = /https?:|data/.test(downBtnImg) ? `<img class="pagetual" src="${downBtnImg}"/>` : `<span>${downBtnImg}</span>`;
  5774. }
  5775. if (_sideControllerIcon) {
  5776. sideControllerIcon = /https?:|data/.test(_sideControllerIcon) ? `<img class="pagetual" src="${_sideControllerIcon}"/>` : `<span>${_sideControllerIcon}</span>`;
  5777. }
  5778. setLoadingDiv(rulesData.loadingText || i18n("loadingText"));
  5779. if (typeof(rulesData.opacity) == "undefined") {
  5780. rulesData.opacity = 1;
  5781. }
  5782. if (typeof(rulesData.hideBar) == "undefined") {
  5783. rulesData.hideBar = false;
  5784. }
  5785. if (typeof(rulesData.dbClick2Stop) == "undefined") {
  5786. rulesData.dbClick2Stop = true;
  5787. }
  5788. if (typeof(rulesData.enableWhiteList) == "undefined") {
  5789. rulesData.enableWhiteList = false;
  5790. }
  5791. if (typeof(rulesData.enableHistory) == "undefined") {
  5792. rulesData.enableHistory = false;
  5793. }
  5794. if (typeof(rulesData.openInNewTab) == "undefined") {
  5795. rulesData.openInNewTab = false;
  5796. }
  5797. if (typeof(rulesData.enableDebug) == "undefined") {
  5798. rulesData.enableDebug = true;
  5799. }
  5800. if (typeof(rulesData.initRun) == "undefined") {
  5801. rulesData.initRun = true;
  5802. }
  5803. if (typeof(rulesData.preload) == "undefined") {
  5804. rulesData.preload = true;
  5805. }
  5806. if (typeof(rulesData.customFirst) == "undefined") {
  5807. rulesData.customFirst = false;
  5808. }
  5809. if (typeof(rulesData.manualMode) == "undefined") {
  5810. rulesData.manualMode = false;
  5811. }
  5812. if (typeof(rulesData.clickMode) == "undefined") {
  5813. rulesData.clickMode = false;
  5814. }
  5815. if (typeof(rulesData.pageBarMenu) == "undefined") {
  5816. rulesData.pageBarMenu = true;
  5817. }
  5818. if (typeof(rulesData.arrowToScroll) == "undefined") {
  5819. rulesData.arrowToScroll = false;
  5820. }
  5821. if (typeof(rulesData.hideLoadingIcon) == "undefined") {
  5822. rulesData.hideLoadingIcon = false;
  5823. }
  5824. if (typeof(rulesData.hideBarArrow) == "undefined") {
  5825. rulesData.hideBarArrow = false;
  5826. }
  5827. if (typeof(rulesData.lastPageTips) == "undefined") {
  5828. rulesData.lastPageTips = true;
  5829. }
  5830. if (rulesData.autoLoadNum && rulesData.initRun) {
  5831. autoLoadNum = parseInt(rulesData.autoLoadNum);
  5832. }
  5833. openInNewTab = rulesData.openInNewTab ? 1 : 0;
  5834. enableDebug = rulesData.enableDebug;
  5835.  
  5836. let _nextSwitch = await getData("nextSwitch_" + location.host);
  5837. if (typeof(_nextSwitch) !== "undefined") {
  5838. nextIndex = _nextSwitch;
  5839. }
  5840.  
  5841. let _forceState = await getData("forceState_" + location.host);
  5842. if (typeof(_forceState) == "undefined") {
  5843. _forceState = (rulesData.enableWhiteList ? 1 : 0);
  5844. }
  5845. forceState = _forceState;
  5846.  
  5847. autoScroll = await getData("autoScroll_" + location.host + location.pathname) || 0;
  5848.  
  5849. updateDate = await getData("ruleLastUpdate");
  5850.  
  5851. manualPause = !!await getData("pauseState_" + location.host);
  5852.  
  5853. let href = location.href.slice(0, 100);
  5854. try {
  5855. if (_unsafeWindow.initedPagetual) {
  5856. if (ruleImportUrlReg.test(href)) {
  5857. showTips(i18n('duplicate'));
  5858. }
  5859. return;
  5860. }
  5861. _unsafeWindow.initedPagetual = true;
  5862. } catch(e) {showTips(e)}
  5863. listenUrl();
  5864. _GM_registerMenuCommand(i18n("update"), () => {
  5865. showTips(i18n("beginUpdate"), "", 60000);
  5866. updateRules(() => {
  5867. showTips(i18n("updateSucc"));
  5868. location.reload();
  5869. },(rule, err) => {
  5870. showTips(`Failed to update ${rule.url} rules!`);
  5871. debug(err);
  5872. });
  5873. });
  5874. _GM_registerMenuCommand(i18n(forceState == 1 ? "enable" : "disableSite"), () => {
  5875. if (forceState == 1) {
  5876. forceState = 0;
  5877. showTips(i18n("enableSiteTips"));
  5878. changeStop(false);
  5879. } else {
  5880. forceState = 1;
  5881. showTips(i18n("disableSiteTips"));
  5882. changeStop(true);
  5883. sideController.remove();
  5884. }
  5885. storage.setItem("forceState_" + location.host, forceState);
  5886. if (!ruleParser.curSiteRule.url) location.reload();
  5887. });
  5888. _GM_registerMenuCommand(i18n("toggleAutoScroll"), () => {
  5889. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), 50)) || 0;
  5890. autoScroll = parseInt(autoScroll) || 0;
  5891. if (autoScroll < 0) autoScroll = 0;
  5892. else if (autoScroll > 1000) autoScroll = 1000;
  5893. storage.setItem("autoScroll_" + location.host + location.pathname, autoScroll);
  5894. startAutoScroll();
  5895. });
  5896. startAutoScroll();
  5897.  
  5898.  
  5899. if (initConfig(href)) return;
  5900. pageReady = true;
  5901. if (forceState == 1) return;
  5902. let now = new Date().getTime();
  5903. if (!updateDate || now - updateDate > 2 * 24 * 60 * 60 * 1000) {
  5904. updateRules(() => {
  5905. }, (rule, err) => {}, true);
  5906. storage.setItem("ruleLastUpdate", now);
  5907. }
  5908. callback();
  5909. });
  5910. });
  5911. }
  5912.  
  5913. function requestDoc(url, callback){
  5914. let postParams = url.match(/#p{(.*)}$/);
  5915. if (postParams) {
  5916. postParams = postParams[1];
  5917. url = url.replace(/#p{.*/, "");
  5918. }
  5919. let ruleHeaders = ruleParser.curSiteRule.headers;
  5920. let headers = {
  5921. 'Referer': location.href,
  5922. 'User-Agent': navigator.userAgent,
  5923. 'accept': 'text/html,application/xhtml+xml,application/xml',
  5924. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + (document.characterSet || document.charset || document.inputEncoding),
  5925. };
  5926. if (ruleHeaders) {
  5927. if (ruleHeaders.referer) {
  5928. headers.referer = ruleHeaders.referer;
  5929. }
  5930. if (ruleHeaders.userAgent) {
  5931. headers.userAgent = ruleHeaders.userAgent;
  5932. }
  5933. if (ruleHeaders.accept) {
  5934. headers.accept = ruleHeaders.accept;
  5935. }
  5936. if (ruleHeaders.contentType) {
  5937. headers.contentType = ruleHeaders.contentType;
  5938. }
  5939. if (ruleHeaders.cookie) {
  5940. headers.cookie = ruleHeaders.cookie;
  5941. }
  5942. }
  5943. _GM_xmlhttpRequest({
  5944. url: url,
  5945. method: postParams ? 'POST' : 'GET',
  5946. data: postParams,
  5947. overrideMimeType: 'text/html;charset=' + (document.characterSet || document.charset || document.inputEncoding),
  5948. headers: headers,
  5949. timeout: 20000,
  5950. onload: async function(res) {
  5951. if (isPause) return callback(false);
  5952. var doc = null, response = res.response;
  5953. let preCode = ruleParser.curSiteRule.pageElementPre || ruleParser.curSiteRule.pagePre;
  5954. if (preCode) {
  5955. try {
  5956. if (typeof preCode == 'function') {
  5957. response = preCode(response);
  5958. } else if (preCode.length == 2) {
  5959. response = response.replace(new RegExp(preCode[0], "gi"), preCode[1]);
  5960. } else {
  5961. response = Function("response",'"use strict";' + preCode)(response);
  5962. }
  5963. } catch(e) {
  5964. debug(e);
  5965. }
  5966. }
  5967. try {
  5968. doc = document.implementation.createHTMLDocument('');
  5969. doc.documentElement.innerHTML = response;
  5970. let base = doc.querySelector("base");
  5971. ruleParser.basePath = base ? base.href : url;
  5972. }
  5973. catch (e) {
  5974. debug('parse error:' + e.toString());
  5975. }
  5976. let pageElement = ruleParser.getPageElement(doc);
  5977. if ((!pageElement || pageElement.length == 0) && res.status >= 400) {
  5978. debug(res.status, "Error status");
  5979. return callback(false);
  5980. }
  5981. if (inCors && (!pageElement || pageElement.length == 0) && ruleParser.curSiteRule.singleUrl) {
  5982. let article = doc.querySelectorAll(mainSel);
  5983. if (article && article.length == 1) {
  5984. article = article[0];
  5985. ruleParser.curSiteRule.pageElement = article.nodeName.toLowerCase() + (article.id ? "#" + article.id : "") + (article.className ? "." + article.className.replace(/ /g, ".") : "") + ">*";
  5986. pageElement = article.children;
  5987. } else {
  5988. ruleParser.curSiteRule.pageElement = allOfBody;
  5989. pageElement = ruleParser.getPageElement(doc);
  5990. }
  5991. ruleParser.getInsert(true);
  5992. }
  5993. //只有1的話怕不是圖片哦
  5994. if (pageElement && (pageElement.length > 1 || (pageElement.length == 1 && !/^IMG$/i.test(pageElement[0].nodeName)))) {
  5995. await ruleParser.insertPage(doc, pageElement, url, callback, false);
  5996. if (ruleParser.curSiteRule.action == 1) {
  5997. isLoading = true;
  5998. requestFromIframe(url, (doc, eles) => {
  5999. if (eles) {
  6000. ruleParser.insertPage(doc, eles, url, callback, true);
  6001. } else isLoading = false;
  6002. });
  6003. } else ruleParser.curSiteRule.action = 0;
  6004. } else if ((ruleParser.curSiteRule.singleUrl || curPage == 1) && !inCors) {
  6005. ruleParser.curSiteRule.action = 1;
  6006. requestFromIframe(url, (doc, eles) => {
  6007. if (eles) {
  6008. ruleParser.insertPage(doc, eles, url, callback, true);
  6009. } else isLoading = false;
  6010. });
  6011. } else {
  6012. debug("Stop as no page element");
  6013. ruleParser.noValidContent(url);
  6014. isPause = true;
  6015. callback(false);
  6016. }
  6017. },
  6018. onerror: function(e) {
  6019. debug(e, "NetError");
  6020. callback(false);
  6021. },
  6022. ontimeout: function(e) {
  6023. debug(e, "NetTimeout");
  6024. callback(false);
  6025. }
  6026. });
  6027. }
  6028.  
  6029. function initPage() {
  6030. ruleParser.initPage(() => {
  6031. if (ruleParser.curSiteRule.autoLoadNum) {
  6032. autoLoadNum = ruleParser.curSiteRule.autoLoadNum;
  6033. }
  6034. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  6035. _GM_registerMenuCommand(i18n("nextSwitch"), () => {
  6036. nextSwitch.start();
  6037. });
  6038. }
  6039. if (ruleParser.nextLinkHref) {
  6040. let isJs = ruleParser.hrefIsJs(ruleParser.nextLinkHref);
  6041. if (!isJs) {
  6042. let inForce = (forceState == 2 || forceState == 3);
  6043. _GM_registerMenuCommand(i18n(inForce ? "cancelForceIframe" : "forceIframe"), () => {
  6044. if (inForce) {
  6045. storage.setItem("forceState_" + location.host, "");
  6046. } else {
  6047. let _state = ruleParser.curSiteRule.action > 0 || confirm(i18n("forceAllBody")) ? 2 : 3;
  6048. storage.setItem("forceState_" + location.host, _state);
  6049. }
  6050. location.reload();
  6051. });
  6052. }
  6053. _GM_registerMenuCommand(i18n("loadNow"), () => {
  6054. let loadNum = window.prompt(i18n("loadConfirm"), "1");
  6055. if (loadNum === "" || loadNum === null) return;
  6056. autoLoadNum = Math.abs(parseInt(loadNum));
  6057. nextPage();
  6058. });
  6059. }
  6060. initListener();
  6061. });
  6062. }
  6063.  
  6064. var pageBarStyle, mainStyleEle, mainStyleStyle;
  6065. function initView() {
  6066. if (!mainStyleStyle) {
  6067. mainStyleStyle = `
  6068. .pagetual_pageBar{
  6069. -moz-transition:all 0.3s ease-in-out 0s;
  6070. -webkit-transition:all 0.3s ease-in-out 0s;
  6071. transition:all 0.3s ease-in-out 0s;
  6072. font-family: Arial,sans-serif !important;
  6073. text-align: center !important;
  6074. }
  6075. .pagetual_pageBar.stop {
  6076. -webkit-filter: invert(100%);
  6077. filter: invert(100%);
  6078. opacity: 1!important;
  6079. }
  6080. .pagetual_pageBar.hide {
  6081. display: none!important;
  6082. }
  6083. .pagetual-hide {
  6084. display: none!important;
  6085. }
  6086. .pagetual_pageBar:hover {
  6087. opacity: 1!important;
  6088. box-shadow: 0px 0px 10px 0px #000000aa;
  6089. border-radius: 20px;
  6090. background-color: rgb(240 240 240 / 80%);
  6091. border-color: transparent!important;
  6092. }
  6093. .pagetual_pageBar span {
  6094. vertical-align: super;
  6095. }
  6096. .pagetual_pageBar a::before,
  6097. .pagetual_pageBar a::after {
  6098. content: none;
  6099. }
  6100. .pagetual_pageBar a>span {
  6101. margin-top: 0!important;
  6102. pointer-events: none;
  6103. padding: unset;
  6104. opacity: 0;
  6105. -moz-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  6106. -webkit-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  6107. transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  6108. transform: none;
  6109. left: 0;
  6110. margin-left: calc(50% - 20px);
  6111. }
  6112. .pagetual_pageBar a>span:hover {
  6113. color: red;
  6114. }
  6115. .pagetual_pageBar a:hover>span {
  6116. opacity: 1;
  6117. }
  6118. .pagetual_pageBar span.prevScreen,
  6119. .pagetual_pageBar span.nextScreen {
  6120. display: block!important;
  6121. }
  6122. .pagetual_pageBar a:hover>span.prevScreen {
  6123. margin-top: -${rulesData.opacity == 1 ? 31 : 30}px!important;
  6124. pointer-events: all;
  6125. }
  6126. .pagetual_pageBar a:hover>span.nextScreen {
  6127. margin-top: 30px!important;
  6128. pointer-events: all;
  6129. }
  6130. .pagetual_pageBar span>svg {
  6131. -moz-transition:transform 0.5s ease, opacity 0.3s ease;
  6132. -webkit-transition:transform 0.5s ease, opacity 0.3s ease;
  6133. transition:transform 0.5 ease, opacity 0.3s ease;
  6134. opacity: 0;
  6135. }
  6136. .pagetual_pageBar.stop span>svg{
  6137. opacity: 1;
  6138. }
  6139. .pagetual_pageBar.stop span>svg>path{
  6140. transform: scale(.8);
  6141. transform-origin: center;
  6142. -moz-transition:transform 0.3s ease;
  6143. -webkit-transition:transform 0.3s ease;
  6144. transition:transform 0.3 ease;
  6145. }
  6146. .pagetual_pageBar.stop:hover span>svg>path{
  6147. transform: unset;
  6148. }
  6149. .pagetual_pageBar:hover span>svg {
  6150. opacity: 1;
  6151. }
  6152. .pagetual_pageBar span>svg.upSvg:hover {
  6153. transform: rotate(360deg) scale3d(1.2, 1.2, 1.2);
  6154. }
  6155. .pagetual_pageBar span>svg.downSvg:hover {
  6156. transform: rotate(540deg) scale3d(1.2, 1.2, 1.2)!important;
  6157. }
  6158. .pagetual_pageBar .pagetual_pageNum{
  6159. color: #55555f;
  6160. }
  6161. .pagetual_pageBar .pagetual_pageNum:hover{
  6162. color: #ff6464;
  6163. }
  6164. .pagetual_tipsWords {
  6165. font-size: 50px;
  6166. font-weight: bold;
  6167. font-family: "黑体", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
  6168. "Oxygen", "Ubuntu", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
  6169. "Segoe UI Emoji", "Segoe UI Symbol";
  6170. color: #ffffff;
  6171. min-height: 70px;
  6172. max-width: 80%;
  6173. line-height: 70px;
  6174. position: fixed;
  6175. left: 50%;
  6176. top: 10%;
  6177. margin-left: -99999px;
  6178. padding: 0 15px;
  6179. z-index: 2147483647;
  6180. background-color: #000;
  6181. border: 1px solid #303030;
  6182. border-radius: 10px;
  6183. opacity: 0;
  6184. filter: alpha(opacity=65);
  6185. box-shadow: 5px 5px 20px 0px #000;
  6186. -moz-transition:opacity 0.3s ease-in-out 0s;
  6187. -webkit-transition:opacity 0.3s ease-in-out 0s;
  6188. transition:opacity 0.3s ease-in-out 0s;
  6189. pointer-events: none;
  6190. }
  6191. .pagetual_tipsWords>a {
  6192. color: #ffffff;
  6193. }
  6194. .pagetual_loading {
  6195. width: 50px;
  6196. height: 50px;
  6197. margin: 10px auto;
  6198. border-radius: 100%;
  6199. display: flex;
  6200. -webkit-animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  6201. animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  6202. }
  6203. @-webkit-keyframes pagetual_loading_scaleout {
  6204. 0% { -webkit-transform: scale(0.0) }
  6205. 100% {
  6206. -webkit-transform: scale(1.0);
  6207. opacity: 0;
  6208. }
  6209. }
  6210. @keyframes pagetual_loading_scaleout {
  6211. 0% {
  6212. transform: scale(0.0);
  6213. -webkit-transform: scale(0.0);
  6214. } 100% {
  6215. transform: scale(1.0);
  6216. -webkit-transform: scale(1.0);
  6217. opacity: 0;
  6218. }
  6219. }
  6220. .pagetual_loading_text {
  6221. white-space: nowrap;
  6222. -webkit-animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  6223. animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  6224. }
  6225. @-webkit-keyframes pagetual_loading_opacity {
  6226. 0% { opacity: 1 }
  6227. 50% { opacity: 0.2 }
  6228. 100% { opacity: 1 }
  6229. }
  6230. @keyframes pagetual_loading_opacity {
  6231. 0% { opacity: 1 }
  6232. 50% { opacity: 0.2 }
  6233. 100% { opacity: 1 }
  6234. }
  6235. `;
  6236. let bodyColor
  6237. 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%);"}`;
  6238. }
  6239. if (!mainStyleEle || !mainStyleEle.parentNode) {
  6240. mainStyleEle = _GM_addStyle(mainStyleStyle);
  6241. }
  6242. }
  6243. var loadingDiv = document.createElement("div");
  6244. 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;";
  6245.  
  6246. 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;`;
  6247. function setLoadingDiv(loadingText) {
  6248. 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>`}`);
  6249. }
  6250.  
  6251. 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>`;
  6252. 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;`;
  6253. 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>`;
  6254. 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);`;
  6255.  
  6256. 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;`;
  6257. 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;`;
  6258. var sideControllerIcon = '';
  6259.  
  6260. var tipsWords = document.createElement("div");
  6261. tipsWords.className = "pagetual_tipsWords";
  6262.  
  6263. var changeStopTimer;
  6264. function changeStop(stop) {
  6265. isPause = stop;
  6266. clearTimeout(changeStopTimer);
  6267. changeStopTimer = setTimeout(() => {
  6268. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar,#pagetual-sideController"), bar => {
  6269. if (isPause) {
  6270. bar.classList.add("stop");
  6271. } else {
  6272. bar.classList.remove("stop");
  6273. }
  6274. });
  6275. if (!isPause) ruleParser.showAddedElements();
  6276. manualPause = isPause;
  6277. storage.setItem("pauseState_" + location.host, isPause ? true : "");
  6278. }, 350);
  6279. }
  6280.  
  6281. function changeHideBar(hide) {
  6282. isHideBar = hide;
  6283. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar"), bar => {
  6284. if (isHideBar) {
  6285. bar.classList.add("hide");
  6286. } else {
  6287. bar.classList.remove("hide");
  6288. }
  6289. });
  6290. }
  6291.  
  6292. function isInViewPort(element) {
  6293. if (!getBody(document).contains(element)) return false;
  6294. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  6295. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  6296. const {
  6297. top,
  6298. right,
  6299. bottom,
  6300. left,
  6301. } = element.getBoundingClientRect();
  6302.  
  6303. return (
  6304. top >= 0 &&
  6305. left >= 0 &&
  6306. right <= viewWidth + 1 &&
  6307. top <= viewHeight * (ruleParser.curSiteRule.rate || rulesData.rate || 1) &&
  6308. isVisible(element, _unsafeWindow)
  6309. );
  6310. }
  6311.  
  6312. function getPageBar() {
  6313. let preBar = null, nextBar = null;
  6314. let pageBars = [].slice.call(document.querySelectorAll(".pagetual_pageBar"));
  6315. for (let i = 0; i < pageBars.length; i++) {
  6316. let pageBar = pageBars[i];
  6317. if (!pageBar || !getBody(document).contains(pageBar)) continue;
  6318. let {
  6319. top,
  6320. right,
  6321. bottom,
  6322. left,
  6323. } = pageBar.getBoundingClientRect();
  6324. if (top > 500) {
  6325. nextBar = pageBar;
  6326. preBar = (i - 1 >= 0 ? pageBars[i - 1] : null);
  6327. if (pageBar && getBody(document).contains(pageBar)) {
  6328. let {
  6329. top,
  6330. right,
  6331. bottom,
  6332. left,
  6333. } = pageBar.getBoundingClientRect();
  6334. if (top < -500) {
  6335. preBar = pageBar;
  6336. } else preBar = (i - 2 >= 0 ? pageBars[i - 2] : null);
  6337. }
  6338. break;
  6339. }
  6340. }
  6341. if (!nextBar) preBar = pageBars[pageBars.length - 2];
  6342. return {preBar: preBar, nextBar: nextBar};
  6343. }
  6344.  
  6345. var urlChanged = false;
  6346. var urlChanging = false;
  6347. var urlchangeHandler = e => {
  6348. if (ruleParser && ruleParser.curSiteRule && ruleParser.curSiteRule.listenUrlChange == false) return;
  6349. isPause = true;
  6350. setTimeout(() => {
  6351. lastActiveUrl = location.href;
  6352. if (urlChanging) return;
  6353. urlChanging = true;
  6354. let href = location.href.slice(0, 60);
  6355. if (href == configPage[0]) {
  6356. setTimeout(() => {
  6357. initConfig(href);
  6358. urlChanging = false;
  6359. }, 1000);
  6360. } else {
  6361. setTimeout(() => {
  6362. if (guidePage.test(href)) {
  6363. setTimeout(() => {
  6364. initConfig(href);
  6365. urlChanging = false;
  6366. }, 1000);
  6367. } else {
  6368. urlChanged = true;
  6369. if (!ruleParser.nextLinkHref) {
  6370. isLoading = false;
  6371. }
  6372. urlChanging = false;
  6373. //if (!pageReady && !ruleImportUrlReg.test(href)) location.reload();
  6374. }
  6375. }, 500);
  6376. }
  6377. }, 1);
  6378. };
  6379. window.addEventListener('pagetual_pushState', urlchangeHandler);
  6380. /*var _wr = function(type) {
  6381. var orig = history[type];
  6382. return function() {
  6383. var rv = orig.apply(this, arguments);
  6384. var e = new Event('pagetual_' + type);
  6385. e.arguments = arguments;
  6386. window.dispatchEvent(e);
  6387. return rv;
  6388. };
  6389. };
  6390. history.pushState = _wr('pushState');*/
  6391.  
  6392. function listenUrl() {
  6393. var prevPathname = window.location.pathname;
  6394. var prevSearch = window.location.search;
  6395. var checkUrlTime = 100;
  6396. var checkUrlTimer;
  6397. var checkClickedEle = null;
  6398. var checkFunc = () => {
  6399. if (forceState == 1) return;
  6400. if (checkClickedEle) {
  6401. if (!clickedSth && checkClickedEle && checkClickedEle.nodeName) {
  6402. if (/^(A|BUTTON)$/i.test(checkClickedEle.nodeName)) {
  6403. clickedSth = true;
  6404. } else {
  6405. let targetStyle = _unsafeWindow.getComputedStyle(checkClickedEle);
  6406. if (targetStyle.cursor == "pointer") clickedSth = true;
  6407. }
  6408. }
  6409. checkClickedEle = null;
  6410. }
  6411. if (checkUrlTime < 5000) {
  6412. checkUrlTime += checkUrlTime>>1;
  6413. }
  6414. clearTimeout(checkUrlTimer);
  6415. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  6416. if (document.hidden) return;
  6417. if ((prevPathname !== window.location.pathname || prevSearch !== window.location.search) && window.location.href != ruleParser.historyUrl) {
  6418. checkUrlTime = 2000;
  6419. prevPathname = window.location.pathname;
  6420. prevSearch = window.location.search;
  6421. var e = new Event('pagetual_pushState');
  6422. e.arguments = arguments;
  6423. window.dispatchEvent(e);
  6424. clickedSth = false;
  6425. }
  6426. };
  6427. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  6428.  
  6429. document.addEventListener("click", e => {
  6430. if (!checkClickedEle) {
  6431. checkClickedEle = e.target;
  6432. checkUrlTime = 300;
  6433. clearTimeout(checkUrlTimer);
  6434. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  6435. }
  6436. });
  6437. }
  6438.  
  6439. let scrollContainer;
  6440. function distToBottom () {
  6441. let scrolly = window.scrollY;
  6442. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  6443. if (!scrollContainer || !document.documentElement.contains(scrollContainer)) {
  6444. let pageEle = ruleParser.getPageElement(document);
  6445. if (pageEle && pageEle.length) {
  6446. let parent = pageEle[0].parentNode, pageScrollY = parent.scrollTop;;
  6447. while (parent && pageScrollY == 0) {
  6448. parent = parent.parentNode;
  6449. pageScrollY = parent.scrollTop;
  6450. }
  6451. if (pageScrollY) {
  6452. scrollContainer = parent;
  6453. return scrollContainer.scrollHeight - pageScrollY - windowHeight;
  6454. }
  6455. }
  6456. }
  6457. if (scrollContainer) {
  6458. return scrollContainer.scrollHeight - scrollContainer.scrollTop - windowHeight;
  6459. }
  6460.  
  6461. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  6462. return scrollH - scrolly - windowHeight;
  6463. }
  6464.  
  6465. let scrollHandler, clickToResetHandler, dblclickHandler, keydownHandler, hashchangeHandler, manualModeKeyHandler, pagetualNextHandler, keyupHandler;
  6466. function initListener () {
  6467. document.removeEventListener('scroll', scrollHandler, true);
  6468. document.removeEventListener('wheel', scrollHandler, true);
  6469. document.removeEventListener('dblclick', dblclickHandler);
  6470. document.removeEventListener('keydown', keydownHandler);
  6471. window.removeEventListener('hashchange', hashchangeHandler, false);
  6472. document.removeEventListener('keydown', manualModeKeyHandler);
  6473. document.removeEventListener('pagetual.next', pagetualNextHandler, false);
  6474. document.removeEventListener('keyup', keyupHandler);
  6475. let loadmoreBtn, loadingMore = true, lastScroll = 0, checkLoadMoreTimes = 0;
  6476. if (ruleParser.curSiteRule.singleUrl) {
  6477. loadingMore = false;
  6478. } else if (ruleParser.curSiteRule.loadMore) {
  6479. loadingMore = false;
  6480. }
  6481. clickMode = typeof ruleParser.curSiteRule.clickMode == 'undefined' ? rulesData.clickMode : ruleParser.curSiteRule.clickMode;
  6482. let clickingNext = false;
  6483. let clickNext = async () => {
  6484. if (clickingNext) return;
  6485. clickingNext = true;
  6486. setTimeout(() => {
  6487. clickingNext = false;
  6488. }, 1500);
  6489. let nextLink = ruleParser.nextLinkHref;
  6490. if (!nextLink) return;
  6491. let isJs = ruleParser.hrefIsJs(nextLink);
  6492. if (isJs) {
  6493. let nextBtn = ruleParser.nextLinkEle;
  6494. if (!nextBtn || !nextBtn.offsetParent) nextBtn = await ruleParser.getNextLink(document, true);
  6495. if (nextBtn) emuClick(nextBtn);
  6496. } else {
  6497. window.location.href = nextLink;
  6498. }
  6499. };
  6500. let checkScrollReach = () => {
  6501. let dist = distToBottom();
  6502. if (clickMode) {
  6503. if (dist < 10) {
  6504. clickNext();
  6505. }
  6506. } else if (dist < bottomGap) {
  6507. nextPage();
  6508. }
  6509. };
  6510. scrollHandler = e => {
  6511. if (urlChanged && !isLoading) {
  6512. ruleParser.initPage(() => {});
  6513. urlChanged = false;
  6514. loadingMore = false;
  6515. }
  6516. if (isPause) return;
  6517. if (!loadingMore) {
  6518. loadmoreBtn = getLoadMore(document, loadmoreBtn);
  6519. if (loadmoreBtn) {
  6520. if (isInViewPort(loadmoreBtn)) {
  6521. emuClick(loadmoreBtn);
  6522. loadingMore = true;
  6523. setTimeout(() => {loadingMore = false}, 200);
  6524. }
  6525. } else {
  6526. loadingMore = true;
  6527. if (!ruleParser.curSiteRule.singleUrl || checkLoadMoreTimes++ < 3) {
  6528. setTimeout(() => {loadingMore = false}, 200);
  6529. }
  6530. }
  6531. }
  6532. if (!isLoading && !stopScroll) {
  6533. checkScrollReach();
  6534. }
  6535. ruleParser.changeVisibility();
  6536. if (ruleParser.curSiteRule.lockScroll) {
  6537. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  6538. if (isLoading && Math.abs(lastScroll - curScroll) > 350) {
  6539. getBody(document).scrollTop = lastScroll;
  6540. document.documentElement.scrollTop = lastScroll;
  6541. } else {
  6542. lastScroll = curScroll;
  6543. }
  6544. }
  6545. };
  6546. dblclickHandler = e => {
  6547. if (forceState == 1 || /^(INPUT|TEXTAREA|SELECT)$/i.test(e.target.nodeName)) return;
  6548. if (!rulesData.dbClick2StopKey) {
  6549. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  6550. (rulesData.dbClick2StopAlt && !e.altKey) ||
  6551. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  6552. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  6553. return;
  6554. }
  6555. }
  6556. if (!/^BODY$/i.test(e.target.nodeName) && !e.target.classList.contains('pagetual_pageBar')) {
  6557. try {
  6558. let selection = window.getSelection();
  6559. let selStr = selection.toString().trim();
  6560. if (!selStr) {
  6561. selection = selection.getRangeAt(0);
  6562. selStr = selection && selection.cloneContents().children[0];
  6563. if (selStr && !/^IMG$/i.test(selStr.nodeName)) selStr = false;
  6564. }
  6565. if (selStr) {
  6566. return;
  6567. }
  6568. } catch (e) {}
  6569. }
  6570. if (rulesData.dbClick2Stop && (ruleParser.nextLinkHref || loadmoreBtn)) {
  6571. setTimeout(() => {
  6572. if (rulesData.hideBarButNoStop || rulesData.hideBar) {
  6573. changeHideBar(!isHideBar);
  6574. }
  6575. if (!rulesData.hideBarButNoStop) {
  6576. changeStop(!isPause);
  6577. showTips(i18n(isPause ? "disable" : "enable"));
  6578. }
  6579. if (!isPause) {
  6580. checkScrollReach();
  6581. }
  6582. }, 10);
  6583. }
  6584. };
  6585. document.addEventListener('dblclick', dblclickHandler);
  6586. clickToResetHandler = e => {
  6587. if (!ruleParser.nextLinkHref) isLoading = false;
  6588. };
  6589. document.addEventListener('click', clickToResetHandler);
  6590. if (rulesData.dbClick2StopKey) {
  6591. keydownHandler = e => {
  6592. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  6593. (rulesData.dbClick2StopAlt && !e.altKey) ||
  6594. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  6595. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  6596. return;
  6597. }
  6598. if (document.activeElement &&
  6599. (/^(INPUT|TEXTAREA)$/i.test(document.activeElement.nodeName) ||
  6600. document.activeElement.contentEditable == 'true')) {
  6601. return;
  6602. }
  6603. var key = e.key.toLowerCase();
  6604. if (rulesData.dbClick2StopKey.toLowerCase() == key) {
  6605. if (forceState == 1) {
  6606. forceState = 0;
  6607. showTips(i18n("enableSiteTips"));
  6608. changeStop(false);
  6609. } else {
  6610. forceState = 1;
  6611. showTips(i18n("disableSiteTips"));
  6612. changeStop(true);
  6613. sideController.remove();
  6614. }
  6615. if (!ruleParser.curSiteRule.url) {
  6616. storage.setItem("forceState_" + location.host, forceState);
  6617. location.reload();
  6618. }
  6619. }
  6620. };
  6621. document.addEventListener('keydown', keydownHandler);
  6622. }
  6623. if (ruleParser.curSiteRule.listenHashChange) {
  6624. hashchangeHandler = () => {
  6625. isPause = true;
  6626. urlChanged = true;
  6627. if (!ruleParser.nextLinkHref) isLoading = false;
  6628. };
  6629. window.addEventListener('hashchange', hashchangeHandler, false);
  6630. }
  6631. let manualMode = typeof ruleParser.curSiteRule.manualMode == 'undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode;
  6632. if (manualMode) {
  6633. manualModeKeyHandler = e => {
  6634. if (document.activeElement &&
  6635. (/^(INPUT|TEXTAREA)$/i.test(document.activeElement.nodeName) ||
  6636. document.activeElement.contentEditable == 'true')) {
  6637. return;
  6638. }
  6639. if (e.keyCode == 39) {
  6640. clickNext();
  6641. } else if (e.keyCode == 37) {
  6642. history.back();
  6643. }
  6644. };
  6645. document.addEventListener('keydown', manualModeKeyHandler);
  6646. pagetualNextHandler = () => {
  6647. clickNext();
  6648. };
  6649. document.addEventListener('pagetual.next', pagetualNextHandler, false);
  6650. return;
  6651. }
  6652. if (rulesData.arrowToScroll) {
  6653. keyupHandler = e => {
  6654. if (document.activeElement &&
  6655. (/^(INPUT|TEXTAREA)$/i.test(document.activeElement.nodeName) ||
  6656. document.activeElement.contentEditable == 'true')) {
  6657. return;
  6658. }
  6659. if (e.keyCode == 39) {
  6660. let nextPageBar=getPageBar().nextBar;
  6661. if (nextPageBar) {
  6662. scrollToPageBar(nextPageBar);
  6663. } else {
  6664. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  6665. window.scrollTo({ top: scrollTop + (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  6666. }
  6667. } else if (e.keyCode == 37) {
  6668. let prePageBar = getPageBar().preBar;
  6669. if (prePageBar) {
  6670. scrollToPageBar(prePageBar);
  6671. } else {
  6672. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  6673. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  6674. }
  6675. }
  6676. };
  6677. document.addEventListener('keyup', keyupHandler);
  6678. }
  6679. if (!ruleParser.curSiteRule.wheel) {
  6680. document.addEventListener('scroll', scrollHandler, true);
  6681. }
  6682. document.addEventListener('wheel', scrollHandler, true);
  6683. }
  6684.  
  6685. let hideTipsTimeout;
  6686. function showTips(content, href, time, wordColor, backColor) {
  6687. initView();
  6688. getBody(document).appendChild(tipsWords);
  6689. tipsWords.style.color = wordColor || 0xFFFFFF;
  6690. tipsWords.style.backgroundColor = backColor || 0x000;
  6691. let _time = 1500;
  6692. if (href) {
  6693. _time = 3500;
  6694. tipsWords.innerHTML = createHTML(`<a href='${href}'>${content}</a>`);
  6695. tipsWords.style.pointerEvents = 'all';
  6696. } else {
  6697. tipsWords.innerHTML = createHTML(content);
  6698. }
  6699. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  6700. setTimeout(() => {
  6701. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  6702. }, 0);
  6703. setTimeout(() => {
  6704. tipsWords.style.opacity = 0.8;
  6705. clearTimeout(hideTipsTimeout);
  6706. hideTipsTimeout = setTimeout(() => {
  6707. tipsWords.style.opacity = 0;
  6708. tipsWords.style.pointerEvents = '';
  6709. }, time || _time);
  6710. }, 1);
  6711. }
  6712.  
  6713. const loadmoreReg = /^\s*((点击)?加载更多|(點擊)?加載更多|load\s*more|もっと読み込む)[.…]*\s*$/i;
  6714. 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";
  6715. function getLoadMore(doc, loadmoreBtn) {
  6716. if (!loadmoreBtn || !getBody(doc).contains(loadmoreBtn) || /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  6717. if (!ruleParser.curSiteRule.singleUrl && !ruleParser.curSiteRule.loadMore) return null;
  6718. if (loadmoreBtn) return loadmoreBtn;
  6719. let btnSel = ruleParser.curSiteRule.loadMore || defaultLoadmoreSel;
  6720. if (btnSel) {
  6721. loadmoreBtn = getElement(btnSel, doc, null, true);
  6722. }
  6723. if (!loadmoreBtn) {
  6724. let buttons = doc.querySelectorAll("input,button,a,div[onclick]");
  6725. for (let i = 0; i < buttons.length; i++) {
  6726. let button = buttons[i];
  6727. if (!button.innerText || button.innerText.length > 20) continue;
  6728. if (button && loadmoreReg.test(button.innerText)) {
  6729. loadmoreBtn = button;
  6730. break;
  6731. }
  6732. }
  6733. }
  6734. if (loadmoreBtn && !ruleParser.curSiteRule.loadMore && loadmoreBtn.dataset.ajax !== "true") {
  6735. let href = loadmoreBtn.getAttribute("href");
  6736. if (href && href != "/" && !ruleParser.hrefIsJs(href)) {
  6737. loadmoreBtn = null;
  6738. }
  6739. }
  6740. if (loadmoreBtn && /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  6741. if (loadmoreBtn) debug(loadmoreBtn, 'Load more button');
  6742. return loadmoreBtn;
  6743. }
  6744.  
  6745. function scrollToPageBar(bar){
  6746. let yOffset = -20;
  6747. if (typeof ruleParser.curSiteRule.pageBarTop !== 'undefined') {
  6748. yOffset = -ruleParser.curSiteRule.pageBarTop;
  6749. }
  6750. const y = bar.getBoundingClientRect().top + window.pageYOffset + yOffset;
  6751. window.scrollTo({ top: y, behavior: 'smooth'});
  6752. }
  6753.  
  6754. const pageNumReg=/[&\/\?](p=|page[=\/_-]?)\d+|[_-]\d+\./;
  6755. function createPageBar(url) {
  6756. curPage++;
  6757. sideController.setup();
  6758. let posEle = null;
  6759. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  6760. let insert = ruleParser.getInsert();
  6761. if (!insert || !insert.parentNode) return;
  6762. if (forceState == 2) {
  6763. posEle = getBody(document);
  6764. posEle = posEle.children[posEle.children.length - 1];
  6765. } else {
  6766. posEle = insert;
  6767. }
  6768. while (posEle && !posEle.offsetParent) {
  6769. posEle = posEle.previousElementSibling || posEle.parentNode;
  6770. }
  6771. if (posEle) {
  6772. let actualBottom = getElementBottom(posEle);
  6773. bottomGap = scrollH - actualBottom + (window.innerHeight || document.documentElement.clientHeight) * (ruleParser.curSiteRule.rate || rulesData.rate || 1);
  6774. if (bottomGap < 100) bottomGap = 100;
  6775. } else {
  6776. bottomGap = 1000;
  6777. }
  6778. if (rulesData.opacity == 0 || ruleParser.curSiteRule.pageBar === 0) return null;
  6779. url = url.replace(/#p{.*/, "");
  6780. let example = (ruleParser.curSiteRule.insertPos == 2 || ruleParser.curSiteRule.insertPos == "in") ? insert.children[0] : (insert.parentNode.children[0] || insert);
  6781. while (example && (/^(SCRIPT|STYLE)$/i.test(example.nodeName) || example.className == "pagetual_pageBar")) {
  6782. example = example.nextElementSibling;
  6783. }
  6784. if (!example || !example.parentNode) example = insert;
  6785. if (example.nodeType != 1) {
  6786. example = example.previousElementSibling || example.parentNode;
  6787. if (!example || example.nodeType != 1) return;
  6788. }
  6789. let exampleStyle = _unsafeWindow.getComputedStyle(example);
  6790. let inTable, inLi;
  6791. if (forceState == 2) {
  6792. inTable = inLi = false;
  6793. } else {
  6794. inTable = /^(TABLE|TBODY)$/i.test(example.parentNode.nodeName) ||
  6795. /^(TR|TBODY)$/i.test(example.nodeName) ||
  6796. exampleStyle.display == "table-row" ||
  6797. (example.nextElementSibling && /^(TR|TBODY)$/i.test(example.nextElementSibling.nodeName));
  6798. inLi = /^LI$/i.test(example.nodeName) || (example.nextElementSibling && /^LI$/i.test(example.nextElementSibling.nodeName));
  6799. }
  6800. let pageBar = document.createElement(inTable ? "tr" : (inLi ? "li" : "div"));
  6801. let upSpan = document.createElement("span");
  6802. let downSpan = document.createElement("span");
  6803. let pageText = document.createElement("a");
  6804. let pageNum;
  6805. pageBar.className = isHideBar ? "pagetual_pageBar hide" : "pagetual_pageBar";
  6806. pageBar.id = "pagetual_pageBar" + curPage;
  6807. pageBar.setAttribute("translate", "no");
  6808. if (isPause) {
  6809. pageBar.classList.add("stop");
  6810. }
  6811. pageBar.style.cssText = pageBarStyle;
  6812. pageBar.title = i18n(isPause ? "enable" : "disable");
  6813. upSpan.innerHTML = createHTML(upSvg);
  6814. upSpan.children[0].style.cssText = upSvgCSS;
  6815. upSpan.title = i18n("toTop");
  6816. downSpan.innerHTML = createHTML(downSvg);
  6817. downSpan.children[0].style.cssText = downSvgCSS;
  6818. downSpan.title = i18n("toBottom");
  6819. upSpan.style.cssText = initStyle;
  6820. downSpan.style.cssText = initStyle;
  6821. pageText.href = url;
  6822. pageText.style.cssText = pageTextStyle;
  6823. pageText.title = i18n("current");
  6824. if (openInNewTab == 1) pageText.target = "_blank";
  6825. pageBar.appendChild(upSpan);
  6826. pageBar.appendChild(pageText);
  6827. if (rulesData.pageBarMenu) {
  6828. pageText.addEventListener("click", e => {
  6829. e.stopPropagation();
  6830. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  6831. e.preventDefault();
  6832. picker.start();
  6833. });
  6834. }
  6835. let touched = false;
  6836. let touchBodyHandler = e => {
  6837. touched = false;
  6838. getBody(document).removeEventListener('touchstart', touchBodyHandler, { passive: false, capture: false });
  6839. };
  6840. pageText.addEventListener("touchstart", e => {
  6841. if (touched) return;
  6842. touched = true;
  6843. pageText.style.pointerEvents = 'none';
  6844. setTimeout(() => {
  6845. pageText.style.pointerEvents = 'all';
  6846. }, 250);
  6847. getBody(document).addEventListener("touchstart", touchBodyHandler, { passive: false, capture: false });
  6848. }, { passive: false, capture: false });
  6849. if (ruleParser.nextTitle) {
  6850. pageText.innerHTML = createHTML(ruleParser.nextTitle + " ");
  6851. pageText.title = ruleParser.nextTitle;
  6852. }
  6853. if (ruleParser.curSiteRule.pageNum || pageNumReg.test(url)) {
  6854. pageText.innerHTML = createHTML(pageText.innerHTML + i18n("page"));
  6855. pageNum = document.createElement("span");
  6856. let num = ruleParser.getPageNumFromUrl(url, curPage);
  6857. pageNum.innerHTML = createHTML(num);
  6858. pageNum.className = "pagetual_pageNum";
  6859. pageNum.title = i18n("inputPageNum");
  6860. pageNum.style.cssText = pageTextStyle;
  6861. pageNum.style.cursor = "pointer";
  6862. pageNum.style.color = "";
  6863. pageNum.style.marginLeft = "5px";
  6864. pageNum.addEventListener("click", e => {
  6865. let pageInput = prompt(i18n("inputPageNum"), num || "1");
  6866. if (pageInput) {
  6867. let localPageBar = document.querySelector("#pagetual_pageBar" + pageInput);
  6868. if (localPageBar) {
  6869. scrollToPageBar(localPageBar);
  6870. } else {
  6871. let pageLink = ruleParser.getLinkByPage(url, pageInput);
  6872. if (pageLink) {
  6873. _GM_openInTab(pageLink, {active:true});
  6874. }
  6875. }
  6876. }
  6877. e.preventDefault();
  6878. e.stopPropagation();
  6879. });
  6880. pageBar.appendChild(pageNum);
  6881. } else {
  6882. pageText.innerHTML = createHTML(pageText.innerHTML + i18n("page") + curPage);
  6883. }
  6884. let preBtn = document.createElement("span");
  6885. preBtn.innerHTML = createHTML("∧");
  6886. preBtn.title = i18n("prevPage");
  6887. preBtn.className = "prevScreen";
  6888. 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; ";
  6889. let nextBtn = document.createElement("span");
  6890. nextBtn.innerHTML = createHTML("∨");
  6891. nextBtn.title = i18n("nextPage");
  6892. nextBtn.className = "nextScreen";
  6893. 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; ";
  6894. let localPage = curPage;
  6895. preBtn.addEventListener("click", e => {
  6896. e.stopPropagation();
  6897. e.preventDefault();
  6898. let prePageBar = document.querySelector("#pagetual_pageBar" + (localPage - 1));
  6899. if (prePageBar) {
  6900. scrollToPageBar(prePageBar);
  6901. } else {
  6902. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  6903. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  6904. }
  6905. });
  6906. nextBtn.addEventListener("click", e => {
  6907. e.stopPropagation();
  6908. e.preventDefault();
  6909. let nextPageBar = document.querySelector("#pagetual_pageBar" + (localPage + 1));
  6910. if (nextPageBar) {
  6911. scrollToPageBar(nextPageBar);
  6912. } else {
  6913. scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  6914. window.scrollTo({ top: scrollH || 9999999, behavior: 'smooth'});
  6915. }
  6916. });
  6917. if (!rulesData.hideBarArrow) {
  6918. pageText.insertBefore(preBtn, pageText.firstChild);
  6919. pageText.insertBefore(nextBtn, pageText.firstChild);
  6920. }
  6921. pageBar.appendChild(downSpan);
  6922. if (forceState == 2) {
  6923. pageBar.style.width = "99%";
  6924. } else {
  6925. let parentStyle = _unsafeWindow.getComputedStyle(example.parentNode);
  6926. let parentWidth = example.parentNode.offsetWidth || parseInt(parentStyle.width);
  6927. pageBar.style.width = parentWidth - parseInt(parentStyle.paddingLeft) - parseInt(parentStyle.paddingRight) - 10 + "px";
  6928. pageBar.style.margin = '10px 5px';
  6929. if (parentStyle.display == "grid" || parentStyle.display == "inline-grid") {
  6930. pageBar.style.gridColumn = "1/-1";
  6931. }
  6932. if (inTable) {
  6933. example = (/^(TR|TBODY)$/i.test(example.nodeName)) ? example : example.nextElementSibling || example;
  6934. if (/^TBODY$/i.test(example.nodeName)) example = example.querySelector("tr");
  6935. let nextTr = example;
  6936. while (nextTr && nextTr.children.length == 0) nextTr = nextTr.nextElementSibling;
  6937. if (nextTr) example = nextTr;
  6938. let tdNum = 0;
  6939. if (exampleStyle.display == "table-row") {
  6940. [].forEach.call(example.children, el => {
  6941. tdNum += el.colSpan || 1;
  6942. });
  6943. } else {
  6944. [].forEach.call(example.children, el => {
  6945. if (/^(TD|TH)$/i.test(el.nodeName)) {
  6946. tdNum += el.colSpan || 1;
  6947. }
  6948. });
  6949. }
  6950. pageBar.style.cssText = "";
  6951. pageBar.style.display = "table-row";
  6952. pageBar.style.backgroundColor = "unset";
  6953. pageBar.style.lineHeight = "20px";
  6954. pageBar.style.boxShadow = "";
  6955. let td = document.createElement("td");
  6956. td.colSpan = tdNum || 1;
  6957. let inTd = document.createElement("div");
  6958. inTd.style.cssText = pageBarStyle;
  6959. inTd.style.display = "";
  6960. inTd.className = pageBar.className;
  6961. pageBar.className = "";
  6962. inTd.appendChild(upSpan);
  6963. inTd.appendChild(pageText);
  6964. if (pageNum) inTd.appendChild(pageNum);
  6965. inTd.appendChild(downSpan);
  6966. td.appendChild(inTd);
  6967. pageBar.appendChild(td);
  6968. } else if (inLi) {
  6969. example = /^LI$/i.test(example.nodeName) ? example : example.nextElementSibling || example;
  6970. pageBar.style.opacity = 1;
  6971. pageBar.style.display = getComputedStyle(example).display;
  6972. pageBar.style.backgroundColor = "unset";
  6973. pageBar.style.lineHeight = "20px";
  6974. pageBar.style.boxShadow = "";
  6975. pageBar.style.border = "";
  6976. pageBar.style.maxWidth = "unset";
  6977. pageBar.style.flex = "auto";
  6978. let inTd = document.createElement("div");
  6979. inTd.style.cssText = pageBarStyle;
  6980. inTd.style.display = "";
  6981. inTd.style.margin = "0"
  6982. inTd.style.padding = "0 0";
  6983. inTd.style.textAlign = "center";
  6984. inTd.style.minWidth = "150px";
  6985. inTd.style.width = 'calc(100% - 20px)';
  6986. inTd.className = pageBar.className;
  6987. pageBar.className = "";
  6988. inTd.appendChild(upSpan);
  6989. inTd.appendChild(pageText);
  6990. if (pageNum) inTd.appendChild(pageNum);
  6991. inTd.appendChild(downSpan);
  6992. if (pageBar.style.display === 'table-row') {
  6993. let td = document.createElement("td");
  6994. td.colSpan = example.children.length;
  6995. td.style.width = '100%';
  6996. td.appendChild(inTd);
  6997. pageBar.appendChild(td);
  6998. } else {
  6999. inTd.style.width = '100%';
  7000. pageBar.appendChild(inTd);
  7001. }
  7002. }
  7003. }
  7004.  
  7005. upSpan.addEventListener("click", e => {
  7006. getBody(document).scrollTop = 0;
  7007. document.documentElement.scrollTop = 0;
  7008. e.preventDefault();
  7009. e.stopPropagation();
  7010. });
  7011. downSpan.addEventListener("click", e => {
  7012. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  7013. changeStop(true);
  7014. }
  7015. pageBar.title = i18n(isPause ? "enable" : "disable");
  7016. scrollH=Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7017. getBody(document).scrollTop = scrollH || 9999999;
  7018. document.documentElement.scrollTop = scrollH || 9999999;
  7019. e.preventDefault();
  7020. e.stopPropagation();
  7021. });
  7022. pageBar.addEventListener("click", e => {
  7023. changeStop(!isPause);
  7024. pageBar.title = i18n(isPause ? "enable" : "disable");
  7025. });
  7026. ruleParser.insertElement(pageBar);
  7027. ruleParser.runPageBar(pageBar);
  7028.  
  7029. return pageBar;
  7030. }
  7031.  
  7032. async function waitForElement(sel, doc) {
  7033. if (!sel) return null;
  7034. return new Promise((resolve) => {
  7035. let checkInv = setInterval(() => {
  7036. let result = getElement(sel, doc, null, true);
  7037. if (result) {
  7038. clearInterval(checkInv);
  7039. resolve(result);
  7040. }
  7041. }, 100);
  7042. });
  7043. }
  7044.  
  7045. async function clickAction(sel, doc) {
  7046. let btn = await waitForElement(sel, doc);
  7047. emuClick(btn);
  7048. }
  7049.  
  7050. async function enterAction(sel, doc) {
  7051. let btn = await waitForElement(sel, doc);
  7052. let eventParam = { key: "Enter", keyCode: 13, bubbles: true };
  7053. let event = new KeyboardEvent('keydown', eventParam);
  7054. btn.dispatchEvent(event);
  7055. event = new KeyboardEvent('keyup', eventParam);
  7056. btn.dispatchEvent(event);
  7057. event = new KeyboardEvent('keypress', eventParam);
  7058. btn.dispatchEvent(event);
  7059. }
  7060.  
  7061. async function inputAction(sel, v, doc) {
  7062. let input = await waitForElement(sel, doc);
  7063. let event = new Event('focus', { bubbles: true });
  7064. input.dispatchEvent(event);
  7065. let lastValue = input.value;
  7066. if (input.nodeName.toUpperCase() == "INPUT") {
  7067. var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
  7068. nativeInputValueSetter.call(input, v);
  7069. } else if (input.nodeName.toUpperCase() == "TEXTAREA") {
  7070. var nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
  7071. nativeTextareaValueSetter.call(input, v);
  7072. } else {
  7073. input.innerHTML = createHTML(v);
  7074. }
  7075. event = new Event('input', { bubbles: true });
  7076. let tracker = input._valueTracker;
  7077. if (tracker) {
  7078. tracker.setValue(lastValue);
  7079. }
  7080. input.dispatchEvent(event);
  7081. event = new Event('change', { bubbles: true });
  7082. input.dispatchEvent(event);
  7083. debug(input, `input ${sel}`);
  7084. }
  7085.  
  7086. function emuClick(btn) {
  7087. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  7088. let orgHref = btn.getAttribute('href');
  7089. if (orgHref && orgHref.replace(location.origin + location.pathname, "").indexOf("#") === 0) {
  7090. let hashAction = e => {
  7091. e.preventDefault();
  7092. getBody(document).scrollTop = curScroll;
  7093. document.documentElement.scrollTop = curScroll;
  7094. btn.removeEventListener('click', hashAction, false);
  7095. };
  7096. btn.addEventListener('click', hashAction, false);
  7097. }
  7098. if (!PointerEvent) return btn.click();
  7099. let eventParam = {
  7100. isTrusted: true,
  7101. altKey: false,
  7102. azimuthAngle: 0,
  7103. bubbles: true,
  7104. button: 0,
  7105. buttons: 0,
  7106. clientX: 1,
  7107. clientY: 1,
  7108. cancelBubble: false,
  7109. cancelable: true,
  7110. composed: true,
  7111. ctrlKey: false,
  7112. defaultPrevented: false,
  7113. detail: 1,
  7114. eventPhase: 2,
  7115. fromElement: null,
  7116. height: 1,
  7117. isPrimary: false,
  7118. metaKey: false,
  7119. pointerId: 1,
  7120. pointerType: "mouse",
  7121. pressure: 0,
  7122. relatedTarget: null,
  7123. returnValue: true,
  7124. shiftKey: false,
  7125. toElement: null,
  7126. twist: 0,
  7127. which: 1
  7128. };
  7129. let mouseEvent = new PointerEvent("mousedown", eventParam);
  7130. btn.dispatchEvent(mouseEvent);
  7131. mouseEvent = new PointerEvent("mouseup", eventParam);
  7132. btn.dispatchEvent(mouseEvent);
  7133. let dispatchTouchEvent = (ele, type) => {
  7134. let touchEvent;
  7135. try {
  7136. touchEvent = document.createEvent('TouchEvent')
  7137. touchEvent.initTouchEvent(type, true, true)
  7138. } catch (err) {
  7139. try {
  7140. touchEvent = document.createEvent('UIEvent')
  7141. touchEvent.initUIEvent(type, true, true)
  7142. } catch (err) {
  7143. touchEvent = document.createEvent('Event')
  7144. touchEvent.initEvent(type, true, true)
  7145. }
  7146. }
  7147. if (touchEvent) {
  7148. try {
  7149. touchEvent.targetTouches = [{
  7150. pageX: 1,
  7151. pageY: 1,
  7152. clientX: 1,
  7153. clientY: 1,
  7154. target: btn
  7155. }];
  7156. touchEvent.touches = [{
  7157. pageX: 1,
  7158. pageY: 1,
  7159. clientX: 1,
  7160. clientY: 1,
  7161. target: btn
  7162. }];
  7163. touchEvent.changedTouches = [{
  7164. pageX: 1,
  7165. pageY: 1,
  7166. clientX: 1,
  7167. clientY: 1,
  7168. target: btn
  7169. }];
  7170. } catch (err) {}
  7171. ele.dispatchEvent(touchEvent);
  7172. }
  7173. }
  7174. dispatchTouchEvent(btn, "touchstart");
  7175. dispatchTouchEvent(btn, "touchend");
  7176.  
  7177. btn.click();
  7178. }
  7179.  
  7180. var failFromIframe = 0;
  7181. var inCors = false;
  7182. var checkRemoveIntv;
  7183. function requestFromIframe(url, callback){
  7184. if (location.protocol === 'https:' && !/^https:/.test(url)) {
  7185. ruleParser.noValidContent(url);
  7186. }
  7187. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  7188. let iframe = document.createElement('iframe');
  7189. iframe.name = 'pagetual-iframe';
  7190. iframe.width = '100%';
  7191. iframe.height = '1000';
  7192. iframe.frameBorder = '0';
  7193. if (ruleParser.curSiteRule.sandbox != false) {
  7194. iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  7195. }
  7196. 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;';
  7197. let waitTime = 100, checkEval;
  7198. ruleParser.runWait((_checkEval, _waitTime) => {
  7199. if (_checkEval) {
  7200. checkEval = _checkEval;
  7201. }
  7202. if (_waitTime) {
  7203. waitTime = _waitTime;
  7204. }
  7205. });
  7206. if (checkRemoveIntv) clearInterval(checkRemoveIntv);
  7207. checkRemoveIntv = setInterval(() => {
  7208. if (!iframe || !getBody(document).contains(iframe)) {
  7209. clearInterval(checkRemoveIntv);
  7210. loadPageOver();
  7211. }
  7212. }, 500);
  7213. let loadedHandler = e => {
  7214. if (e.data != 'pagetual-iframe:DOMLoaded' && e.type != 'load') return;
  7215. clearInterval(checkRemoveIntv);
  7216. window.removeEventListener('message', loadedHandler, false);
  7217. iframe.removeEventListener('load', loadedHandler, false);
  7218. let tryTimes = 0;
  7219. function checkIframe() {
  7220. if (urlChanged || isPause) {
  7221. return callback(false, false);
  7222. }
  7223. try {
  7224. let doc = iframe.contentDocument || iframe.contentWindow.document;
  7225. let base = doc.querySelector("base");
  7226. ruleParser.basePath = base ? base.href : url;
  7227. let eles = ruleParser.getPageElement(doc, iframe.contentWindow, tryTimes < 25);
  7228. if (checkEval && !checkEval(doc)) {
  7229. setTimeout(() => {
  7230. checkIframe();
  7231. }, waitTime);
  7232. return;
  7233. } else if (eles && eles.length > 0) {
  7234. callback(doc, eles);
  7235. } else if (tryTimes++ < 100) {
  7236. setTimeout(() => {
  7237. checkIframe();
  7238. }, waitTime);
  7239. return;
  7240. } else {
  7241. if (failFromIframe++ > 2) {
  7242. failFromIframe = 0;
  7243. debug("Stop as failFromIframe");
  7244. isPause = true;
  7245. callback(false, false);
  7246. } else {
  7247. ruleParser.noValidContent(url);
  7248. callback(false, false);
  7249. }
  7250. }
  7251. } catch(e) {
  7252. inCors = true;
  7253. if (forceState === 3) {
  7254. debug("Stop as cors");
  7255. isPause = true;
  7256. }
  7257. if (!ruleParser.curSiteRule.pageElement) {
  7258. ruleParser.curSiteRule.pageElement = allOfBody;
  7259. ruleParser.getInsert(true);
  7260. }
  7261. ruleParser.curSiteRule.action = 0;
  7262. ruleParser.nextLinkHref = url;
  7263. callback(false, false);
  7264. nextPage();
  7265. }
  7266. if (iframe && iframe.parentNode) iframe.parentNode.removeChild(iframe);
  7267. }
  7268. setTimeout(() => {
  7269. checkIframe();
  7270. }, waitTime);
  7271. };
  7272. let code = ruleParser.curSiteRule.iframeInit;
  7273. if (code) {
  7274. let checkReady = setInterval(() => {
  7275. let doc;
  7276. try {
  7277. doc = iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document);
  7278. } catch(e) {
  7279. clearInterval(checkReady);
  7280. return;
  7281. }
  7282. if (doc) {
  7283. try {
  7284. Function('win', 'iframe', '"use strict";' + code)(iframe.contentWindow, iframe);
  7285. clearInterval(checkReady);
  7286. } catch(e) {
  7287. debug(e);
  7288. }
  7289. }
  7290. }, 50);
  7291. }
  7292. window.addEventListener('message', loadedHandler, false);
  7293. iframe.addEventListener('load', loadedHandler, false);
  7294. iframe.src = url;
  7295. try {
  7296. getBody(document).appendChild(iframe);
  7297. } catch (e) {
  7298. return callback(false, false);
  7299. }
  7300. }
  7301.  
  7302. var emuIframe, lastActiveUrl, orgContent, meetCors = false;
  7303. function emuPage(callback) {
  7304. let orgPage = null, preContent = null, iframeDoc, checkTimes = 0, loadmoreBtn, pageEle, nextLink, loadmoreEnd = false, waitTimes = 80, changed = false;
  7305. function returnFalse(log) {
  7306. if (curPage > 1 && rulesData.lastPageTips) showTips(i18n("lastPage"));
  7307. debug(log);
  7308. isPause = true;
  7309. callback(false, false);
  7310. if (emuIframe && emuIframe.parentNode) {
  7311. emuIframe.parentNode.removeChild(emuIframe);
  7312. sideController.remove();
  7313. emuIframe = null;
  7314. }
  7315. }
  7316. async function checkPage() {
  7317. if (isPause) return loadPageOver();
  7318. try {
  7319. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  7320. } catch(e) {
  7321. returnFalse("Stop as cors");
  7322. return;
  7323. }
  7324.  
  7325. let waitTime = 200, checkEval;
  7326. ruleParser.runWait((_checkEval, _waitTime) => {
  7327. if (_checkEval) {
  7328. checkEval = _checkEval;
  7329. }
  7330. if (_waitTime) {
  7331. waitTime = _waitTime;
  7332. }
  7333. });
  7334.  
  7335. if (!orgPage) {
  7336. if (!loadmoreEnd) {
  7337. loadmoreBtn = getLoadMore(iframeDoc);
  7338. if (loadmoreBtn && isVisible(loadmoreBtn, emuIframe.contentWindow)) {
  7339. emuClick(loadmoreBtn);
  7340. let intv = setInterval(() => {
  7341. loadmoreBtn = getLoadMore(iframeDoc);
  7342. if (!loadmoreBtn || !getBody(document).contains(loadmoreBtn) || !isVisible(loadmoreBtn, emuIframe.contentWindow)) {
  7343. clearInterval(intv);
  7344. loadmoreEnd = true;
  7345. setTimeout(() => {
  7346. checkPage();
  7347. }, 500);
  7348. } else if (isInViewPort(loadmoreBtn)) {
  7349. emuClick(loadmoreBtn);
  7350. }
  7351. }, 200);
  7352. return;
  7353. } else {
  7354. loadmoreEnd = true;
  7355. }
  7356. }
  7357. if (checkEval && !checkEval(iframeDoc)) {
  7358. waitTimes = 50;
  7359. setTimeout(() => {
  7360. checkPage();
  7361. }, waitTime);
  7362. return;
  7363. } else {
  7364. if (!nextLink || !nextLink.offsetParent) nextLink = await ruleParser.getNextLink(iframeDoc, true);
  7365. if (nextLink) pageEle = ruleParser.getPageElement(iframeDoc, emuIframe.contentWindow, true);
  7366. if (!pageEle || pageEle.length == 0 || !nextLink) {
  7367. if (waitTimes-- > 0) {
  7368. setTimeout(() => {
  7369. checkPage();
  7370. }, waitTime);
  7371. return;
  7372. }
  7373. }
  7374. }
  7375. if (!pageEle || pageEle.length == 0) {
  7376. returnFalse("Stop as no page when emu");
  7377. return;
  7378. }
  7379. if (/^UL$/i.test(pageEle[0].nodeName)) pageEle = pageEle[0].children;
  7380. pageEle = pageEle[parseInt((pageEle.length - 1) / 2)];
  7381. while(pageEle && ((pageEle.scrollHeight && pageEle.scrollHeight < 50) || !pageEle.offsetParent || (!/^IMG$/i.test(pageEle.nodeName) && !pageEle.innerHTML.trim()))) {
  7382. if (pageEle.nextElementSibling) pageEle = pageEle.nextElementSibling;
  7383. else break;
  7384. }
  7385. if (ruleParser.curSiteRule.singleUrl && orgContent != pageEle.innerHTML) {
  7386. orgContent = pageEle.innerHTML;
  7387. if (waitTimes-- > 0) {
  7388. setTimeout(() => {
  7389. checkPage();
  7390. }, waitTime);
  7391. return;
  7392. }
  7393. }
  7394. orgPage = pageEle;
  7395. if (nextLink) {
  7396. if (/^IMG$/i.test(orgPage.nodeName)) {
  7397. if (!ruleParser.curSiteRule.lazyImgSrc) ruleParser.curSiteRule.lazyImgSrc = "0";
  7398. if (orgPage.src) {
  7399. orgContent = orgPage.src;
  7400. } else {
  7401. setTimeout(() => {
  7402. checkPage();
  7403. }, 500);
  7404. return;
  7405. }
  7406. } else {
  7407. orgContent = orgPage.innerHTML;
  7408. }
  7409. preContent = orgContent;
  7410. if (!isVisible(nextLink, emuIframe.contentWindow)) {
  7411. returnFalse("Stop as next hide when emu");
  7412. } else {
  7413. emuClick(nextLink);
  7414. setTimeout(() => {
  7415. checkPage();
  7416. }, 500);
  7417. }
  7418. } else {
  7419. returnFalse("Stop as no next when emu");
  7420. }
  7421. return;
  7422. }
  7423. if (!ruleParser.checkStopSign(nextLink, iframeDoc)) {
  7424. return returnFalse("Stop as stopSign");;
  7425. }
  7426. if (checkTimes++ > 200) {
  7427. returnFalse("Stop as timeout when emu");
  7428. return;
  7429. }
  7430. let eles = ruleParser.getPageElement(iframeDoc, emuIframe.contentWindow, true), checkItem;
  7431. if (eles && eles.length > 0) {
  7432. checkItem = eles;
  7433. if (/^UL$/i.test(eles[0].nodeName)) checkItem = eles[0].children;
  7434. checkItem = checkItem[parseInt((checkItem.length - 1) / 2)];
  7435. while(checkItem && ((checkItem.scrollHeight && checkItem.scrollHeight < 50) || !checkItem.offsetParent || (!/^IMG$/i.test(checkItem.nodeName) && !checkItem.innerHTML.trim()))) {
  7436. if (checkItem.nextElementSibling) checkItem = checkItem.nextElementSibling;
  7437. else break;
  7438. }
  7439. }
  7440. if (!checkItem || (checkEval && !checkEval(iframeDoc))) {
  7441. if (checkEval) checkTimes = 0;
  7442. setTimeout(() => {
  7443. checkPage();
  7444. }, waitTime);
  7445. } else {
  7446. let checkInner;
  7447. if (/^IMG$/i.test(checkItem.nodeName)) {
  7448. if (checkItem.src) {
  7449. checkInner = checkItem.src;
  7450. } else {
  7451. setTimeout(() => {
  7452. checkPage();
  7453. }, waitTime);
  7454. return;
  7455. }
  7456. } else {
  7457. checkInner = checkItem.innerHTML;
  7458. }
  7459. if (orgPage != checkItem || checkInner != preContent) {
  7460. changed = true;
  7461. orgPage = checkItem;
  7462. preContent = checkInner;
  7463. setTimeout(() => {
  7464. checkPage();
  7465. }, waitTime);
  7466. } else if (changed) {
  7467. checkTimes = 0;
  7468. if (orgContent == preContent && (ruleParser.curSiteRule.singleUrl || ruleParser.curSiteRule.stopSame)) {
  7469. returnFalse("Stop as same content");
  7470. } else {
  7471. orgContent = preContent;
  7472. callback(iframeDoc, eles);
  7473. }
  7474. } else {
  7475. if (checkTimes % 10 === 5) {
  7476. if (!nextLink || !nextLink.offsetParent) {
  7477. nextLink = await ruleParser.getNextLink(iframeDoc, true);
  7478. }
  7479. if (nextLink) {
  7480. emuClick(nextLink);
  7481. }
  7482. }
  7483. setTimeout(() => {
  7484. checkPage();
  7485. }, waitTime);
  7486. }
  7487. }
  7488. }
  7489. if (!emuIframe) {
  7490. let loaded = false;
  7491. emuIframe = document.createElement('iframe');
  7492. emuIframe.name = 'pagetual-iframe';
  7493. let notSetSandbox = typeof ruleParser.curSiteRule.sandbox == 'undefined';
  7494. if (notSetSandbox || ruleParser.curSiteRule.sandbox == true) {
  7495. emuIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  7496. } else if (ruleParser.curSiteRule.sandbox) {
  7497. emuIframe.sandbox = ruleParser.curSiteRule.sandbox;
  7498. }
  7499. emuIframe.width = '100%';
  7500. emuIframe.height = '100%';
  7501. emuIframe.frameBorder = '0';
  7502. 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;';
  7503. emuIframe.addEventListener("load", e => {
  7504. setTimeout(() => {
  7505. try {
  7506. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  7507. } catch(e) {
  7508. if (e.message && e.message.indexOf("cross-origin") != -1 && notSetSandbox && emuIframe.hasAttribute("sandbox")) {
  7509. emuIframe.removeAttribute("sandbox");
  7510. meetCors = true;
  7511. callback(false, false);
  7512. } else {
  7513. returnFalse("Stop as cors");
  7514. }
  7515. return;
  7516. }
  7517. meetCors = false;
  7518. let code = ruleParser.curSiteRule.init;
  7519. if (code) {
  7520. try {
  7521. 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)});
  7522. } catch(e) {
  7523. debug(e);
  7524. }
  7525. }
  7526. if (loaded) return;
  7527. loaded = true;
  7528. checkPage();
  7529. }, 500);
  7530. });
  7531. let code = ruleParser.curSiteRule.iframeInit;
  7532. if (code) {
  7533. let checkReady = setInterval(() => {
  7534. try {
  7535. iframeDoc = emuIframe.contentDocument || (emuIframe.contentWindow && emuIframe.contentWindow.document);
  7536. } catch(e) {
  7537. clearInterval(checkReady);
  7538. return;
  7539. }
  7540. if (iframeDoc) {
  7541. try {
  7542. Function('win', 'iframe', '"use strict";' + code)(emuIframe.contentWindow, emuIframe);
  7543. clearInterval(checkReady);
  7544. } catch(e) {
  7545. debug(e);
  7546. }
  7547. }
  7548. }, 50);
  7549. }
  7550. if (!lastActiveUrl) lastActiveUrl = location.href;
  7551. emuIframe.src = lastActiveUrl;
  7552. getBody(document).appendChild(emuIframe);
  7553. } else {
  7554. if (emuIframe.src != lastActiveUrl || meetCors) {
  7555. emuIframe.src = lastActiveUrl;
  7556. return;
  7557. }
  7558. checkPage();
  7559. }
  7560. }
  7561.  
  7562. var scrollToResizeInited = false;
  7563. var resizePool = [];
  7564. var scrollingToResize = false;
  7565.  
  7566. function isTouchViewPort(element) {
  7567. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  7568. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  7569. const {
  7570. top,
  7571. right,
  7572. bottom,
  7573. left,
  7574. } = element.getBoundingClientRect();
  7575.  
  7576. return (
  7577. top < viewHeight &&
  7578. left < viewWidth &&
  7579. right > 0 &&
  7580. bottom > 0
  7581. );
  7582. }
  7583.  
  7584. function resizeIframe(iframe, frameDoc, pageEle) {
  7585. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  7586. if (ruleParser.curSiteRule.singleUrl || forceState === 2) {
  7587. let height = (getBody(frameDoc).scrollHeight || getBody(frameDoc).offsetHeight || 500);
  7588. if (!iframe.style.height || height - parseInt(iframe.style.height) > window.innerHeight) {
  7589. iframe.style.height = height + "px";
  7590. iframe.style.minHeight = iframe.style.height;
  7591. }
  7592. iframe.style.width = "100%";
  7593. frameDoc.documentElement.scrollTop = 0;
  7594. frameDoc.documentElement.scrollLeft = 0;
  7595. } else {
  7596. if (pageEle) {
  7597. let fitWidth = ruleParser.curSiteRule.fitWidth !== false;
  7598. let targetElement = pageEle[0];
  7599. if (!targetElement) return;
  7600. if (pageEle.length > 1) {
  7601. targetElement = targetElement.parentNode;
  7602. }
  7603. let scrollHeight = targetElement.scrollHeight || targetElement.offsetHeight || 500;
  7604. iframe.style.height = scrollHeight + "px";
  7605. let scrollTop = 0, scrollLeft = 0;
  7606. getBody(frameDoc).scrollTop = 0;
  7607. getBody(frameDoc).scrollLeft = 0;
  7608. while (targetElement && targetElement.offsetParent) {
  7609. targetElement.offsetParent.scrollTop = targetElement.offsetTop;
  7610. if (targetElement.offsetParent.scrollTop == 0) {
  7611. scrollTop += targetElement.offsetTop;
  7612. }
  7613. if (fitWidth) {
  7614. targetElement.offsetParent.scrollLeft = targetElement.offsetLeft;
  7615. if (targetElement.offsetParent.scrollLeft == 0) {
  7616. scrollLeft += targetElement.offsetLeft;
  7617. }
  7618. }
  7619. targetElement = targetElement.offsetParent;
  7620. }
  7621. frameDoc.documentElement.scrollTop = scrollTop;
  7622. frameDoc.documentElement.scrollLeft = scrollLeft;
  7623. if (frameDoc.documentElement.scrollTop == 0 && frameDoc.documentElement.scrollLeft == 0) {
  7624. getBody(frameDoc).scrollTop += scrollTop;
  7625. getBody(frameDoc).scrollLeft += scrollLeft;
  7626. }
  7627. if (!fitWidth && iframe.style.marginLeft == '0px') {
  7628. iframe.style.width = "100vw";
  7629. iframe.style.maxWidth = "100vw";
  7630. iframe.style.minWidth = "100vw";
  7631. var cWidth = document.body.clientWidth || document.documentElement.clientWidth;
  7632. var iWidth = window.innerWidth;
  7633. iframe.style.marginLeft = -iframe.getBoundingClientRect().left - (iWidth - cWidth) / 2 + "px";
  7634. }
  7635. }
  7636. }
  7637. getBody(document).scrollTop = curScroll;
  7638. document.documentElement.scrollTop = curScroll;
  7639. }
  7640.  
  7641. function scrollToResize(e) {
  7642. if (scrollingToResize) return;
  7643. else {
  7644. scrollingToResize = true;
  7645. let resizeHandler = () => {
  7646. let touched = 0;
  7647. for (let i = 0; i < resizePool.length; i++) {
  7648. let resizeArr = resizePool[i];
  7649. let iframe = resizeArr[1]();
  7650. if (isTouchViewPort(iframe)) {
  7651. touched++;
  7652. let pageEle = resizeArr[0]();
  7653. let frameDoc = resizeArr[2]();
  7654. resizeIframe(iframe, frameDoc, pageEle);
  7655. } else if (touched) {
  7656. if (touched == 1) {
  7657. let pageEle = resizeArr[0]();
  7658. let frameDoc = resizeArr[2]();
  7659. resizeIframe(iframe, frameDoc, pageEle);
  7660. }
  7661. break;
  7662. } else if (!iframe.parentNode) {
  7663. resizePool.splice(i, 1);
  7664. break;
  7665. }
  7666. }
  7667. };
  7668. setTimeout(() => {
  7669. scrollingToResize = false;
  7670. }, 300);
  7671. resizeHandler();
  7672. }
  7673. }
  7674.  
  7675. function forceIframe(url, callback) {
  7676. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  7677. let curIframe = document.createElement('iframe'), iframeDoc, pageElement = null, isloaded = false, inAction = true;
  7678. let loadedHandler = () => {
  7679. let getPageEle = () => {
  7680. if (ruleParser.curSiteRule.singleUrl) {
  7681. return null;
  7682. } else {
  7683. if (!pageElement || pageElement.length === 0 || !pageElement[0].offsetParent) {
  7684. pageElement = ruleParser.getPageElement(iframeDoc, curIframe.contentWindow);
  7685. }
  7686. return pageElement;
  7687. }
  7688. };
  7689. resizeIframe(curIframe, iframeDoc, getPageEle());
  7690. if (isloaded) return;
  7691. isloaded = true;
  7692. let getIframe = () => {
  7693. return curIframe;
  7694. };
  7695. let getFrameDoc = () => {
  7696. return iframeDoc;
  7697. };
  7698. ruleParser.insertPage(iframeDoc, [], url, ele => {
  7699. callback(curIframe);
  7700. inAction = false;
  7701. }, true);
  7702. resizePool.push([getPageEle, getIframe, getFrameDoc]);
  7703. };
  7704. let checkIframeTimer = setInterval(() => {
  7705. if (!curIframe.parentNode) {
  7706. clearInterval(checkIframeTimer);
  7707. return isloaded || callback(false);
  7708. }
  7709. }, 500);
  7710. let code = ruleParser.curSiteRule.iframeInit;
  7711. if (code) {
  7712. let checkReady = setInterval(() => {
  7713. try {
  7714. iframeDoc = curIframe.contentDocument || (curIframe.contentWindow && curIframe.contentWindow.document);
  7715. } catch(e) {
  7716. clearInterval(checkReady);
  7717. return;
  7718. }
  7719. if (iframeDoc) {
  7720. try {
  7721. Function('win', 'iframe', '"use strict";' + code)(curIframe.contentWindow, curIframe);
  7722. clearInterval(checkReady);
  7723. } catch(e) {
  7724. debug(e);
  7725. }
  7726. }
  7727. }, 50);
  7728. }
  7729. curIframe.name = 'pagetual-iframe';
  7730. curIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  7731. curIframe.frameBorder = '0';
  7732. curIframe.scrolling = "no";
  7733. 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;';
  7734. curIframe.addEventListener("load", e => {
  7735. clearInterval(checkIframeTimer);
  7736. if (isPause) return callback(false);
  7737. try {
  7738. iframeDoc = curIframe.contentDocument || curIframe.contentWindow.document;
  7739. } catch(e) {
  7740. debug("Stop as cors");
  7741. isPause = true;
  7742. callback(false);
  7743. return;
  7744. }
  7745. let css = ruleParser.curSiteRule.css || rulesData.customCss;
  7746. if (css) {
  7747. let cssArr = css.split("inIframe:");
  7748. if (cssArr && cssArr.length > 1) {
  7749. let styleEle = iframeDoc.createElement("style");
  7750. styleEle.innerHTML = cssArr[1];
  7751. iframeDoc.head.appendChild(styleEle);
  7752. }
  7753. }
  7754. loadedHandler();
  7755. let code = ruleParser.curSiteRule.init;
  7756. if (code) {
  7757. try {
  7758. 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)});
  7759. } catch(e) {
  7760. debug(e);
  7761. }
  7762. }
  7763. iframeDoc.addEventListener('wheel', e => {
  7764. document.dispatchEvent(new Event('wheel'));
  7765. }, true);
  7766. });
  7767. let checkTimes = 0, findPageEle = false;
  7768. let forceRefresh = e => {
  7769. if (inAction || !iframeDoc) return;
  7770. inAction = true;
  7771. let foundNext = () => {
  7772. document.removeEventListener("scroll", forceRefresh);
  7773. }
  7774. setTimeout(async () => {
  7775. inAction = false;
  7776. if (!ruleParser.nextLinkHref && !isPause) {
  7777. checkTimes++;
  7778. await ruleParser.getNextLink(iframeDoc, true);
  7779. if (ruleParser.nextLinkHref) {
  7780. foundNext();
  7781. if (isLoading) isLoading = false;
  7782. } else if (checkTimes >= 10) {
  7783. foundNext();
  7784. } else if (checkTimes >= 3 && !findPageEle) {
  7785. if (!pageElement) pageElement = ruleParser.getPageElement(iframeDoc, curIframe.contentWindow);
  7786. if (!pageElement) {
  7787. inAction = true;
  7788. curIframe.contentWindow.location.reload();
  7789. } else {
  7790. findPageEle = true;
  7791. }
  7792. }
  7793. } else {
  7794. foundNext();
  7795. }
  7796. }, 100);
  7797. };
  7798. document.addEventListener("scroll", forceRefresh);
  7799. curIframe.src = url;
  7800. let insert = ruleParser.getInsert();
  7801. let body = getBody(document);
  7802. let curScroll = body.scrollTop || document.documentElement.scrollTop;
  7803. if (forceState == 2) {
  7804. document.documentElement.appendChild(loadingDiv);
  7805. body.appendChild(curIframe);
  7806. let bodyStyle = getComputedStyle(body);
  7807. if (bodyStyle.display == "flex" || bodyStyle.display == "inline-flex") {
  7808. body.style.flexDirection = "column";
  7809. }
  7810. } else {
  7811. ruleParser.insertElement(curIframe);
  7812. }
  7813. body.scrollTop = curScroll;
  7814. document.documentElement.scrollTop = curScroll;
  7815.  
  7816. if (!scrollToResizeInited) {
  7817. scrollToResizeInited = true;
  7818. document.addEventListener("scroll", scrollToResize);
  7819. }
  7820. return curIframe;
  7821. }
  7822.  
  7823. function loadPageOver() {
  7824. isLoading = false;
  7825. stopScroll = true;
  7826. setTimeout(() => {stopScroll = false}, 300);
  7827. if (loadingDiv.parentNode) {
  7828. loadingDiv.parentNode.removeChild(loadingDiv);
  7829. }
  7830. let rate = (ruleParser.curSiteRule.rate || rulesData.rate || 1);
  7831. if (rate != 1 && !clickMode) {
  7832. setTimeout(() => {
  7833. if (distToBottom() < bottomGap) {
  7834. nextPage();
  7835. }
  7836. }, 1);
  7837. }
  7838. }
  7839.  
  7840. function checkAutoLoadNum() {
  7841. if (autoLoadNum >= 0) {
  7842. if (autoLoadNum != 0 && --autoLoadNum == 0) {
  7843. autoLoadNum = -1;
  7844. } else {
  7845. setTimeout(() => nextPage(), 1);
  7846. }
  7847. }
  7848. }
  7849.  
  7850. var tryTimes = 0, showedLastPageTips = false;
  7851. async function nextPage() {
  7852. if (typeof ruleParser.curSiteRule.manualMode == 'undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode) return;
  7853. if (clickMode) return;
  7854. if (isPause || isLoading || forceState == 1) return;
  7855. if (ruleParser.curSiteRule.delay) {
  7856. try {
  7857. let checkDelay = ((typeof ruleParser.curSiteRule.delay == 'function') ? ruleParser.curSiteRule.delay : Function('"use strict";' + ruleParser.curSiteRule.delay))();
  7858. if (!checkDelay) return;
  7859. } catch(e) {
  7860. debug(e);
  7861. }
  7862. }
  7863. let nextLink = ruleParser.nextLinkHref;
  7864. if (!nextLink) {
  7865. isLoading = true;
  7866. if (curPage == 1) {
  7867. await ruleParser.getNextLink(document, true);
  7868. nextLink = ruleParser.nextLinkHref;
  7869. }
  7870. if (!nextLink) {
  7871. if (curPage == 1 && (ruleParser.curSiteRule.pinUrl || tryTimes++ <= 3)) {
  7872. setTimeout(() => {isLoading = false}, 500);
  7873. } else if (curPage > 1 && rulesData.lastPageTips && !showedLastPageTips) {
  7874. showTips(i18n("lastPage"));
  7875. showedLastPageTips = true;
  7876. }
  7877. return;
  7878. }
  7879. isLoading = false;
  7880. }
  7881. showedLastPageTips = false;
  7882. let pvGallery = document.querySelector("span.pv-gallery-container");
  7883. if (pvGallery && pvGallery.style.display != "none") return;
  7884. let insert = ruleParser.getInsert();
  7885. if (insert) {
  7886. if (curPage == 1) initView();
  7887. /*if (curPage == 1) {
  7888. window.postMessage({
  7889. command: 'pagetual.insert'
  7890. }, '*');
  7891. }*/
  7892. let isJs = ruleParser.curSiteRule.action == 3 || ruleParser.hrefIsJs(nextLink);
  7893. if (!isJs) {
  7894. emuIframe = null;
  7895. lastActiveUrl = nextLink;
  7896. if (location.protocol == "https:" && /^http:/.test(nextLink)) {
  7897. nextLink = nextLink.replace(/^http/, "https");
  7898. }
  7899. }
  7900. isLoading = true;
  7901. if (curPage != 1 || !isJs || !ruleParser.curSiteRule.singleUrl) {
  7902. ruleParser.beginLoading(loadingDiv);
  7903. }
  7904. let sleep = ruleParser.curSiteRule.sleep || 0;
  7905. setTimeout(() => {
  7906. if (ruleParser.curSiteRule.pageElementByJs) {
  7907. var over = eles => {
  7908. if (urlChanged || isPause) {
  7909. loadPageOver();
  7910. return;
  7911. }
  7912. if (eles) {
  7913. ruleParser.insertPage(document, eles, nextLink, () => {
  7914. createPageBar(nextLink);
  7915. checkAutoLoadNum();
  7916. }, true);
  7917. } else {
  7918. debug("Stop as no page when get by js");
  7919. isPause = true;
  7920. loadPageOver();
  7921. }
  7922. };
  7923. try {
  7924. ((typeof ruleParser.curSiteRule.pageElementByJs == 'function') ? ruleParser.curSiteRule.pageElementByJs : Function("over", "pageNum",'"use strict";' + ruleParser.curSiteRule.pageElementByJs))(over, curPage);
  7925. } catch(e) {
  7926. debug(e);
  7927. }
  7928. } else if ((forceState == 2 || ruleParser.curSiteRule.action == 2) && !isJs) {
  7929. forceIframe(nextLink, (iframe) => {
  7930. if (urlChanged || isPause) {
  7931. loadPageOver();
  7932. return;
  7933. }
  7934. let pageBar = createPageBar(nextLink);
  7935. if (pageBar && iframe && iframe.parentNode) iframe.parentNode.insertBefore(pageBar, iframe);
  7936. loadPageOver();
  7937. checkAutoLoadNum();
  7938. });
  7939. } else if ((forceState == 3 || ruleParser.curSiteRule.action == 1) && !isJs) {
  7940. requestFromIframe(nextLink, (doc, eles) => {
  7941. if (urlChanged || isPause) {
  7942. loadPageOver();
  7943. return;
  7944. }
  7945. if (eles) {
  7946. ruleParser.insertPage(doc, eles, nextLink, () => {
  7947. createPageBar(nextLink);
  7948. checkAutoLoadNum();
  7949. }, true);
  7950. } else loadPageOver();
  7951. });
  7952. } else {
  7953. if (!isJs) {
  7954. requestDoc(nextLink, (eles) => {
  7955. if (urlChanged || isPause) {
  7956. loadPageOver();
  7957. return;
  7958. }
  7959. if (eles) {
  7960. createPageBar(nextLink);
  7961. checkAutoLoadNum();
  7962. } else loadPageOver();
  7963. });
  7964. } else {
  7965. emuPage((doc, eles) => {
  7966. if (urlChanged || isPause) {
  7967. loadPageOver();
  7968. return;
  7969. }
  7970. if (eles) {
  7971. ruleParser.insertPage(doc, eles, "", () => {
  7972. createPageBar(nextLink);
  7973. checkAutoLoadNum();
  7974. }, true);
  7975. } else loadPageOver();
  7976. });
  7977. }
  7978. }
  7979. }, sleep);
  7980. }
  7981. }
  7982.  
  7983. function init() {
  7984. if (document.readyState == 'loading' || document.readyState == 'uninitialized') {
  7985. let domReady = e => {
  7986. initRules(() => {
  7987. initPage();
  7988. });
  7989. document.removeEventListener("DOMContentLoaded", domReady, false);
  7990. }
  7991. document.addEventListener("DOMContentLoaded", domReady, false);
  7992. } else {
  7993. initRules(() => {
  7994. initPage();
  7995. });
  7996. }
  7997. }
  7998.  
  7999. function visibilitychangeHandler() {
  8000. document.removeEventListener('visibilitychange', visibilitychangeHandler);
  8001. init();
  8002. }
  8003.  
  8004. setTimeout(() => {
  8005. if (document.hidden) {
  8006. document.addEventListener('visibilitychange', visibilitychangeHandler);
  8007. } else {
  8008. init();
  8009. }
  8010. }, 300);
  8011. })();