东方永页机

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

当前为 2024-02-03 提交的版本,查看 最新版本

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