东方永页机

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

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

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