东方永页机

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

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

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