东方永页机

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

当前为 2024-01-05 提交的版本,查看 最新版本

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址