东方永页机

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

当前为 2024-04-21 提交的版本,查看 最新版本

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