东方永页机

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

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

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址