东方永页机

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

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