东方永页机

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

当前为 2023-11-27 提交的版本,查看 最新版本

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