东方永页机

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

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

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

QingJ © 2025

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