东方永页机

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

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

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