东方永页机

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

当前为 2024-05-31 提交的版本,查看 最新版本

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