东方永页机

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

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

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