东方永页机

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

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

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

QingJ © 2025

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