东方永页机

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

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

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