东方永页机

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

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