东方永页机

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

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

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

QingJ © 2025

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