東方永頁機

終極自動翻頁 - 加載並拼接下一分頁內容至當前頁尾,智能適配任意網頁

目前為 2023-11-24 提交的版本,檢視 最新版本

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