东方永页机

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

当前为 2023-12-13 提交的版本,查看 最新版本

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