东方永页机

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

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

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