东方永页机

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

当前为 2023-11-29 提交的版本,查看 最新版本

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