东方永页机

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

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