东方永页机

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

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