东方永页机

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

当前为 2023-10-14 提交的版本,查看 最新版本

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址