东方永页机

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

当前为 2023-09-11 提交的版本,查看 最新版本

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