东方永页机

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

当前为 2024-01-15 提交的版本,查看 最新版本

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

QingJ © 2025

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