东方永页机

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

目前为 2024-04-15 提交的版本,查看 最新版本

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