东方永页机

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

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

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