东方永页机

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

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

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

QingJ © 2025

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