东方永页机

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

当前为 2024-02-25 提交的版本,查看 最新版本

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