东方永页机

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

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

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