东方永页机

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

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

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