东方永页机

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

当前为 2023-12-08 提交的版本,查看 最新版本

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

QingJ © 2025

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