东方永页机

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

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

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