东方永页机

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

目前为 2023-10-25 提交的版本。查看 最新版本

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