东方永页机

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

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

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