东方永页机

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

目前为 2023-10-27 提交的版本。查看 最新版本

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