东方永页机

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

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

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