东方永页机

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

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

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