东方永页机

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

当前为 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.87
  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, doc);
  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, doc);
  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, doc) {
  3138. if (!eles || eles.length == 0) return;
  3139. let lazyImgSrc = this.curSiteRule.lazyImgSrc;
  3140. if (lazyImgSrc === 0 || lazyImgSrc === '0') return;
  3141. let imgLazyAttrs = [];
  3142. let lazyAttrs = ["div[data-thumb]|data-src", "div.img|data-src", "div.lazy|data-src", "div.lazy|data-original", "a.lazy|data-bg", "a.lazyload|data-original"];
  3143. let removeProps = [];
  3144. let setLazyImg = img => {
  3145. let realSrc;
  3146. imgLazyAttrs.forEach(attr => {
  3147. realSrc = img.getAttribute(lazyImgSrc[0]);
  3148. if (realSrc) {
  3149. removeProps.forEach(prop => {
  3150. img.removeAttribute(prop.trim());
  3151. });
  3152. img.src = realSrc;
  3153. return;
  3154. }
  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. if (lazyImgSrc) {
  3206. if (!Array.isArray(lazyImgSrc)) {
  3207. lazyAttrs = [lazyImgSrc];
  3208. } else {
  3209. lazyAttrs = lazyImgSrc[0].split(",");
  3210. removeProps = lazyImgSrc[1].split(",");
  3211. }
  3212. }
  3213. lazyAttrs.forEach(attr => {
  3214. let attrArr = attr.split("|");
  3215. if (attrArr.length !== 2) {
  3216. imgLazyAttrs.push(attr.trim());
  3217. } else {
  3218. let selector = attrArr[0].trim();
  3219. let lazyAttr = attrArr[1].trim();
  3220. if (selector == "img") {
  3221. imgLazyAttrs.push(lazyAttr);
  3222. } else {
  3223. selector += "[" + lazyAttr + "]";
  3224. [].forEach.call(doc.querySelectorAll(selector), ele => {
  3225. ele.style.setProperty("background-image", "url(" + ele.getAttribute(lazyAttr) + ")", "important");
  3226. removeProps.forEach(prop => {
  3227. ele.removeAttribute(prop.trim());
  3228. });
  3229. });
  3230. }
  3231. }
  3232. });
  3233. [].forEach.call(doc.querySelectorAll("img,picture>source"), img => {
  3234. setLazyImg(img);
  3235. });
  3236. }
  3237.  
  3238. initPage(callback) {
  3239. let self = this;
  3240. if (self.initing) return;
  3241. self.initing = true;
  3242. setTimeout(() => {
  3243. self.initing = false;
  3244. }, 100);
  3245. curPage = 1;
  3246. urlChanged = false;
  3247. this.clearAddedElements();
  3248. this.insert = null;
  3249. this.visibilityItems = [];
  3250. this.visibleIndex = -1;
  3251. this.pageDoc = document;
  3252. this.nextLinkHref = null;
  3253. this.curUrl = location.href;
  3254. this.oldUrl = "";
  3255. this.initUrl = location.href;
  3256. this.historyUrl = "";
  3257. let base = document.querySelector("base");
  3258. this.basePath = base ? base.href : location.href;
  3259. this.getRule(async () => {
  3260. if (self.curSiteRule.sideController === true || (self.curSiteRule.sideController !== false && rulesData.sideController)) {
  3261. isPause = manualPause;
  3262. }
  3263. if (self.curSiteRule.enable == 0) {
  3264. debug("Stop as rule disable");
  3265. isPause = true;
  3266. _GM_registerMenuCommand(i18n("enable"), () => {
  3267. showTips(i18n("enableSiteTips"));
  3268. if(!self.customRules) {
  3269. self.customRules = [];
  3270. }
  3271. for (let i in self.customRules) {
  3272. if (self.customRules[i].url == self.curSiteRule.url) {
  3273. self.customRules.splice(i, 1);
  3274. break;
  3275. }
  3276. }
  3277. self.curSiteRule.enable = 1;
  3278. self.customRules.unshift(self.curSiteRule);
  3279. storage.setItem("customRules", self.customRules);
  3280. location.reload();
  3281. });
  3282. return;
  3283. }
  3284. //若是再亂匹配就不緩存wedata,或者只在找完本地規則之後再考慮wedata的緩存
  3285. if (self.curSiteRule.singleUrl) {
  3286. delete self.curSiteRule.pageElement;
  3287. self.smartRules = self.smartRules.filter(item => {return item && item.url != self.curSiteRule.url});
  3288. self.smartRules.unshift(self.curSiteRule);
  3289. if (self.smartRules.length > 100) {
  3290. self.smartRules.pop();
  3291. }
  3292. storage.setItem("smartRules", self.smartRules);
  3293. } else if (self.curSiteRule && self.curSiteRule.url.length > 13) {
  3294. self.addToHpRules();
  3295. }
  3296. let css = self.curSiteRule.css || rulesData.customCss;
  3297. if (css) {
  3298. let cssArr = css.split("inIframe:");
  3299. if (cssArr && cssArr.length) {
  3300. _GM_addStyle(cssArr[0]);
  3301. }
  3302. }
  3303. if (/sidesearch=(1|true)$/.test(self.curUrl)) {
  3304. openInNewTab = 0;
  3305. } else if (typeof self.curSiteRule.openInNewTab !== 'undefined') {
  3306. openInNewTab = self.curSiteRule.openInNewTab ? 1 : 2;
  3307. }
  3308. let autoClick = self.curSiteRule.autoClick;
  3309. if (autoClick) {
  3310. let autoClickBtn;
  3311. autoClickBtn = getElement(autoClick, document, null, true);
  3312. if (autoClickBtn) {
  3313. emuClick(autoClickBtn);
  3314. }
  3315. }
  3316. let code = self.curSiteRule.init;
  3317. if (code) {
  3318. try {
  3319. ((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)});
  3320. } catch(e) {
  3321. debug(e);
  3322. }
  3323. }
  3324. await self.getNextLink(document, true);
  3325. if (self.curSiteRule.pageNum && self.nextLinkHref && self.nextLinkHref != "#") {
  3326. let num1st = self.getPageNumFromUrl(location.href, 1);
  3327. let num2nd = self.getPageNumFromUrl(self.nextLinkHref, 1);
  3328. if (num2nd != num1st + 1) {
  3329. self.curSiteRule.pageNum = null;
  3330. }
  3331. }
  3332. if (self.curSiteRule.singleUrl && self.nextLinkHref == false && self.possibleRule) {
  3333. setTimeout(() => {
  3334. self.initPage(() => {});
  3335. }, 3000);
  3336. }
  3337. self.refreshByClick();
  3338.  
  3339. let pageElementCss = self.curSiteRule.pageElementCss || rulesData.pageElementCss;
  3340. if (pageElementCss && pageElementCss !== '0') {
  3341. self.getPageElement(document, _unsafeWindow);
  3342. }
  3343. callback();
  3344. let initRun = typeof self.curSiteRule.initRun == 'undefined' ? rulesData.initRun : self.curSiteRule.initRun;
  3345. if (self.nextLinkHref) {
  3346. sideController.setup();
  3347. if (initRun && initRun != false) {
  3348. setTimeout(() => {
  3349. nextPage();
  3350. }, 500);
  3351. }
  3352. }
  3353. });
  3354. }
  3355.  
  3356. beginLoading() {
  3357. isLoading = true;
  3358. let lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3359. ruleParser.insertElement(loadingDiv);
  3360. if (forceState == 2) {
  3361. getBody(document).appendChild(loadingDiv);
  3362. } else {
  3363. let parent = loadingDiv.parentNode;
  3364. if (compareNodeName(parent, ["tbody"])) {
  3365. parent = parent.parentNode;
  3366. }
  3367. if (compareNodeName(parent, ["table"])) {
  3368. parent.parentNode.appendChild(loadingDiv);
  3369. }
  3370. }
  3371. getBody(document).scrollTop = lastScrollTop;
  3372. document.documentElement.scrollTop = lastScrollTop;
  3373. }
  3374.  
  3375. insertElement(ele) {
  3376. if (!this.insert || !this.insert.parentNode) {
  3377. this.getInsert();
  3378. }
  3379. if (this.insert) {
  3380. let self = this;
  3381. if (ele.nodeName == "#document-fragment") {
  3382. [].forEach.call(ele.children, el => {
  3383. self.addedElePool.push(el);
  3384. });
  3385. } else {
  3386. this.addedElePool.push(ele);
  3387. }
  3388. if (this.curSiteRule.insertPos == 2 || this.curSiteRule.insertPos == "in") {
  3389. this.insert.appendChild(ele);
  3390. } else {
  3391. this.insert.parentNode.insertBefore(ele, this.insert);
  3392. }
  3393. }
  3394. }
  3395.  
  3396. noValidContent(url) {
  3397. if (!this.curSiteRule.nextLinkByUrl) showTips(i18n("noValidContent"), url);
  3398. }
  3399.  
  3400. async insertPage(doc, eles, url, callback, tried) {
  3401. this.oldUrl = this.curUrl;
  3402. let oldTitle = this.pageDoc.title;
  3403. this.pageDoc = doc;
  3404. this.curUrl = url;
  3405. isLoading = true;
  3406. let nextLink = await this.getNextLink(doc);
  3407. this.nextTitle = "";
  3408. if (this.curSiteRule.pageBarText) {
  3409. if (this.curSiteRule.pageBarText == 1 || this.curSiteRule.pageBarText == true) {
  3410. this.nextTitle = doc.title;
  3411. } else {
  3412. try {
  3413. this.nextTitle = ((typeof this.curSiteRule.pageBarText == 'function') ? this.curSiteRule.pageBarText : Function("doc",'"use strict";' + this.curSiteRule.pageBarText))(doc);
  3414. } catch(e) {
  3415. debug(e);
  3416. }
  3417. }
  3418. }
  3419. if (curPage == 1 && !tried && !nextLink && this.curSiteRule.singleUrl && this.curSiteRule.pageElement && this.curSiteRule.action != 0) {
  3420. this.curSiteRule.action = 1;
  3421. this.curUrl = location.href;
  3422. isLoading = false;
  3423. return false;
  3424. }
  3425. let lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3426. this.getInsert();
  3427. var self = this, newEles = [];
  3428. if (!eles || eles.length == 0 || !self.insert || !self.insert.parentNode) {
  3429. if (callback) callback(eles);
  3430. loadPageOver();
  3431. } else {
  3432. await this.pageInit(doc, eles);
  3433. if (callback) callback(eles);
  3434. loadPageOver();
  3435. const collection = document.createDocumentFragment();
  3436. [].forEach.call(eles, ele => {
  3437. let newEle = ele.cloneNode(true);
  3438. let oldCanvass = ele.querySelectorAll("canvas");
  3439. let newCanvass = newEle.querySelectorAll("canvas");
  3440. if (self.updateUrl) {
  3441. [].forEach.call(newEle.querySelectorAll("img"), img => {
  3442. if (img.getAttribute("src")) img.src = self.canonicalUri(img.getAttribute("src"));
  3443. });
  3444. [].forEach.call(newEle.querySelectorAll("a"), a => {
  3445. if (a.getAttribute("href")) a.href = self.canonicalUri(a.getAttribute("href"));
  3446. });
  3447. }
  3448. for (let i = 0; i < oldCanvass.length; i++) {
  3449. let oldCanvas = oldCanvass[i];
  3450. let newCanvas = newCanvass[i];
  3451. newCanvas.getContext('2d').drawImage(oldCanvas, 0, 0);
  3452. }
  3453. if (!compareNodeName(newEle, ["style", "script"])) self.visibilityItems.push(newEle);
  3454. collection.appendChild(newEle)
  3455. newEles.push(newEle);
  3456. });
  3457. self.insertElement(collection);
  3458. }
  3459. getBody(document).scrollTop = lastScrollTop;
  3460. document.documentElement.scrollTop = lastScrollTop;
  3461. this.pageAction(doc, newEles);
  3462. let enableHistory = this.curSiteRule.history;
  3463. let enableHistoryAfterInsert = false;
  3464. if (enableHistory == 1) {
  3465. enableHistory = true;
  3466. } else if (enableHistory == 2) {
  3467. enableHistory = true;
  3468. enableHistoryAfterInsert = true;
  3469. } else if (enableHistory == 0) {
  3470. enableHistory = false;
  3471. } else {
  3472. enableHistory = rulesData.enableHistory;
  3473. enableHistoryAfterInsert = rulesData.enableHistoryAfterInsert;
  3474. }
  3475. if (enableHistory) {
  3476. this.historyUrl = enableHistoryAfterInsert ? this.curUrl : this.oldUrl;
  3477. if(this.historyUrl != location.href) {
  3478. let isJs = this.hrefIsJs(this.historyUrl);
  3479. if (!isJs) {
  3480. let historyTitle = enableHistoryAfterInsert ? doc.title : oldTitle;
  3481. _unsafeWindow.history.replaceState(undefined, historyTitle, this.historyUrl);
  3482. document.title = historyTitle;
  3483. }
  3484. }
  3485. }
  3486. isLoading = false;
  3487. return true;
  3488. }
  3489. }
  3490. var ruleParser = new RuleParser();
  3491.  
  3492. class SideController {
  3493. //static controller;
  3494. constructor() {
  3495. this.inited = false;
  3496. }
  3497.  
  3498. /*static getInstance() {
  3499. if (!SideController.controller) {
  3500. SideController.controller = new SideController();
  3501. }
  3502. return SideController.controller;
  3503. }*/
  3504.  
  3505. setup() {
  3506. if (ruleParser.curSiteRule.sideController === false) return;
  3507. if (!rulesData.sideController && !ruleParser.curSiteRule.sideController) return;
  3508. this.addToStage();
  3509. }
  3510.  
  3511. init() {
  3512. if (this.inited) return;
  3513. this.inited = true;
  3514. let self = this;
  3515. this.cssText = `
  3516. #pagetual-sideController {
  3517. position: fixed;
  3518. top: calc(50% - 83px);
  3519. left: calc(99% - 40px);
  3520. width: 40px;
  3521. border-radius: 20px;
  3522. box-shadow: rgb(0 0 0) 0px 0px 10px;
  3523. text-align: center;
  3524. background: #ffffffd0!important;
  3525. user-select: none;
  3526. z-index: 2147483646!important;
  3527. padding: 0!important;
  3528. opacity: 0.35;
  3529. transition: opacity .5s ease, background .5s, box-shadow .5s;
  3530. }
  3531. #pagetual-sideController:hover {
  3532. opacity: 1;
  3533. }
  3534. #pagetual-sideController * {
  3535. font-weight: bold;
  3536. font-family: arial;
  3537. font-style: normal;
  3538. font-size: 20px!important;
  3539. color: black!important;
  3540. line-height: normal;
  3541. float: none;
  3542. }
  3543. #pagetual-sideController.stop {
  3544. -webkit-filter: invert(100%);
  3545. filter: invert(100%);
  3546. }
  3547. .pagetual-sideController-btn {
  3548. padding: 5px 0;
  3549. cursor: pointer;
  3550. transition: transform .15s ease-in-out, opacity .3s ease;
  3551. }
  3552. #pagetual-sideController .pagetual-sideController-btn:hover {
  3553. transform: scale(1.5);
  3554. color: red!important;
  3555. }
  3556. #pagetual-sideController.minSize {
  3557. box-shadow: rgb(0 0 0 / 0%) 0px 0px 0px;
  3558. background: #00000000!important;
  3559. }
  3560. #pagetual-sideController.minSize .pagetual-sideController-btn {
  3561. opacity: 0;
  3562. }
  3563. #pagetual-sideController #pagetual-sideController-move > svg {
  3564. transition: transform .3s ease;
  3565. }
  3566. #pagetual-sideController #pagetual-sideController-move > svg:hover {
  3567. transform: scale(1.2);
  3568. }
  3569. #pagetual-sideController.minSize #pagetual-sideController-move > svg {
  3570. background: white;
  3571. opacity: 0;
  3572. }
  3573. #pagetual-sideController #pagetual-sideController-move > img,
  3574. #pagetual-sideController #pagetual-sideController-move > span {
  3575. width: 35px;
  3576. height: 35px;
  3577. cursor: pointer;
  3578. }
  3579. #pagetual-sideController.minSize #pagetual-sideController-move > img,
  3580. #pagetual-sideController.minSize #pagetual-sideController-move > span {
  3581. border-radius: 50px;
  3582. text-shadow: rgb(255 255 255) 0px 0px 10px;
  3583. }
  3584. #pagetual-sideController #pagetual-sideController-pagenum {
  3585. font-size: 15px!important;
  3586. line-height: 30px;
  3587. text-align: center;
  3588. position: absolute;
  3589. right: calc(50% - 15px);
  3590. top: calc(50% - 15px);
  3591. border: 1px solid #00000099;
  3592. display: inline-block;
  3593. width: 30px;
  3594. height: 30px;
  3595. box-sizing: border-box;
  3596. border-radius: 50%;
  3597. background: white;
  3598. opacity: 0;
  3599. transition: opacity .5s ease;
  3600. pointer-events: none;
  3601. }
  3602. #pagetual-sideController.minSize #pagetual-sideController-pagenum {
  3603. opacity: 0.8;
  3604. }
  3605. `;
  3606. let frame = document.createElement("div");
  3607. frame.id = "pagetual-sideController";
  3608. frame.innerHTML = createHTML(`
  3609. <div id="pagetual-sideController-top" class="pagetual-sideController-btn">⊼</div>
  3610. <div>
  3611. <div id="pagetual-sideController-pre" class="pagetual-sideController-btn">∧</div>
  3612. <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>
  3613. <div id="pagetual-sideController-next" class="pagetual-sideController-btn">∨</div>
  3614. </div>
  3615. <div id="pagetual-sideController-bottom" class="pagetual-sideController-btn">⊻</div>
  3616. `);
  3617. frame.classList.add("stop");
  3618. let top = frame.querySelector("#pagetual-sideController-top");
  3619. let pre = frame.querySelector("#pagetual-sideController-pre");
  3620. let move = frame.querySelector("#pagetual-sideController-move");
  3621. let next = frame.querySelector("#pagetual-sideController-next");
  3622. let bottom = frame.querySelector("#pagetual-sideController-bottom");
  3623. let pagenum = frame.querySelector("#pagetual-sideController-pagenum");
  3624. if (sideControllerIcon) move.innerHTML = sideControllerIcon;
  3625.  
  3626. frame.addEventListener("dblclick", e => {
  3627. e.preventDefault();
  3628. e.stopPropagation();
  3629. });
  3630.  
  3631. frame.addEventListener("mouseenter", e => {
  3632. clearTimeout(self.hideTimer);
  3633. frame.classList.remove("minSize");
  3634. });
  3635.  
  3636. frame.addEventListener("mouseleave", e => {
  3637. clearTimeout(self.hideTimer);
  3638. self.hideTimer = setTimeout(() => {
  3639. frame.classList.add("minSize");
  3640. }, 800);
  3641. });
  3642.  
  3643. pre.addEventListener("click", e => {
  3644. let prePageBar = getPageBar().preBar;
  3645. if (prePageBar) {
  3646. scrollToPageBar(prePageBar);
  3647. } else {
  3648. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3649. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  3650. }
  3651. }, true);
  3652.  
  3653. next.addEventListener("click", e => {
  3654. let pageBarObj = getPageBar();
  3655. let nextPageBar = pageBarObj.nextBar;
  3656. if (nextPageBar) {
  3657. scrollToPageBar(nextPageBar);
  3658. } else {
  3659. if (pageBarObj.preBar) {
  3660. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  3661. window.scrollTo({ top: (scrollH || 9999999), behavior: 'instant'});
  3662. } else {
  3663. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3664. window.scrollTo({ top: scrollTop + (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  3665. }
  3666. }
  3667. }, true);
  3668.  
  3669. top.addEventListener("click", e => {
  3670. getBody(document).scrollTop=0;
  3671. document.documentElement.scrollTop=0;
  3672. e.preventDefault();
  3673. e.stopPropagation();
  3674. }, true);
  3675.  
  3676. bottom.addEventListener("click", e => {
  3677. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  3678. changeStop(true);
  3679. }
  3680. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  3681. getBody(document).scrollTop = scrollH || 9999999;
  3682. document.documentElement.scrollTop = scrollH || 9999999;
  3683. e.preventDefault();
  3684. e.stopPropagation();
  3685. }, true);
  3686.  
  3687. let initX, initY, moving = false;
  3688. let removeTimer;
  3689. move.addEventListener("click", e => {
  3690. if (!moving) {
  3691. changeStop(!isPause);
  3692. }
  3693. }, true);
  3694. move.addEventListener("dblclick", e => {
  3695. clearTimeout(removeTimer);
  3696. document.removeEventListener("mousemove", mouseMoveHandler, true);
  3697. document.removeEventListener("mouseup", mouseUpHandler, true);
  3698. changeStop(!isPause);
  3699. if (isPause) {
  3700. ruleParser.hideAddedElements();
  3701. } else {
  3702. ruleParser.showAddedElements();
  3703. }
  3704. }, true);
  3705.  
  3706. move.oncontextmenu = e => {
  3707. e.preventDefault();
  3708. picker.start();
  3709. };
  3710.  
  3711. let mouseMoveHandler = e => {
  3712. if (moving) {
  3713. let windowHeight=window.innerHeight || document.documentElement.clientHeight;
  3714. let windowWidth=window.innerWidth || document.documentElement.clientWidth;
  3715. initX = (e.clientX - 10 + 40) / windowWidth * 100;
  3716. initY = (e.clientY - 83 + 83) / windowHeight * 100;
  3717. this.frame.style.top = `calc(${initY}% - 83px)`;
  3718. this.frame.style.left = `calc(${initX}% - 40px)`;
  3719. } else if (Math.abs(e.clientX - initX) + Math.abs(e.clientY - initY) > 20) {
  3720. moving = true;
  3721. clearTimeout(removeTimer);
  3722. }
  3723. };
  3724. let mouseUpHandler = e => {
  3725. clearTimeout(removeTimer);
  3726. document.removeEventListener("mousemove", mouseMoveHandler, true);
  3727. document.removeEventListener("mouseup", mouseUpHandler, true);
  3728. if (moving) {
  3729. rulesData.sideControllerPos = {x: parseInt(initX), y: parseInt(initY)};
  3730. storage.setItem("rulesData", rulesData);
  3731. }
  3732. };
  3733.  
  3734. move.addEventListener("mousedown", e => {
  3735. initX = e.clientX;
  3736. initY = e.clientY;
  3737. moving = false;
  3738. clearTimeout(removeTimer);
  3739. removeTimer = setTimeout(() => {
  3740. self.remove();
  3741. }, 1500);
  3742. document.addEventListener("mousemove", mouseMoveHandler, true);
  3743. document.addEventListener("mouseup", mouseUpHandler, true);
  3744. }, true);
  3745.  
  3746. this.frame = frame;
  3747. this.pagenum = pagenum;
  3748. if (rulesData.sideControllerPos) {
  3749. this.frame.style.top = `calc(${rulesData.sideControllerPos.y}% - 83px)`;
  3750. this.frame.style.left = `calc(${rulesData.sideControllerPos.x}% - 40px)`;
  3751. }
  3752. }
  3753.  
  3754. addToStage() {
  3755. this.init();
  3756. if (!this.styleEle || !this.styleEle.parentNode) {
  3757. this.styleEle = _GM_addStyle(this.cssText);
  3758. }
  3759. if (!isPause) {
  3760. this.frame.classList.remove("stop");
  3761. }
  3762. this.pagenum.innerHTML = createHTML(curPage);
  3763. this.frame.title = i18n("page") + curPage;
  3764. if (this.frame.parentNode) return;
  3765. getBody(document).appendChild(this.frame);
  3766. clearTimeout(this.hideTimer);
  3767. this.frame.classList.add("minSize");
  3768. }
  3769.  
  3770. remove() {
  3771. if (this.frame && this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  3772. }
  3773. }
  3774. const sideController = new SideController();
  3775.  
  3776. class NextSwitch {
  3777. //static nextSwitch;
  3778. constructor() {
  3779. this.inited = false;
  3780. }
  3781.  
  3782. /*static getInstance() {
  3783. if (!NextSwitch.nextSwitch) {
  3784. NextSwitch.nextSwitch = new NextSwitch();
  3785. }
  3786. return NextSwitch.nextSwitch;
  3787. }*/
  3788.  
  3789. init() {
  3790. if (this.inited) return;
  3791. this.inited = true;
  3792. let self = this;
  3793. this.cssText = `
  3794. #pagetual-nextSwitch {
  3795. position: fixed;
  3796. top: 10px;
  3797. left: calc(50% - 160px);
  3798. background: aliceblue;
  3799. padding: 10px;
  3800. border-radius: 5px;
  3801. text-align: center;
  3802. opacity: 0.95;
  3803. color: #161616;
  3804. z-index: 2147483647;
  3805. font-size: 16px;
  3806. box-shadow: rgb(0 0 0) 0px 0px 10px;
  3807. }
  3808. #pagetual-nextSwitch>.title {
  3809. margin: -5px 45px 10px 45px;
  3810. font-size: 20px;
  3811. font-weight: bold;
  3812. border-bottom: 1px solid black;
  3813. user-select: none;
  3814. color: orangered;
  3815. }
  3816. #pagetual-nextSwitch>.group {
  3817. display: flex;
  3818. flex-direction: column;
  3819. }
  3820. #pagetual-nextSwitch>.group>span {
  3821. color: #161616;
  3822. cursor: pointer;
  3823. margin: 3px;
  3824. font-size: larger;
  3825. }
  3826. #pagetual-nextSwitch>.group>span:hover {
  3827. color: red;
  3828. }
  3829. #pagetual-nextSwitch>.group>span.current {
  3830. border: 2px dotted red;
  3831. border-radius: 10px;
  3832. }
  3833. #pagetual-nextSwitch>.closeSwitch {
  3834. position: absolute;
  3835. top: 3px;
  3836. right: 10px;
  3837. background: none;
  3838. border: none;
  3839. vertical-align: top;
  3840. transition: transform .15s ease-in-out;
  3841. float: right;
  3842. cursor: pointer;
  3843. }
  3844. #pagetual-nextSwitch svg {
  3845. width: 30px;
  3846. height: 30px;
  3847. vertical-align: middle;
  3848. fill: #161616;
  3849. overflow: hidden;
  3850. }
  3851. #pagetual-nextSwitch button:hover {
  3852. transform: scale(1.2);
  3853. }
  3854. `;
  3855. let frame = document.createElement("div");
  3856. frame.id = "pagetual-nextSwitch";
  3857. frame.innerHTML = createHTML(`
  3858. <div class="title">${i18n("nextSwitch")}</div>
  3859. <button type="button" class="closeSwitch">
  3860. <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2754">
  3861. <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">
  3862. </path>
  3863. </svg>
  3864. </button>
  3865. <div class="group"></div>
  3866. `);
  3867. let group = frame.querySelector(".group");
  3868. let closeBtn = frame.querySelector(".closeSwitch");
  3869. closeBtn.addEventListener("click", e => {
  3870. self.close();
  3871. }, true);
  3872. this.frame = frame;
  3873. let currentSpan;
  3874. ruleParser.curSiteRule.nextLink.forEach((link, i) => {
  3875. let span = document.createElement("span");
  3876. let target = getElement(link, document);
  3877. let index = "<b>" + (i + 1) + "</b>: ";
  3878. if (target) {
  3879. let targetInner = target.innerText.trim();
  3880. span.innerHTML = index + (targetInner || link);
  3881. } else {
  3882. span.innerHTML = index + "Not Found";
  3883. }
  3884. span.title = link;
  3885. span.addEventListener("click", e => {
  3886. if (currentSpan) currentSpan.classList.remove("current");
  3887. span.classList.add("current");
  3888. currentSpan = span;
  3889. nextIndex = i;
  3890. storage.setItem("nextSwitch_" + location.host, nextIndex === 0 ? "" : nextIndex);
  3891. ruleParser.curUrl += "#pagetual";
  3892. ruleParser.oldUrl = ruleParser.curUrl;
  3893. autoLoadNum = -1;
  3894. if (!ruleParser.nextLinkHref) {
  3895. isLoading = false;
  3896. }
  3897. ruleParser.getNextLink(ruleParser.pageDoc || document);
  3898. self.close();
  3899. }, true);
  3900. if (i == nextIndex) {
  3901. span.classList.add("current");
  3902. currentSpan = span;
  3903. }
  3904. group.appendChild(span);
  3905. });
  3906. }
  3907.  
  3908. start() {
  3909. this.init();
  3910. if (!this.styleEle || !this.styleEle.parentNode) {
  3911. this.styleEle = _GM_addStyle(this.cssText);
  3912. }
  3913. document.documentElement.appendChild(this.frame);
  3914. }
  3915.  
  3916. close() {
  3917. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  3918. }
  3919. }
  3920. const nextSwitch = new NextSwitch();
  3921.  
  3922. class Picker {
  3923. //static picker;
  3924. constructor() {
  3925. this.inited = false;
  3926. }
  3927.  
  3928. /*static getInstance() {
  3929. if (!Picker.picker) {
  3930. Picker.picker = new Picker();
  3931. }
  3932. return Picker.picker;
  3933. }*/
  3934.  
  3935. init() {
  3936. if (this.inited) return;
  3937. this.inited = true;
  3938. let self = this;
  3939. this.signList = [];
  3940. this.cssText = `
  3941. body.pagetual-picker,
  3942. body.pagetual-picker *:hover,
  3943. body.pagetual-picker a:hover {
  3944. cursor: crosshair !important;
  3945. }
  3946. #pagetual-picker {
  3947. position: fixed;
  3948. top: 10px;
  3949. left: calc(50% - 178px);
  3950. background: aliceblue;
  3951. padding: 10px;
  3952. border-radius: 5px;
  3953. text-align: center;
  3954. opacity: 0.95;
  3955. color: #161616;
  3956. z-index: 2147483646;
  3957. font-size: 16px;
  3958. overflow: hidden;
  3959. box-shadow: rgb(0 0 0) 0px 0px 10px;
  3960. }
  3961. #pagetual-picker * {
  3962. margin: 0;
  3963. padding: 0;
  3964. font-family: Times New Roman;
  3965. overflow: initial;
  3966. user-select: none;
  3967. }
  3968. #pagetual-picker>.title {
  3969. margin: -5px 45px 10px 45px;
  3970. font-size: 20px;
  3971. font-weight: bold;
  3972. cursor: move;
  3973. border-bottom: 1px solid black;
  3974. user-select: none;
  3975. color: orangered;
  3976. height: initial;
  3977. width: initial;
  3978. position: initial;
  3979. }
  3980. #pagetual-picker button {
  3981. background: none;
  3982. border: none;
  3983. vertical-align: top;
  3984. transition: transform .15s ease-in-out;
  3985. float: right;
  3986. cursor: pointer;
  3987. overflow: hidden;
  3988. background-color: unset!important;
  3989. }
  3990. #pagetual-picker button:hover {
  3991. transform: scale(1.2);
  3992. }
  3993. #pagetual-picker>.closePicker {
  3994. position: absolute;
  3995. top: 3px;
  3996. right: 10px;
  3997. }
  3998. #pagetual-picker>.logoIcon {
  3999. position: absolute;
  4000. top: 3px;
  4001. left: 10px;
  4002. }
  4003. #pagetual-picker>.logoIcon.showSign>svg>path {
  4004. fill: gray;
  4005. }
  4006. #pagetual-picker textarea{
  4007. display: inline-block;
  4008. width: calc(100% - 65px);
  4009. height: 20px;
  4010. min-width: 290px;
  4011. max-width: calc(65vw - 50px);
  4012. min-height: unset;
  4013. padding: 6px 12px;
  4014. font-size: 16px;
  4015. font-weight: 400;
  4016. line-height: 1.5;
  4017. color: #495057;
  4018. background-color: #fff;
  4019. background-clip: padding-box;
  4020. border: 1px solid #ced4da;
  4021. border-radius: 4px;
  4022. transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
  4023. box-sizing: content-box;
  4024. margin-right: 5px;
  4025. resize: both;
  4026. box-shadow: 0 1px 5px 1px #ddd;
  4027. overflow-wrap: anywhere;
  4028. }
  4029. #pagetual-picker textarea:focus {
  4030. color: black;
  4031. background-color: #fff;
  4032. border-color: #80bdff;
  4033. outline: 0;
  4034. box-shadow: 0 0 0 3.2px rgb(0 123 255 / 25%);
  4035. }
  4036. #pagetual-picker [type=checkbox],
  4037. #pagetual-picker [type=radio] {
  4038. line-height: 20px;
  4039. height: 25px;
  4040. width: 25px;
  4041. margin-left: 5px;
  4042. vertical-align: middle;
  4043. appearance: auto;
  4044. display: inline-block;
  4045. position: initial;
  4046. }
  4047. #pagetual-picker [type=checkbox]:after,
  4048. #pagetual-picker [type=radio]:after,
  4049. #pagetual-picker [type=checkbox]:before,
  4050. #pagetual-picker [type=radio]:before {
  4051. border: none;
  4052. background: none;
  4053. }
  4054. #pagetual-picker label {
  4055. font-size: 18px;
  4056. line-height: 25px;
  4057. vertical-align: middle;
  4058. display: inline-block;
  4059. color: black;
  4060. position: initial;
  4061. cursor: pointer;
  4062. }
  4063. #pagetual-picker .bottom {
  4064. text-align: left;
  4065. margin: 10px 0;
  4066. width: 100%;
  4067. }
  4068. #pagetual-picker .bottom>button {
  4069. float: right;
  4070. }
  4071. #pagetual-picker svg {
  4072. width: 30px;
  4073. height: 30px;
  4074. vertical-align: middle;
  4075. fill: #161616;
  4076. overflow: hidden;
  4077. }
  4078. #pagetual-picker svg * {
  4079. pointer-events: none;
  4080. }
  4081. #pagetual-picker .allpath {
  4082. font-size: 18px;
  4083. margin: 10px auto;
  4084. max-width: 330px;
  4085. word-break: break-all;
  4086. cursor: context-menu;
  4087. overflow: hidden;
  4088. max-height: 42px;
  4089. -moz-transition:max-height 1s ease-in;
  4090. -webkit-transition:max-height 1s ease-in;
  4091. transition:max-height 1s ease-in;
  4092. color: black;
  4093. }
  4094. #pagetual-picker .allpath:hover {
  4095. max-height: calc(100vh - 130px);
  4096. overflow: auto;
  4097. }
  4098. #pagetual-picker .allpath>span.path {
  4099. cursor: pointer;
  4100. }
  4101. #pagetual-picker .allpath>span.path:hover {
  4102. opacity: 0.6;
  4103. }
  4104. #pagetual-picker .allpath>span.path:hover,
  4105. #pagetual-picker .allpath>span.path.checked {
  4106. color: orangered;
  4107. }
  4108. #pagetual-picker .moreConfig {
  4109. display: flex;
  4110. justify-content: space-between;
  4111. border-top: 1px solid;
  4112. padding-top: 10px;
  4113. width: 100%;
  4114. }
  4115. #pagetual-picker .command {
  4116. width: 100%;
  4117. color: black!important;
  4118. text-align: center;
  4119. font-size: large;
  4120. margin-top: 10px;
  4121. box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.12);
  4122. border-radius: 5px;
  4123. }
  4124. #pagetual-picker .command:hover {
  4125. color: orangered;
  4126. }
  4127. #pagetual-picker #showDetail {
  4128. float: initial;
  4129. margin-top: 10px;
  4130. }
  4131. #pagetual-picker.showDetail #showDetail {
  4132. float: right;
  4133. }
  4134. #pagetual-picker #showDetail>svg {
  4135. -moz-transition:transform 0.3s ease;
  4136. -webkit-transition:transform 0.3s ease;
  4137. transition:transform 0.3 ease;
  4138. }
  4139. #pagetual-picker.showDetail #showDetail>svg {
  4140. transform: rotate(180deg);
  4141. }
  4142. #pagetual-picker .tempRule {
  4143. display: none;
  4144. margin-top: 10px;
  4145. height: 300px;
  4146. min-height: 150px;
  4147. }
  4148. #pagetual-picker.showDetail .tempRule {
  4149. display: inline-block;
  4150. }
  4151. #pagetual-picker #saveDetail {
  4152. display: none;
  4153. position: absolute;
  4154. bottom: 10px;
  4155. right: 8px;
  4156. }
  4157. #pagetual-picker.showDetail #saveDetail {
  4158. display: inline-block;
  4159. }
  4160. #pagetual-picker #saveDetail svg {
  4161. width: 35px;
  4162. height: 35px;
  4163. }
  4164. #pagetual-picker .addProp {
  4165. display: none;
  4166. flex-direction: column;
  4167. position: absolute;
  4168. bottom: 45px;
  4169. right: 12px;
  4170. }
  4171. #pagetual-picker.showDetail .addProp {
  4172. display: flex;
  4173. }
  4174. #pagetual-picker .addProp>button {
  4175. font-size: 30px;
  4176. font-family: Arial,sans-serif;
  4177. line-height: 35px;
  4178. color: #161616;
  4179. }
  4180. `;
  4181. this.mainSignDiv = this.createSignDiv();
  4182. this.allSignDiv = [];
  4183. let frame = document.createElement("div");
  4184. frame.id = "pagetual-picker";
  4185. frame.innerHTML = createHTML(`
  4186. <button title="Pagetual" type="button" class="logoIcon">
  4187. <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>
  4188. </button>
  4189. <div class="title" title="${i18n("configure")}">${i18n("picker")}</div>
  4190. <button title="${i18n("closePicker")}" type="button" class="closePicker">
  4191. <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>
  4192. </button>
  4193. <div class="allpath" title="${i18n("switchSelector")}"></div>
  4194. <div>
  4195. <textarea class="selector" spellcheck="false" name="selector" placeholder="${i18n("pickerPlaceholder")}"></textarea>
  4196. <button id="check" title="${i18n("pickerCheck")}" type="button">
  4197. <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>
  4198. </button>
  4199. </div>
  4200. <div class="bottom">
  4201. <input name="xpath" id="checkbox_id" type="checkbox" />
  4202. <label for="checkbox_id">XPath</label>
  4203. <button id="edit" title="${i18n("gotoEdit")}" type="button">
  4204. <svg viewBox="0 0 1024 1024" style="color: orangered;fill: orangered;" version="1.1" xmlns="http://www.w3.org/2000/svg">
  4205. <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">
  4206. </path>
  4207. </svg>
  4208. </button>
  4209. </div>
  4210. <div class="moreConfig">
  4211. <div title="${i18n('forceStateIframe')}">
  4212. <input name="forceState" id="forceStateIframe" type="radio" />
  4213. <label for="forceStateIframe">${i18n('iframe')}</label>
  4214. </div>
  4215. <div title="${i18n('forceStateDynamic')}">
  4216. <input name="forceState" id="forceStateDynamic" type="radio" />
  4217. <label for="forceStateDynamic">${i18n('dynamic')}</label>
  4218. </div>
  4219. <div title="${i18n('forceStateDisable')}">
  4220. <input name="forceState" id="forceStateDisable" type="radio" />
  4221. <label for="forceStateDisable">${i18n('disable')}</label>
  4222. </div>
  4223. </div>
  4224. <button id="nextSwitch" class="command" title="${i18n("nextSwitch")}" type="button">${i18n("nextSwitch")}</button>
  4225. <button id="loadNow" class="command" title="${i18n("loadNow")}" type="button">${i18n("loadNow")}</button>
  4226. <button id="autoScroll" class="command" title="${i18n("toggleAutoScroll")}" type="button"></button>
  4227. <div>
  4228. <textarea class="tempRule" spellcheck="false" placeholder="{Rule object}" title="Rule for current site"></textarea>
  4229. <button id="showDetail" title="" type="button">
  4230. <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>
  4231. </button>
  4232. <div class="addProp">
  4233. <button id="addOtherProp" title="${i18n("addOtherProp")}" type="button">+</button>
  4234. <button id="addNextSelector" title="${i18n("addNextSelector")}" type="button">></button>
  4235. <button id="addPageSelector" title="${i18n("addPageSelector")}" type="button">❏</button>
  4236. </div>
  4237. <button id="saveDetail" title="${i18n("save")}" type="button">
  4238. <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>
  4239. </button>
  4240. </div>
  4241. `);
  4242. let forceStateIframe = frame.querySelector("#forceStateIframe");//forceState 1 禁用 2 强嵌 3 动态
  4243. let forceStateDynamic = frame.querySelector("#forceStateDynamic");
  4244. let forceStateDisable = frame.querySelector("#forceStateDisable");
  4245. let clickRadio = e => {
  4246. let radio = e.currentTarget.querySelector('input');
  4247. if (radio.checked) {
  4248. forceState = "";
  4249. } else {
  4250. switch (radio.id) {
  4251. case "forceStateIframe":
  4252. forceState = 2;
  4253. break;
  4254. case "forceStateDynamic":
  4255. forceState = 3;
  4256. break;
  4257. case "forceStateDisable":
  4258. forceState = 1;
  4259. break;
  4260. default:
  4261. return;
  4262. }
  4263. }
  4264. storage.setItem("forceState_" + location.host, forceState);
  4265. self.close();
  4266. location.reload();
  4267. };
  4268. forceStateIframe.parentNode.addEventListener("mousedown", clickRadio);
  4269. forceStateDynamic.parentNode.addEventListener("mousedown", clickRadio);
  4270. forceStateDisable.parentNode.addEventListener("mousedown", clickRadio);
  4271. if (forceState == 1) forceStateDisable.checked = true;
  4272. else if (forceState == 2) forceStateIframe.checked = true;
  4273. else if (forceState == 3) forceStateDynamic.checked = true;
  4274. let closeBtn = frame.querySelector(".closePicker");
  4275. let logoBtn = frame.querySelector(".logoIcon");
  4276. let title = frame.querySelector(".title");
  4277. let allpath = frame.querySelector(".allpath");
  4278. let selectorInput = frame.querySelector(".selector");
  4279. let xpath = frame.querySelector("#checkbox_id");
  4280. let checkBtn = frame.querySelector("#check");
  4281. let editBtn = frame.querySelector("#edit");
  4282. let nextSwitchBtn = frame.querySelector("#nextSwitch");
  4283. let autoScrollBtn = frame.querySelector("#autoScroll");
  4284. let loadNow = frame.querySelector("#loadNow");
  4285. let tempRule = frame.querySelector(".tempRule");
  4286. let showDetailBtn = frame.querySelector("#showDetail");
  4287. let saveDetailBtn = frame.querySelector("#saveDetail");
  4288. let addOtherProp = frame.querySelector("#addOtherProp");
  4289. let addNextSelector = frame.querySelector("#addNextSelector");
  4290. let addPageSelector = frame.querySelector("#addPageSelector");
  4291. autoScrollBtn.addEventListener("click", e => {
  4292. self.close();
  4293. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), 50)) || 0;
  4294. autoScroll = parseInt(autoScroll) || 0;
  4295. if (autoScroll < 0) autoScroll = 0;
  4296. else if (autoScroll > 1000) autoScroll = 1000;
  4297. storage.setItem("autoScroll_" + location.host + location.pathname, autoScroll);
  4298. startAutoScroll();
  4299. }, true);
  4300. addOtherProp.addEventListener("click", e => {
  4301. let propName = prompt(i18n("propName"));
  4302. if (!propName) return;
  4303. let propValue = prompt(i18n("propValue"));
  4304. if (!propValue) return;
  4305. if (propValue === "true") propValue = true;
  4306. else if (propValue === "false") propValue = false;
  4307. else if (/^\d+$/.test(propValue)) propValue = parseInt(propValue);
  4308. let editTemp = self.getTempRule();
  4309. if (!editTemp) return;
  4310. editTemp[propName] = propValue;
  4311. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  4312. }, true);
  4313. addNextSelector.addEventListener("click", e => {
  4314. let editTemp = self.getTempRule();
  4315. if (!editTemp) return;
  4316. let selector = self.selectorInput.value;
  4317. if (selector) {
  4318. editTemp.nextLink = selector;
  4319. }
  4320. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  4321. }, true);
  4322. addPageSelector.addEventListener("click", e => {
  4323. let editTemp = self.getTempRule();
  4324. if (!editTemp) return;
  4325. let selector = self.selectorInput.value;
  4326. if (selector) {
  4327. editTemp.pageElement = selector;
  4328. }
  4329. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  4330. }, true);
  4331. showDetailBtn.addEventListener("click", e => {
  4332. frame.classList.toggle("showDetail");
  4333. }, true);
  4334. saveDetailBtn.addEventListener("click", e => {
  4335. let editTemp = self.getTempRule(true);
  4336. if (tempRule.value && !editTemp) {
  4337. return;
  4338. }
  4339. if(!ruleParser.customRules) {
  4340. ruleParser.customRules = [];
  4341. }
  4342. for (let i in ruleParser.customRules) {
  4343. if (ruleParser.customRules[i].url == editTemp.url) {
  4344. ruleParser.customRules.splice(i, 1);
  4345. break;
  4346. }
  4347. }
  4348. if (tempRule.value) {
  4349. ruleParser.customRules.unshift(editTemp);
  4350. ruleParser.curSiteRule = editTemp;
  4351. } else {
  4352. ruleParser.curSiteRule = {};
  4353. isPause = true;
  4354. }
  4355. storage.setItem("customRules", ruleParser.customRules);
  4356. if (ruleParser.hpRules && ruleParser.curSiteRule && !ruleParser.curSiteRule.singleUrl) {
  4357. ruleParser.addToHpRules(true);
  4358. }
  4359. if (window.confirm(i18n("reloadPage"))) {
  4360. setTimeout(() => {location.reload()}, 100);
  4361. }
  4362. }, true);
  4363. nextSwitchBtn.addEventListener("click", e => {
  4364. self.close();
  4365. nextSwitch.start();
  4366. }, true);
  4367. loadNow.addEventListener("click", e => {
  4368. self.close();
  4369. let loadNum = window.prompt(i18n("loadConfirm"), "1");
  4370. if (loadNum === "" || loadNum === null) return;
  4371. autoLoadNum = Math.abs(parseInt(loadNum));
  4372. nextPage();
  4373. }, true);
  4374. closeBtn.addEventListener("click", e => {
  4375. self.close();
  4376. }, true);
  4377. this.showSign = true;
  4378. logoBtn.addEventListener("click", e => {
  4379. logoBtn.classList.toggle("showSign");
  4380. self.showSign = !self.showSign;
  4381. getBody(document).classList.toggle("pagetual-picker");
  4382. }, true);
  4383. let moving = false;
  4384. let initX = 0, initY = 0, initPos = {x: 0, y: 0};
  4385. let moveHanlder = e => {
  4386. if (moving) {
  4387. frame.style.left = e.clientX - initX + "px";
  4388. frame.style.top = e.clientY - initY + "px";
  4389. e.stopPropagation();
  4390. e.preventDefault();
  4391. } else if(Math.abs(e.clientX - initPos.x) + Math.abs(e.clientY - initPos.y) > 20) {
  4392. moving = true;
  4393. }
  4394. };
  4395. let upHanlder = e => {
  4396. if (moving) {
  4397. moving = false;
  4398. } else {
  4399. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  4400. }
  4401. document.removeEventListener("mousemove", moveHanlder, true);
  4402. title.removeEventListener("mouseup", upHanlder, true);
  4403. e.stopPropagation();
  4404. e.preventDefault();
  4405. };
  4406. title.addEventListener("mousedown", e => {
  4407. initPos = {x: e.clientX, y: e.clientY};
  4408. initX = e.clientX - parseInt(getComputedStyle(frame).left);
  4409. initY = e.clientY - parseInt(getComputedStyle(frame).top);
  4410. document.addEventListener("mousemove", moveHanlder, true);
  4411. title.addEventListener("mouseup", upHanlder, true);
  4412. });
  4413. frame.addEventListener("mouseenter", e => {
  4414. if (!self.showSign || moving) return;
  4415. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  4416. self.checkInputSelector();
  4417. });
  4418. frame.addEventListener("mouseleave", e => {
  4419. if (!self.showSign) {
  4420. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  4421. self.clearSigns();
  4422. return;
  4423. }
  4424. if (moving) return;
  4425. getBody(document).appendChild(self.mainSignDiv);
  4426. self.clearSigns();
  4427. });
  4428. checkBtn.addEventListener("click", e => {
  4429. self.checkInputSelector();
  4430. if (this.selectorInput.value) _GM_setClipboard(this.selectorInput.value);
  4431. showTips(i18n("copied"));
  4432. });
  4433. xpath.addEventListener("click", e => {
  4434. if (!selectorInput.value) {
  4435. self.setSelectorDiv("");
  4436. return;
  4437. }
  4438. let element = getElement(selectorInput.value, document);
  4439. let selector = self.getSelectorFromEle(element);
  4440. self.setSelectorDiv(selector);
  4441. selectorInput.value = selector;
  4442. });
  4443. editBtn.addEventListener("click", e => {
  4444. rulesData.editTemp = self.getTempRule();
  4445. storage.setItem("rulesData", rulesData);
  4446. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  4447. });
  4448. editBtn.oncontextmenu = e => {
  4449. e.preventDefault();
  4450. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  4451. };
  4452. this.frame = frame;
  4453. this.xpath = xpath;
  4454. this.allpath = allpath;
  4455. this.selectorInput = selectorInput;
  4456. this.nextSwitchBtn = nextSwitchBtn;
  4457. this.autoScrollBtn = autoScrollBtn;
  4458. this.loadNow = loadNow;
  4459. this.tempRule = tempRule;
  4460. this.logoBtn = logoBtn;
  4461. let setTitleTimer;
  4462. this.moveHandler = e => {
  4463. if (!self.showSign || e.target === document) return;
  4464. let target = self.getTarget(e.target);
  4465. self.adjustSignDiv(self.mainSignDiv, target);
  4466. clearTimeout(setTitleTimer);
  4467. setTitleTimer = setTimeout(() => {
  4468. if (self.inPicker && target.hasAttributes()) {
  4469. let title = target.nodeName.toLowerCase() + "\n";
  4470. for (const attr of target.attributes) {
  4471. title += `【${attr.name}】${attr.value ? " ➡️ " + attr.value : ""}\n`;
  4472. }
  4473. getBody(document).title = title;
  4474. }
  4475. }, 100);
  4476. };
  4477. this.clickHandler = e => {
  4478. if (!self.showSign) return;
  4479. if (self.inPicker) {
  4480. e.stopPropagation();
  4481. e.preventDefault();
  4482. }
  4483. let target = self.getTarget(e.target);
  4484. let selector = self.getSelectorFromEle(target);
  4485. selectorInput.value = selector;
  4486. self.setSelectorDiv(selector);
  4487. };
  4488. }
  4489.  
  4490. getTempRule(detail) {
  4491. if (this.tempRule.value) {
  4492. try {
  4493. this.editTemp = JSON.parse(this.tempRule.value);
  4494. } catch (e) {
  4495. this.editTemp = null;
  4496. if (detail) {
  4497. let pos = e && e.message && e.message.match(/position (\d+)/);
  4498. if (pos) {
  4499. pos = parseInt(pos[1]);
  4500. this.tempRule.value = this.tempRule.value.slice(0, pos) + "➡️" + this.tempRule.value.slice(pos);
  4501. }
  4502. showTips(i18n("errorJson"));
  4503. return null;
  4504. }
  4505. }
  4506. }
  4507. if (!this.editTemp) {
  4508. if (ruleParser.curSiteRule.url && !ruleParser.curSiteRule.singleUrl) {
  4509. this.editTemp = ruleParser.curSiteRule;
  4510. } else {
  4511. this.editTemp = {
  4512. name: document.title,
  4513. url: "^" + (location.origin + location.pathname).replace(/[^\/]*$/, "").replace(/^https?/, "https?").replace(/\./g, "\\."),
  4514. example: location.href
  4515. };
  4516. }
  4517. delete this.editTemp.from;
  4518. delete this.editTemp.type;
  4519. delete this.editTemp.updatedAt;
  4520. }
  4521. if (this.selectorInput.value && !this.frame.classList.contains("showDetail")) {
  4522. this.editTemp.pageElement = this.selectorInput.value;
  4523. }
  4524. return this.editTemp;
  4525. }
  4526.  
  4527. getTarget(ele) {
  4528. while (ele.parentNode && (ele.offsetWidth === 0 || ele.offsetHeight === 0)) {
  4529. ele = ele.parentNode;
  4530. }
  4531. return ele;
  4532. }
  4533.  
  4534. close() {
  4535. this.clearSigns();
  4536. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  4537. if (this.mainSignDiv.parentNode) this.mainSignDiv.parentNode.removeChild(this.mainSignDiv);
  4538. getBody(document).classList.remove("pagetual-picker");
  4539. getBody(document).removeEventListener("mousemove", this.moveHandler, true);
  4540. getBody(document).removeEventListener("click", this.clickHandler, true);
  4541. getBody(document).title = "";
  4542. this.inPicker = false;
  4543. }
  4544.  
  4545. setImportant(ele, prop, value) {
  4546. ele.style.setProperty(prop, value, "important");
  4547. }
  4548.  
  4549. createSignDiv() {
  4550. let signDiv = document.createElement("div");
  4551. this.setImportant(signDiv, "position", "absolute");
  4552. this.setImportant(signDiv, "pointer-events", "none");
  4553. this.setImportant(signDiv, "z-index", "2147483646");
  4554. this.setImportant(signDiv, "background", "rgba(120, 170, 210, 0.6)");
  4555. this.setImportant(signDiv, "transition", "all 0.15s ease-out");
  4556. this.setImportant(signDiv, "box-shadow", "rgb(0 0 0) 0px 0px 3px 0px");
  4557. return signDiv;
  4558. }
  4559.  
  4560. adjustSignDiv(div, target) {
  4561. let rect = target.getBoundingClientRect();
  4562. this.setImportant(div, "width", rect.width + "px");
  4563. this.setImportant(div, "height", rect.height + "px");
  4564. this.setImportant(div, "left", rect.left + window.scrollX + "px");
  4565. this.setImportant(div, "top", rect.top + window.scrollY + "px");
  4566. }
  4567.  
  4568. getSelectorFromEle(ele) {
  4569. return this.xpath.checked ? createXPathFromElement(ele) : geneSelector(ele, true);
  4570. }
  4571.  
  4572. fillTempRuleTextarea() {
  4573. if (!this.frame.classList.contains("showDetail")) this.tempRule.value = JSON.stringify(this.getTempRule(), null, 4);
  4574. }
  4575.  
  4576. setSelectorDiv(selector) {
  4577. this.fillTempRuleTextarea();
  4578. let self = this;
  4579. this.allpath.innerHTML = createHTML("");
  4580. if (!selector) return;
  4581. if (this.xpath.checked) {
  4582. let span = document.createElement("span");
  4583. span.innerText = selector;
  4584. span.addEventListener("click", e => {
  4585. self.selectorInput.value = selector;
  4586. self.checkInputSelector();
  4587. }, true);
  4588. this.allpath.appendChild(span);
  4589. } else {
  4590. selector.split(">").forEach((item, index) => self.geneSelectorItem(item, index));
  4591. }
  4592. }
  4593.  
  4594. geneSelectorItem(item, index) {
  4595. let self = this;
  4596. item = item.trim();
  4597. if (!item) return;
  4598. if (index !== 0) {
  4599. let span = document.createElement("span");
  4600. span.innerText = " > ";
  4601. this.allpath.appendChild(span);
  4602. }
  4603. let span = document.createElement("span");
  4604. span.className = "path";
  4605. span.innerText = item;
  4606. span.addEventListener("click", e => {
  4607. let selector = "";
  4608. let target = e.target;
  4609. while (target) {
  4610. selector = target.innerText + selector;
  4611. target = target.previousElementSibling;
  4612. }
  4613. self.selectorInput.value = selector;
  4614. self.checkInputSelector();
  4615. if (self.checkedPath) {
  4616. self.checkedPath.classList.remove("checked");
  4617. }
  4618. span.classList.add("checked");
  4619. self.checkedPath = span;
  4620. }, true);
  4621. this.allpath.appendChild(span);
  4622. }
  4623.  
  4624. checkInputSelector() {
  4625. let self = this;
  4626. this.clearSigns();
  4627. if (!this.selectorInput.value) return;
  4628. let eles = getAllElements(this.selectorInput.value, document);
  4629. if (eles && eles.length > 0) {
  4630. eles.forEach(ele => {
  4631. let sign = self.createSignDiv();
  4632. getBody(document).appendChild(sign);
  4633. self.adjustSignDiv(sign, ele);
  4634. self.signList.push(sign);
  4635. });
  4636. this.fillTempRuleTextarea();
  4637. }
  4638. }
  4639.  
  4640. clearSigns() {
  4641. this.signList.forEach(sign => {
  4642. if (sign.parentNode) sign.parentNode.removeChild(sign);
  4643. });
  4644. this.signList = [];
  4645. }
  4646.  
  4647. start() {
  4648. this.init();
  4649. if (this.inPicker) return;
  4650. this.inPicker = true;
  4651. if (!this.styleEle || !this.styleEle.parentNode) {
  4652. this.styleEle = _GM_addStyle(this.cssText);
  4653. }
  4654. document.documentElement.appendChild(this.frame);
  4655. getBody(document).appendChild(this.mainSignDiv);
  4656. getBody(document).classList.add("pagetual-picker");
  4657.  
  4658. this.logoBtn.classList.remove("showSign");
  4659. this.showSign = true;
  4660.  
  4661. getBody(document).addEventListener("mousemove", this.moveHandler, true);
  4662. getBody(document).addEventListener("click", this.clickHandler, true);
  4663. this.xpath.checked = isXPath(ruleParser.curSiteRule.pageElement);
  4664. this.tempRule.value = "";
  4665. this.editTemp = null;
  4666. this.frame.classList.remove("showDetail");
  4667.  
  4668. this.loadNow.style.display = ruleParser.nextLinkHref ? "block" : "none";
  4669. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  4670. this.nextSwitchBtn.style.display = "block";
  4671. } else {
  4672. this.nextSwitchBtn.style.display = "none";
  4673. }
  4674. this.autoScrollBtn.innerText = i18n(autoScroll ? "disableAutoScroll" : "enableAutoScroll");
  4675.  
  4676. let pageElementSel = ruleParser.curSiteRule.pageElement || "";
  4677. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  4678. pageElementSel = pageElementSel[nextIndex < pageElementSel.length ? nextIndex : 0];
  4679. }
  4680. this.setSelectorDiv(pageElementSel);
  4681. }
  4682. }
  4683. const picker = new Picker();
  4684.  
  4685. var editor, editorChanged = false;
  4686. function createEdit() {
  4687. var options = {
  4688. mode: 'code',
  4689. modes: ['code', 'tree'],
  4690. templates: [
  4691. {
  4692. text: 'New site',
  4693. title: 'Insert a new site',
  4694. className: 'jsoneditor-type-object',
  4695. field: 'SiteTemplate',
  4696. value: {
  4697. 'name': 'Site name',
  4698. 'url': 'Site url'
  4699. }
  4700. }
  4701. ],
  4702. schema: {
  4703. "title": "Sites data",
  4704. "description": "Object containing site config",
  4705. "type": "array",
  4706. "items": {
  4707. "type": 'object',
  4708. "properties": {
  4709. "name": {
  4710. "title": "Site Name",
  4711. "description": "The site's name.",
  4712. "examples": [
  4713. "Google"
  4714. ],
  4715. "type": "string"
  4716. },
  4717. "url": {
  4718. "title": "Site Url",
  4719. "description": "The Regexp of site's url.",
  4720. "examples": [
  4721. "^https:\/\/yande\\.re\/"
  4722. ],
  4723. "type": "string"
  4724. }
  4725. },
  4726. "required": ["name", "url"]
  4727. }
  4728. },
  4729. onChange: () => {
  4730. editorChanged = true;
  4731. }
  4732. };
  4733. setTimeout(() => {
  4734. var container = document.getElementById("jsoneditor");
  4735. container.style.height = '800px';
  4736. container.innerHTML = "";
  4737. editor = new JSONEditor(container, options);
  4738. editor.set(ruleParser.customRules);
  4739. }, 500);
  4740. }
  4741.  
  4742. function checkGuidePage(href) {
  4743. if (guidePage.test(href)) {
  4744. if (typeof JSONEditor !== 'undefined') {
  4745. createEdit();
  4746. } else {
  4747. let checkEditorReady = setInterval(() => {
  4748. if (typeof JSONEditor !== 'undefined') {
  4749. createEdit();
  4750. clearInterval(checkEditorReady);
  4751. }
  4752. }, 100);
  4753. }
  4754. [].forEach.call(getBody(document).querySelectorAll('a'), ele => {
  4755. ele.target = "_blank";
  4756. });
  4757. return true;
  4758. }
  4759. return false;
  4760. }
  4761.  
  4762. function startAutoScroll() {
  4763. clearInterval(autoScrollInterval);
  4764. if (autoScroll <= 0) return;
  4765. autoScrollInterval = setInterval(() => {
  4766. if (isPause) return;
  4767. window.scroll(window.scrollX, window.scrollY + 1);
  4768. }, parseInt(1000 / autoScroll));
  4769. }
  4770.  
  4771. var inUpdate = false;
  4772. function initConfig(href) {
  4773. let isGuidePage = checkGuidePage(href);
  4774. if (!isGuidePage) {
  4775. if (href.indexOf("PagetualGuide") != -1) return true;
  4776. if (location.hostname === "pagetual.hoothin.com") return true;
  4777. }
  4778.  
  4779. var configCon, insertPos, click2import, importUrlPre;
  4780.  
  4781. let inConfig = isGuidePage;
  4782. if (!inConfig) {
  4783. for (let i = 0; i < configPage.length; i++) {
  4784. if (configPage[i] == location.href) {
  4785. inConfig = true;
  4786. break;
  4787. }
  4788. }
  4789. }
  4790. if (ruleImportUrlReg.test(href) || inConfig) {
  4791. let importing = false;
  4792. if (!inUpdate && rulesData.uninited) {
  4793. setTimeout(() => {
  4794. if (!inUpdate && !importing) showTips(i18n("firstAlert"));
  4795. }, 3000);
  4796. setTimeout(() => {
  4797. if (!inUpdate && !importing) showTips(i18n("firstAlert"));
  4798. }, 6000);
  4799. showTips(i18n("firstAlert"));
  4800. }
  4801. let defaultOption = document.querySelector('#discussion_rating_4');
  4802. if (defaultOption) defaultOption.checked = true;
  4803. let createImportBtn = (pre) => {
  4804. let importBtn = document.createElement("button");
  4805. importBtn.id = "pagetualImport";
  4806. importBtn.innerText = i18n("import");
  4807. importBtn.style.marginTop = "100px";
  4808. importBtn.style.float = "right";
  4809. importBtn.style.position = "relative";
  4810. importBtn.style.display = "block";
  4811. importBtn.style.fontSize = "20px";
  4812. importBtn.addEventListener("click", e => {
  4813. let parentNode = importBtn.parentNode;
  4814. if (!parentNode) return;
  4815. parentNode.removeChild(importBtn);
  4816. try {
  4817. let rules = parentNode.innerText.trim();
  4818. let isContent = /['"]name['"]/i.test(rules);
  4819. if (isContent) {
  4820. let ruleList = JSON.parse(`[${rules}]`);
  4821. for (let i in ruleList) {
  4822. let hasRule = false;
  4823. let r = ruleList[i];
  4824. for (let j in ruleParser.customRules) {
  4825. if (ruleParser.customRules[j].name == r.name) {
  4826. ruleParser.customRules[j] = r;
  4827. hasRule = true;
  4828. break;
  4829. }
  4830. }
  4831. if (!hasRule) ruleParser.customRules.push(r);
  4832. ruleParser.hpRules.unshift(r);
  4833. }
  4834. storage.setItem("customRules", ruleParser.customRules);
  4835. storage.setItem("hpRules", ruleParser.hpRules);
  4836. storage.setItem("smartRules", []);
  4837. showTips(i18n("importSucc"));
  4838. } else {
  4839. rules = rules.split("\n");
  4840. let diff = false;
  4841. for (let c = 0; c < rules.length; c++) {
  4842. let urlArr = rules[c].split("|"), url, type = 1;
  4843. if (urlArr.length == 1) {
  4844. url = urlArr[0].trim();
  4845. if (!/^http/.test(url)) {
  4846. showTips(i18n("errorWrongUrl"));
  4847. return;
  4848. }
  4849. } else if (urlArr.length == 2) {
  4850. type = urlArr[0].trim();
  4851. url = urlArr[1].trim();
  4852. if (!/^http/.test(url)) {
  4853. showTips(i18n("errorWrongUrl"));
  4854. return;
  4855. }
  4856. } else {
  4857. break;
  4858. }
  4859. let maxId = 1, hasUrl = false;
  4860. if (!rulesData.urls) {
  4861. rulesData.urls = [];
  4862. maxId = 1;
  4863. } else {
  4864. rulesData.urls.forEach(u => {
  4865. if (maxId < u.id) {
  4866. maxId = u.id;
  4867. }
  4868. if (u.url == url) {
  4869. hasUrl = true;
  4870. }
  4871. });
  4872. if (hasUrl) break;
  4873. }
  4874. diff = true;
  4875. if (!rulesData.sort) rulesData.sort = [1];
  4876. rulesData.urls.push({id: maxId + 1, url: url, type: type});
  4877. rulesData.sort.unshift(maxId + 1);
  4878. }
  4879. if (!diff) {
  4880. showTips(i18n("errorAlreadyExists"));
  4881. setTimeout(() => {
  4882. showTips(i18n("beginUpdate"), "", 30000);
  4883. updateRules(() => {
  4884. showTips(i18n("updateSucc"));
  4885. location.reload();
  4886. }, (rule, err) => {
  4887. showTips(`Failed to update ${rule.url} rules!`);
  4888. debug(err);
  4889. });
  4890. }, 500);
  4891. return;
  4892. }
  4893. storage.setItem("rulesData", rulesData);
  4894.  
  4895. if (rulesData.urls) ruleUrls = ruleUrls.concat(rulesData.urls);
  4896. if (rulesData.sort) {
  4897. let urls = [];
  4898. rulesData.sort.forEach(id => {
  4899. for (let s = 0; s < ruleUrls.length; s++) {
  4900. if (id == ruleUrls[s].id) {
  4901. urls.push(ruleUrls[s]);
  4902. break;
  4903. }
  4904. }
  4905. });
  4906. ruleUrls = urls;
  4907. }
  4908. showTips(i18n("beginUpdate"), "", 30000);
  4909. updateRules(() => {
  4910. showTips(i18n("updateSucc"));
  4911. location.reload();
  4912. }, (rule, err) => {
  4913. showTips(`Failed to update ${rule.url} rules!`);
  4914. debug(err);
  4915. });
  4916. importing = true;
  4917. }
  4918. } catch (e) {
  4919. _GM_notification(e.toString());
  4920. }
  4921. });
  4922. if (pre) {
  4923. let clientHeight = 35 - pre.clientHeight;
  4924. if (clientHeight > -20) clientHeight = -20;
  4925. importBtn.style.marginTop = `${clientHeight}px`;
  4926. pre.appendChild(importBtn);
  4927. }
  4928. return importBtn;
  4929. };
  4930. [].forEach.call(document.querySelectorAll('pre[name=pagetual],pre[name=user-content-pagetual]'), pre => {
  4931. let importBtn = createImportBtn(pre);
  4932. });
  4933. document.addEventListener("mouseover", e => {
  4934. if (compareNodeName(e.target, ["pre"])) {
  4935. let nameAttr = e.target.getAttribute("name");
  4936. if (nameAttr == "pagetual" || nameAttr == "user-content-pagetual") {
  4937. if (e.target.querySelector('#pagetualImport')) return;
  4938. let importBtn = createImportBtn(e.target);
  4939. }
  4940. }
  4941. });
  4942.  
  4943. if (inConfig) {
  4944. if (!inUpdate && _GM_info.script && _GM_info.script.version && _GM_info.script.version !== '1.0.0') {
  4945. let versionEle = document.querySelector('.markdown-body>h1[id],article>h1');
  4946. let latestVer = versionEle && versionEle.innerText.match(/\d[\d\.]+/)[0];
  4947. if (latestVer && latestVer != _GM_info.script.version) {
  4948. showTips(i18n('outOfDate'), "", 3000);
  4949. }
  4950. }
  4951. _GM_addStyle(`
  4952. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  4953. cursor: pointer;
  4954. user-select: none;
  4955. display: inline-block;
  4956. margin-right: 5px;
  4957. -moz-transition:color 0.3s ease, transform 0.3s;
  4958. -webkit-transition:color 0.3s ease, transform 0.3s;
  4959. transition:color 0.3s ease, transform 0.3s;
  4960. }
  4961. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  4962. color:red;
  4963. transform: scale(1.5);
  4964. -webkit-transform: scale(1.5);
  4965. }
  4966. .updateDate{
  4967. cursor: pointer;
  4968. user-select: none;
  4969. -moz-transition:color 0.3s ease, transform 0.3s;
  4970. -webkit-transition:color 0.3s ease, transform 0.3s;
  4971. transition:color 0.3s ease, transform 0.3s;
  4972. transform-origin: left;
  4973. -webkit-transform-origin: left;
  4974. }
  4975. .updateDate:hover{
  4976. color:red;
  4977. transform: scale(1.1);
  4978. -webkit-transform: scale(1.1);
  4979. }
  4980. input[type=number]::-webkit-inner-spin-button,
  4981. input[type=number]::-webkit-outer-spin-button {
  4982. -webkit-appearance: none;
  4983. margin: 0;
  4984. }
  4985. input[type=number] {
  4986. -moz-appearance:textfield;
  4987. }
  4988. table td>h3 {
  4989. margin: 16px!important;
  4990. }
  4991. #saveBtn {
  4992. width: 100%;
  4993. position: fixed;
  4994. z-index: 999;
  4995. bottom: 0px;
  4996. left: 0px;
  4997. font-size: x-large;
  4998. opacity: 0.8;
  4999. cursor: pointer;
  5000. -moz-transition:opacity 0.3s ease;
  5001. -webkit-transition:opacity 0.3s ease;
  5002. transition:opacity 0.3s ease;
  5003. }
  5004. #saveBtn:hover {
  5005. opacity: 1;
  5006. }
  5007. `);
  5008. click2import = document.querySelector("[name='user-content-click2import'],[name='click2import']");
  5009. if (click2import) click2import.innerText = i18n("click2ImportRule")
  5010. configCon = document.querySelector(".markdown-body,.theme-default-content");
  5011. if (!configCon) {
  5012. setTimeout(() => {
  5013. location.reload();
  5014. }, 1000);
  5015. return true;
  5016. }
  5017. insertPos = configCon.querySelector("hr,#jsoneditor");
  5018.  
  5019. importUrlPre = document.querySelector("pre[name='user-content-pagetual'],pre[name='pagetual']");
  5020. if (!rulesData.uninited) {
  5021. if (importUrlPre) importUrlPre.style.display = "none";
  5022. if (click2import) click2import.style.display = "none";
  5023. }
  5024. let otherconfig = document.querySelector("a[name='user-content-otherconfig'],a[name='otherconfig']");
  5025. if (otherconfig) otherconfig.parentNode.removeChild(otherconfig);
  5026. let rulesExample = document.querySelector("#user-content-rules-example+a,#rules-example>a");
  5027. if (rulesExample) {
  5028. rulesExample.innerText = i18n("rulesExample");
  5029. if (lang == "zh-CN") {
  5030. rulesExample.href = rulesExample.href.replace("en", "cn");
  5031. } else if (lang == "zh-TW" || lang == "zh-HK") {
  5032. rulesExample.href = rulesExample.href.replace("/en", "");
  5033. }
  5034. }
  5035. } else return false;
  5036. } else return false;
  5037. class Rulebar {
  5038. init(ruleUrl) {
  5039. let id = ruleUrl.id;
  5040. this.ruleUrl = ruleUrl;
  5041. this.item = document.createElement("p");
  5042. this.item.dataset.id = id;
  5043. let url = document.createElement("a");
  5044. url.href = ruleUrl.url;
  5045. url.innerHTML = ruleUrl.url;
  5046. url.title = ruleUrl.url;
  5047. let up = document.createElement("span");
  5048. up.innerHTML = "↑ ";
  5049. up.title = i18n("sortTitle");
  5050. let down = document.createElement("span");
  5051. down.innerHTML = "↓ ";
  5052. down.title = i18n("sortTitle");
  5053. let del = document.createElement("span");
  5054. del.innerHTML = "× ";
  5055. up.onclick = e => {
  5056. this.moveUp();
  5057. };
  5058. down.onclick = e => {
  5059. this.moveDown();
  5060. };
  5061. del.onclick = e => {
  5062. this.del();
  5063. };
  5064. this.item.appendChild(up);
  5065. this.item.appendChild(down);
  5066. this.item.appendChild(del);
  5067. this.item.appendChild(url);
  5068. if (ruleParser.rules) {
  5069. url.style.maxWidth = "calc(100% - 140px)";
  5070. url.style.overflow = "hidden";
  5071. url.style.display = "inline-block";
  5072. url.style.textOverflow = "ellipsis";
  5073. url.style.verticalAlign = "bottom";
  5074. url.style.whiteSpace = "nowrap";
  5075. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == id ? 1 : 0), 0);
  5076. let idSpan = document.createElement("span");
  5077. idSpan.style.float = "right";
  5078. idSpan.innerHTML = `[rules: ${rulesLength}]`;
  5079. this.item.appendChild(idSpan);
  5080. this.idSpan = idSpan;
  5081. }
  5082. configCon.insertBefore(this.item, insertPos);
  5083. }
  5084. updateNum() {
  5085. if (ruleParser.rules) {
  5086. let rulesLength = ruleParser.rules.reduce((acc, cur) => acc + (cur.from == this.item.dataset.id ? 1 : 0), 0);
  5087. this.idSpan.innerHTML = `[rules: ${rulesLength}]`;
  5088. }
  5089. }
  5090. saveSort() {
  5091. let sort = [];
  5092. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i => {
  5093. sort.push(i.dataset.id);
  5094. });
  5095. rulesData.sort = sort;
  5096. let urls = [];
  5097. sort.forEach(id => {
  5098. for (let s = 0; s < ruleUrls.length; s++) {
  5099. if (id == ruleUrls[s].id) {
  5100. urls.push(ruleUrls[s]);
  5101. break;
  5102. }
  5103. }
  5104. });
  5105. ruleUrls = urls;
  5106. storage.setItem("rulesData", rulesData);
  5107. }
  5108. moveUp() {
  5109. let preE = this.item.previousElementSibling;
  5110. if (compareNodeName(preE, ["p"]) && preE.children.length > 1) {
  5111. this.item.parentNode.insertBefore(this.item, preE);
  5112. this.saveSort();
  5113. }
  5114. }
  5115. moveDown() {
  5116. let nextE = this.item.nextElementSibling;
  5117. if (compareNodeName(nextE, ["p"]) && nextE.children.length > 1) {
  5118. this.item.parentNode.insertBefore(nextE, this.item);
  5119. this.saveSort();
  5120. }
  5121. }
  5122. del() {
  5123. if (this.ruleUrl.id < 2) {
  5124. showTips(i18n("cantDel"));
  5125. } else if (window.confirm(i18n("confirmDel"))) {
  5126. for (let u = 0; u < rulesData.urls.length; u++) {
  5127. if (this.ruleUrl.id == rulesData.urls[u].id) {
  5128. rulesData.urls.splice(u, 1);
  5129. break;
  5130. }
  5131. }
  5132. for (let u = 0; u < ruleUrls.length; u++) {
  5133. if (this.ruleUrl.id == ruleUrls[u].id) {
  5134. ruleUrls.splice(u, 1);
  5135. break;
  5136. }
  5137. }
  5138. for (let u = 0; u < rulesData.sort.length; u++) {
  5139. if (this.ruleUrl.id == rulesData.sort[u]) {
  5140. rulesData.sort.splice(u, 1);
  5141. break;
  5142. }
  5143. }
  5144. storage.setItem("rulesData", rulesData);
  5145. ruleParser.rules = ruleParser.rules.filter(item => {return item.from != this.ruleUrl.id});
  5146. storage.setItem("rules", ruleParser.rules);
  5147. this.item.parentNode.removeChild(this.item);
  5148. //location.reload();
  5149. }
  5150. }
  5151. }
  5152. let langSelect = document.createElement("select");
  5153. langSelect.style.float = "right";
  5154. langSelect.style.position = "relative";
  5155. langSelect.style.zIndex = "1";
  5156. let option = document.createElement("option");
  5157. option.value = "";
  5158. option.innerText = "Language";
  5159. langSelect.appendChild(option);
  5160. for (let key in langList) {
  5161. let option = document.createElement("option");
  5162. option.value = key;
  5163. option.innerText = langList[key];
  5164. langSelect.appendChild(option);
  5165. }
  5166. langSelect.value = rulesData.lang || "";
  5167. configCon.insertBefore(langSelect, insertPos);
  5168.  
  5169. let updateP = document.createElement("p"), i = 0;
  5170. let now = new Date().getTime();
  5171.  
  5172.  
  5173. let pastDate = (new Date(updateDate)).toString(), passStr;
  5174. let passTime = (now - updateDate) / 1000;
  5175. if (isNaN(passTime)) {
  5176. passStr = i18n("firstUpdate");
  5177. } else {
  5178. if (passTime < 60) {
  5179. passStr = i18n("passSec", parseInt(passTime));
  5180. } else if (passTime < 60 * 60) {
  5181. passStr = i18n("passMin", parseInt(passTime / 60));
  5182. } else if (passTime < 60 * 60 * 24) {
  5183. passStr = i18n("passHour", parseInt(passTime / 3600));
  5184. } else {
  5185. passStr = i18n("passDay", parseInt(passTime / 86400));
  5186. }
  5187. passStr += " 🖱 " + i18n("click2update");
  5188. }
  5189.  
  5190. let rulebarList = [], updateFail = false;
  5191. updateP.className = "updateDate";
  5192. updateP.innerHTML = passStr;
  5193. updateP.title = i18n("update") + " - " + pastDate;
  5194. configCon.insertBefore(updateP, insertPos);
  5195. if (ruleUrls) {
  5196. ruleUrls.forEach(ruleUrl => {
  5197. let rulebar = new Rulebar();
  5198. rulebar.init(ruleUrl);
  5199. rulebarList.push(rulebar);
  5200. });
  5201. }
  5202. let customUrlsTitle = document.createElement("h2");
  5203. customUrlsTitle.innerHTML = i18n("customUrls");
  5204. configCon.insertBefore(customUrlsTitle, insertPos);
  5205. let customUrlsInput = document.createElement("textarea");
  5206. customUrlsInput.style.width = "100%";
  5207. customUrlsInput.placeholder = "http://wedata.net/databases/AutoPagerize/items_all.json \nhttps://hoothin.github.io/UserScripts/Pagetual/pagetualRules.json";
  5208. customUrlsInput.spellcheck = false;
  5209. configCon.insertBefore(customUrlsInput, insertPos);
  5210.  
  5211. let btns = document.createElement("div");
  5212. btns.style.display = "flex";
  5213. configCon.insertBefore(btns, insertPos);
  5214. let upBtnImg = document.createElement("div");
  5215. upBtnImg.style.width = "33%";
  5216. let upBtnImgTitle = document.createElement("h2");
  5217. upBtnImgTitle.style.whiteSpace = "nowrap";
  5218. upBtnImgTitle.style.overflow = "auto";
  5219. upBtnImgTitle.innerHTML = i18n("upBtnImg");
  5220. upBtnImg.appendChild(upBtnImgTitle);
  5221. let upBtnImgInput = document.createElement("input");
  5222. upBtnImgInput.style.width = "100%";
  5223. upBtnImgInput.placeholder = "data:image/png;base64,UpBtn";
  5224. upBtnImgInput.value = rulesData.upBtnImg || '';
  5225. upBtnImgInput.spellcheck = false;
  5226. upBtnImg.appendChild(upBtnImgInput);
  5227. btns.appendChild(upBtnImg);
  5228.  
  5229. let downBtnImg = document.createElement("div");
  5230. downBtnImg.style.width = "33%";
  5231. let downBtnImgTitle = document.createElement("h2");
  5232. downBtnImgTitle.style.whiteSpace = "nowrap";
  5233. downBtnImgTitle.style.overflow = "auto";
  5234. downBtnImgTitle.innerHTML = i18n("downBtnImg");
  5235. downBtnImg.appendChild(downBtnImgTitle);
  5236. let downBtnImgInput = document.createElement("input");
  5237. downBtnImgInput.style.width = "100%";
  5238. downBtnImgInput.placeholder = "data:image/png;base64,DownBtn";
  5239. downBtnImgInput.value = rulesData.downBtnImg || '';
  5240. downBtnImgInput.spellcheck = false;
  5241. downBtnImg.appendChild(downBtnImgInput);
  5242. btns.appendChild(downBtnImg);
  5243.  
  5244. let sideControllerIconDiv = document.createElement("div");
  5245. sideControllerIconDiv.style.width = "33%";
  5246. let sideControllerIconTitle = document.createElement("h2");
  5247. sideControllerIconTitle.style.whiteSpace = "nowrap";
  5248. sideControllerIconTitle.style.overflow = "auto";
  5249. sideControllerIconTitle.innerHTML = i18n("sideControllerIcon");
  5250. sideControllerIconDiv.appendChild(sideControllerIconTitle);
  5251. let sideControllerIconInput = document.createElement("input");
  5252. sideControllerIconInput.style.width = "100%";
  5253. sideControllerIconInput.placeholder = "🤍";
  5254. sideControllerIconInput.value = rulesData.sideControllerIcon || '';
  5255. sideControllerIconInput.spellcheck = false;
  5256. sideControllerIconDiv.appendChild(sideControllerIconInput);
  5257. btns.appendChild(sideControllerIconDiv);
  5258.  
  5259. let otherBtns = document.createElement("div");
  5260. otherBtns.style.display = "flex";
  5261. configCon.insertBefore(otherBtns, insertPos);
  5262. let loadingText = document.createElement("div");
  5263. loadingText.style.width = "100%";
  5264. let loadingTextTitle = document.createElement("h2");
  5265. loadingTextTitle.style.whiteSpace = "nowrap";
  5266. loadingTextTitle.style.overflow = "auto";
  5267. loadingTextTitle.innerHTML = i18n("loadingTextTitle");
  5268. loadingText.appendChild(loadingTextTitle);
  5269. let loadingTextInput = document.createElement("input");
  5270. loadingTextInput.value = rulesData.loadingText || '';
  5271. loadingTextInput.placeholder = i18n("loadingText");
  5272. loadingTextInput.style.width = "100%";
  5273. loadingTextInput.style.margin = "0";
  5274. loadingTextInput.spellcheck = false;
  5275. loadingText.appendChild(loadingTextInput);
  5276. otherBtns.appendChild(loadingText);
  5277.  
  5278. let opacity = document.createElement("div");
  5279. let opacityTitle = document.createElement("h2");
  5280. opacityTitle.style.whiteSpace = "nowrap";
  5281. opacityTitle.style.overflow = "visible";
  5282. opacityTitle.innerHTML = i18n("opacity");
  5283. opacity.appendChild(opacityTitle);
  5284. let opacityInput = document.createElement("input");
  5285. opacityInput.value = rulesData.opacity * 100;
  5286. opacityInput.type = "number";
  5287. opacityInput.min = 0;
  5288. opacityInput.max = 100;
  5289. opacityInput.style.width = "110px";
  5290. opacityInput.style.margin = "0";
  5291. opacityInput.placeholder = i18n("opacityPlaceholder");
  5292. opacityInput.spellcheck = false;
  5293. opacityInput.oninput = e => {
  5294. if (opacityInput.value > 100) opacityInput.value = 100;
  5295. else if (opacityInput.value < 0) opacityInput.value = 0;
  5296. };
  5297. opacity.appendChild(opacityInput);
  5298. otherBtns.appendChild(opacity);
  5299.  
  5300. let pageElementCss = document.createElement("div");
  5301. pageElementCss.style.marginBottom = "30px";
  5302. let pageElementCssTitle = document.createElement("h2");
  5303. pageElementCssTitle.innerHTML = i18n("pageElementCss");
  5304. pageElementCss.appendChild(pageElementCssTitle);
  5305. let pageElementCssInput = document.createElement("input");
  5306. pageElementCssInput.value = rulesData.pageElementCss || '';
  5307. pageElementCssInput.style.width = "100%";
  5308. pageElementCssInput.style.margin = "0";
  5309. pageElementCssInput.placeholder = "font-size: xx-large;";
  5310. pageElementCssInput.spellcheck = false;
  5311. pageElementCss.appendChild(pageElementCssInput);
  5312. configCon.insertBefore(pageElementCss, insertPos);
  5313.  
  5314. let customCss = document.createElement("div");
  5315. customCss.style.marginBottom = "50px";
  5316. let customCssTitle = document.createElement("h2");
  5317. customCssTitle.innerHTML = i18n("customCss");
  5318. customCss.appendChild(customCssTitle);
  5319. let customCssInput = document.createElement("textarea");
  5320. customCssInput.value = rulesData.customCss || '';
  5321. customCssInput.style.width = "100%";
  5322. customCssInput.style.margin = "0";
  5323. customCssInput.placeholder = ".pagetual {\n}";
  5324. customCssInput.spellcheck = false;
  5325. customCss.appendChild(customCssInput);
  5326. configCon.insertBefore(customCss, insertPos);
  5327.  
  5328. let configTable = document.createElement("table");
  5329. configTable.style.width = "100%";
  5330. let configTbody = document.createElement("tbody");
  5331. configTbody.style.width = "99%";
  5332. configTbody.style.display = "inline-table";
  5333. configTable.appendChild(configTbody);
  5334. configCon.insertBefore(configTable, insertPos);
  5335. function createCheckbox(innerText, val, tag, parentCheck, otherType) {
  5336. if (typeof val == 'undefined') val = "";
  5337. let title = document.createElement(tag || "h3");
  5338. title.innerHTML = innerText;
  5339. title.style.overflowWrap = "normal";
  5340. let input = document.createElement("input");
  5341. if (otherType === 'key') {
  5342. input.type = 'text';
  5343. input.setAttribute('readOnly', 'readonly');
  5344. input.addEventListener("keydown", e => {
  5345. if (e.key === 'Escape' || e.key === 'Backspace') input.value = '';
  5346. else input.value = e.key;
  5347. e.stopPropagation();
  5348. e.preventDefault();
  5349. });
  5350. } else {
  5351. input.type = otherType || "checkbox";
  5352. }
  5353. input.style.width = "30px";
  5354. input.style.height = "20px";
  5355. input.style.float = "left";
  5356. input.style.margin = "5px";
  5357. input.value = val;
  5358. input.checked = val;
  5359. let td = document.createElement("td");
  5360. td.appendChild(input);
  5361. if (parentCheck) {
  5362. title.style.margin = "0";
  5363. td.appendChild(title);
  5364. let parent = parentCheck.parentNode.nextElementSibling;
  5365. let tr = parent.querySelector("tr");
  5366. if (!tr) {
  5367. tr = document.createElement("tr");
  5368. parent.appendChild(tr);
  5369. }
  5370. tr.appendChild(td);
  5371. if (!parentCheck.checked) {
  5372. td.style.display = "none";
  5373. }
  5374. parentCheck.addEventListener("click", e => {
  5375. td.style.display = parentCheck.checked ? "" : "none";
  5376. });
  5377. } else {
  5378. let tr = document.createElement("tr");
  5379. tr.appendChild(td);
  5380. td = document.createElement("td");
  5381. td.appendChild(title);
  5382. tr.appendChild(td);
  5383. configTable.children[0].appendChild(tr);
  5384. }
  5385. let xNodePos = innerText.indexOf('【X】');
  5386. if (xNodePos !== -1) {
  5387. input.style.float = "";
  5388. let xNode = title.firstChild.splitText(xNodePos);
  5389. xNode.splitText(3);
  5390. xNode.parentNode.replaceChild(input, xNode);
  5391. }
  5392. return input;
  5393. }
  5394.  
  5395. let setConfigPageInput = createCheckbox(i18n("setConfigPage"), false);
  5396. let enableWhiteListInput = createCheckbox(i18n("autoRun"), rulesData.enableWhiteList != true);
  5397. let sideControllerInput = createCheckbox(i18n("sideController"), rulesData.sideController);
  5398. let enableDebugInput = createCheckbox(i18n("enableDebug"), rulesData.enableDebug != false);
  5399. let enableHistoryInput = createCheckbox(i18n("enableHistory"), rulesData.enableHistory === true);
  5400. let enableHistoryAfterInsertInput = createCheckbox(i18n("enableHistoryAfterInsert"), rulesData.enableHistoryAfterInsert === true, "h4", enableHistoryInput);
  5401. let openInNewTabInput = createCheckbox(i18n("openInNewTab"), rulesData.openInNewTab != false);
  5402. let hidePageBarInput = createCheckbox(i18n("hideBarTips"), rulesData.opacity == 0);
  5403. let hidePageBarArrowInput = createCheckbox(i18n("hideBarArrow"), rulesData.hideBarArrow);
  5404. let hideLoadingIconInput = createCheckbox(i18n("hideLoadingIcon"), rulesData.hideLoadingIcon != false);
  5405. let initRunInput = createCheckbox(i18n("initRun"), rulesData.initRun != false);
  5406. let autoLoadNumInput = createCheckbox(i18n("autoLoadNum"), rulesData.autoLoadNum, "h4", initRunInput, "number");
  5407. let preloadInput = createCheckbox(i18n("preload"), rulesData.preload != false);
  5408. let rateInput = createCheckbox(i18n("turnRate"), rulesData.rate, "h4", preloadInput, "number");
  5409. let dbClick2StopInput = createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  5410. let manualModeInput = createCheckbox(i18n("manualMode"), rulesData.manualMode);
  5411. let clickModeInput = createCheckbox(i18n("clickMode"), rulesData.clickMode);
  5412. let pageBarMenuInput = createCheckbox(i18n("pageBarMenu"), rulesData.pageBarMenu != false);
  5413. let arrowToScrollInput = createCheckbox(i18n("arrowToScroll"), rulesData.arrowToScroll);
  5414. let contentVisibilityInput = createCheckbox(i18n("contentVisibility"), rulesData.contentVisibility);
  5415. let wedata2githubInput = createCheckbox(i18n("wedata2github"), rulesData.wedata2github);
  5416. let customFirstInput = createCheckbox(i18n("customFirst"), rulesData.customFirst);
  5417. let lastPageTipsInput = createCheckbox(i18n("lastPageTips"), rulesData.lastPageTips);
  5418.  
  5419. let hideBarInput = createCheckbox(i18n("hideBar"), rulesData.hideBar && !rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  5420. hideBarInput.name = 'hideBar';
  5421. let hideBarButNoStopInput = createCheckbox(i18n("hideBarButNoStop"), rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  5422. hideBarButNoStopInput.name = 'hideBar';
  5423. hideBarInput.addEventListener('mouseup', e => {
  5424. if (hideBarInput.checked) {
  5425. setTimeout(() => {hideBarInput.checked = false}, 0);
  5426. }
  5427. });
  5428. hideBarButNoStopInput.addEventListener('mouseup', e => {
  5429. if (hideBarButNoStopInput.checked) {
  5430. setTimeout(() => {hideBarButNoStopInput.checked = false}, 0);
  5431. }
  5432. });
  5433. hidePageBarInput.addEventListener('click', e => {
  5434. opacityInput.value = hidePageBarInput.checked ? 0 : 100;
  5435. });
  5436.  
  5437. let dbClick2StopCtrlInput = createCheckbox(i18n("dbClick2StopCtrl"), rulesData.dbClick2StopCtrl, "h4", dbClick2StopInput);
  5438. let dbClick2StopAltInput = createCheckbox(i18n("dbClick2StopAlt"), rulesData.dbClick2StopAlt, "h4", dbClick2StopInput);
  5439. let dbClick2StopShiftInput = createCheckbox(i18n("dbClick2StopShift"), rulesData.dbClick2StopShift, "h4", dbClick2StopInput);
  5440. let dbClick2StopMetaInput = createCheckbox(i18n("dbClick2StopMeta"), rulesData.dbClick2StopMeta, "h4", dbClick2StopInput);
  5441. let dbClick2StopKeyInput = createCheckbox(i18n("dbClick2StopKey"), rulesData.dbClick2StopKey, "h4", dbClick2StopInput, "key");
  5442.  
  5443. let otherConfigPage = rulesData.configPage ? rulesData.configPage != location.href : configPage[0] != location.href;
  5444. if (!otherConfigPage) {
  5445. setConfigPageInput.parentNode.parentNode.style.display = "none";
  5446. }
  5447.  
  5448. updateP.onclick = e => {
  5449. updateFail = false;
  5450. ruleParser.rules = [];
  5451. showTips(i18n("beginUpdate"), "", 30000);
  5452. updateRules(() => {
  5453. if (!updateFail) {
  5454. showTips(i18n("updateSucc"));
  5455. if (importUrlPre) importUrlPre.style.display = "none";
  5456. if (click2import) click2import.style.display = "none";
  5457. }
  5458. updateP.innerHTML = i18n("passSec", 0);
  5459. updateP.title = i18n("update");
  5460. rulebarList.forEach(rulebar => {
  5461. rulebar.updateNum();
  5462. });
  5463. }, (rule, err) => {
  5464. if (rule.id == 1) {
  5465. showTips(`Failed to update wedata rules! Try to switch to wedata mirror!`);
  5466. wedata2githubInput.scrollIntoView({ behavior: "smooth" });
  5467. } else {
  5468. showTips(`Failed to update ${rule.url} rules!`);
  5469. }
  5470. debug(err);
  5471. updateFail = true;
  5472. });
  5473. };
  5474. let customRulesTitle = document.createElement("h2");
  5475. 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');
  5476. configCon.insertBefore(customRulesTitle, insertPos);
  5477. let customRulesInput = document.createElement("textarea");
  5478. customRulesInput.spellcheck = false;
  5479. configCon.insertBefore(customRulesInput, insertPos);
  5480. if (rulesData.editTemp) {
  5481. if (!ruleParser.customRules) {
  5482. ruleParser.customRules = [];
  5483. }
  5484. for (let i in ruleParser.customRules) {
  5485. if (ruleParser.customRules[i].url == rulesData.editTemp.url) {
  5486. ruleParser.customRules.splice(i, 1);
  5487. break;
  5488. }
  5489. }
  5490. ruleParser.customRules.unshift(rulesData.editTemp);
  5491. rulesData.editTemp = null;
  5492. storage.setItem("rulesData", rulesData);
  5493. customRulesInput.previousElementSibling.scrollIntoView();
  5494. }
  5495. customRulesInput.style.width = "100%";
  5496. customRulesInput.style.height = "800px";
  5497. 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]`;
  5498. let preCustom = getFormatJSON(ruleParser.customRules);
  5499. customRulesInput.value = preCustom;
  5500. if (isGuidePage) customRulesInput.style.display = "none";
  5501. let blacklistInput = document.createElement("textarea");
  5502. blacklistInput.style.width = "100%";
  5503. blacklistInput.style.height = "500px";
  5504. blacklistInput.style.display = "none";
  5505. blacklistInput.spellcheck = false;
  5506. 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";
  5507. blacklistInput.value = rulesData.blacklist ? rulesData.blacklist.join("\n") : "";
  5508. let blacklistBtn = document.createElement("button");
  5509. blacklistBtn.innerText = i18n("editBlacklist");
  5510. blacklistBtn.style.width = "100%";
  5511. blacklistBtn.onclick = e => {
  5512. blacklistInput.style.display = blacklistInput.style.display == "none" ? "" : "none";
  5513. };
  5514. configCon.insertBefore(blacklistBtn, insertPos);
  5515. configCon.insertBefore(blacklistInput, insertPos);
  5516. let saveBtn = document.createElement("button");
  5517. saveBtn.innerHTML = i18n("save");
  5518. saveBtn.id = "saveBtn";
  5519. configCon.insertBefore(saveBtn, insertPos);
  5520. saveBtn.onclick = e => {
  5521. try {
  5522. let customRules;
  5523. if (editor) {
  5524. if (editorChanged) {
  5525. editorChanged = false;
  5526. storage.setItem("hpRules", []);
  5527. storage.setItem("smartRules", []);
  5528. }
  5529. customRules = editor.get();
  5530. if (!customRules) {
  5531. customRules = "";
  5532. } else {
  5533. if (Array && Array.isArray && !Array.isArray(customRules)) {
  5534. showTips(i18n("errorRulesMustBeArray"));
  5535. return;
  5536. }
  5537. }
  5538. } else {
  5539. if (customRulesInput.value != preCustom) {
  5540. storage.setItem("hpRules", []);
  5541. storage.setItem("smartRules", []);
  5542. }
  5543. if (customRulesInput.value == "") {
  5544. customRules = "";
  5545. } else {
  5546. customRules = JSON.parse(customRulesInput.value);
  5547. if (Array && Array.isArray && !Array.isArray(customRules)) {
  5548. showTips(i18n("errorRulesMustBeArray"));
  5549. return;
  5550. }
  5551. customRulesInput.value = JSON.stringify(customRules, null, 4);
  5552. }
  5553. }
  5554. debug(customRules);
  5555. storage.setItem("customRules", customRules);
  5556. } catch(e) {
  5557. debug(e);
  5558. let pos = e && e.message && e.message.match(/position (\d+)/);
  5559. if (pos && !editor) {
  5560. pos = parseInt(pos[1]);
  5561. customRulesInput.value = customRulesInput.value.slice(0, pos) + "➡️" + customRulesInput.value.slice(pos);
  5562. }
  5563. showTips(i18n("errorJson"));
  5564. return;
  5565. }
  5566. rulesData.lang = langSelect.value || "";
  5567. if (setConfigPageInput.checked) rulesData.configPage = location.href;
  5568. rulesData.wedata2github = wedata2githubInput.checked;
  5569. let opacity = parseInt(opacityInput.value) || 0;
  5570. if (opacity > 100) opacity = 100;
  5571. else if (opacity < 0) opacity = 0;
  5572. rulesData.opacity = opacity / 100;
  5573. rulesData.blacklist = blacklistInput.value ? blacklistInput.value.trim().split("\n") : "";
  5574. rulesData.hideBar = hideBarInput.checked;
  5575. rulesData.hideBarButNoStop = hideBarButNoStopInput.checked;
  5576. rulesData.dbClick2Stop = dbClick2StopInput.checked;
  5577. rulesData.enableWhiteList = !enableWhiteListInput.checked;
  5578. rulesData.enableDebug = enableDebugInput.checked;
  5579. rulesData.enableHistory = enableHistoryInput.checked;
  5580. rulesData.enableHistoryAfterInsert = enableHistoryAfterInsertInput.checked;
  5581. rulesData.openInNewTab = openInNewTabInput.checked;
  5582. rulesData.hideLoadingIcon = hideLoadingIconInput.checked;
  5583. rulesData.hideBarArrow = hidePageBarArrowInput.checked;
  5584. rulesData.customFirst = customFirstInput.checked;
  5585. rulesData.lastPageTips = lastPageTipsInput.checked;
  5586. rulesData.initRun = initRunInput.checked;
  5587. rulesData.autoLoadNum = autoLoadNumInput.value !== "0" ? autoLoadNumInput.value : '';
  5588. rulesData.rate = parseInt(rateInput.value) || 1;
  5589. rulesData.preload = preloadInput.checked;
  5590. rulesData.manualMode = manualModeInput.checked;
  5591. rulesData.clickMode = clickModeInput.checked;
  5592. rulesData.pageBarMenu = pageBarMenuInput.checked;
  5593. rulesData.arrowToScroll = arrowToScrollInput.checked;
  5594. rulesData.contentVisibility = contentVisibilityInput.checked;
  5595. if (rulesData.sideController != sideControllerInput.checked) {
  5596. rulesData.sideControllerPos = false;
  5597. }
  5598. rulesData.sideController = sideControllerInput.checked;
  5599. rulesData.pageElementCss = pageElementCssInput.value;
  5600. rulesData.customCss = customCssInput.value;
  5601. rulesData.upBtnImg = upBtnImgInput.value;
  5602. rulesData.downBtnImg = downBtnImgInput.value;
  5603. rulesData.sideControllerIcon = sideControllerIconInput.value;
  5604. rulesData.loadingText = loadingTextInput.value;
  5605. rulesData.dbClick2StopCtrl = dbClick2StopCtrlInput.checked;
  5606. rulesData.dbClick2StopAlt = dbClick2StopAltInput.checked;
  5607. rulesData.dbClick2StopShift = dbClick2StopShiftInput.checked;
  5608. rulesData.dbClick2StopMeta = dbClick2StopMetaInput.checked;
  5609. rulesData.dbClick2StopKey = dbClick2StopKeyInput.value;
  5610. storage.setItem("rulesData", rulesData);
  5611. let customUrls = customUrlsInput.value.trim();
  5612. if (customUrls) {
  5613. customUrls = customUrls.split(/\n/);
  5614. for (let c = 0; c < customUrls.length; c++) {
  5615. let url;
  5616. if (/^0\s*\|/.test(customUrls[c])) {
  5617. url = customUrls[c].replace(/^0\s*\|\s*/, "").trim();
  5618. if (!/^http/.test(url)) {
  5619. showTips(i18n("errorWrongUrl"));
  5620. return;
  5621. }
  5622. } else {
  5623. url = customUrls[c].trim();
  5624. if (!/^http/.test(url)) {
  5625. showTips(i18n("errorWrongUrl"));
  5626. return;
  5627. }
  5628. }
  5629. let maxId = 1, hasUrl = false;
  5630. if (!rulesData.urls) {
  5631. rulesData.urls = [];
  5632. }
  5633. ruleUrls.forEach(u => {
  5634. if (maxId < u.id) {
  5635. maxId = u.id;
  5636. }
  5637. if (u.url == url) {
  5638. hasUrl = true;
  5639. }
  5640. });
  5641. if (hasUrl) break;
  5642. if (!rulesData.sort) rulesData.sort = [1];
  5643. rulesData.urls.push({id: maxId + 1, url: url});
  5644. rulesData.sort.push(maxId + 1);
  5645. storage.setItem("rulesData", rulesData);
  5646. }
  5647. }
  5648. showTips(i18n("settingsSaved"));
  5649. };
  5650. return true;
  5651. }
  5652.  
  5653. function updateRules (success, fail, keepCache) {
  5654. if (!storage.supportCrossSave()) {
  5655. fail({url:''}, "Not support cross storage");
  5656. showTips("Current platform do not support cross storage!");
  5657. return;
  5658. }
  5659. if (inUpdate) return;
  5660. inUpdate = true;
  5661. let ruleIndex = ruleUrls.length - 1;
  5662. if (!keepCache) {
  5663. storage.setItem("hpRules", []);
  5664. storage.setItem("smartRules", []);
  5665. }
  5666. let allOk = true;
  5667. function addNextRule() {
  5668. if (ruleIndex < 0) {
  5669. let now = new Date().getTime();
  5670. storage.setItem("ruleLastUpdate", now);
  5671. storage.setItem("rules", ruleParser.rules);
  5672. inUpdate = false;
  5673. if (allOk) {
  5674. rulesData.uninited = false;
  5675. storage.setItem("rulesData", rulesData);
  5676. }
  5677. success();
  5678. } else {
  5679. let rule = ruleUrls[ruleIndex--];
  5680. ruleParser.addRuleByUrl(rule.url, rule.id, (json, err) => {
  5681. if (!json) {
  5682. allOk = false;
  5683. fail(rule, err);
  5684. }
  5685. addNextRule();
  5686. })
  5687. }
  5688. }
  5689. addNextRule();
  5690. }
  5691.  
  5692. function objIsArr(obj) {
  5693. return obj &&
  5694. typeof obj === 'object' &&
  5695. typeof obj.length === 'number' &&
  5696. !(obj.propertyIsEnumerable('length'));
  5697. }
  5698.  
  5699. function isVisible(el, win) {
  5700. if(!el || !el.offsetParent)return false;
  5701. var loopable = true,
  5702. visible = el.nodeName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  5703. while(loopable && visible) {
  5704. el = el.parentNode;
  5705.  
  5706. if(el && !compareNodeName(el, ["body"])) {
  5707. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  5708. }else {
  5709. loopable = false;
  5710. }
  5711. }
  5712. return visible;
  5713. }
  5714.  
  5715. function getElementTop(ele) {
  5716. if (!ele) return 0;
  5717. if (ele.getBoundingClientRect) {
  5718. return ele.getBoundingClientRect().top + document.documentElement.scrollTop;
  5719. }
  5720. var actualTop = ele.offsetTop;
  5721. var current = ele.offsetParent;
  5722. while (current) {
  5723. actualTop += current.offsetTop;
  5724. current = current.offsetParent;
  5725. }
  5726. return actualTop;
  5727. }
  5728.  
  5729. function getElementLeft(ele) {
  5730. if (!ele) return 0;
  5731. if (ele.getBoundingClientRect) {
  5732. return ele.getBoundingClientRect().left + document.documentElement.scrollLeft;
  5733. }
  5734. var actualLeft = ele.offsetLeft;
  5735. var current = ele.offsetParent;
  5736. while (current) {
  5737. actualLeft += current.offsetLeft;
  5738. current = current.offsetParent;
  5739. }
  5740. return actualLeft;
  5741. }
  5742.  
  5743. function getElementBottom(ele) {
  5744. return getElementTop(ele) + (ele.offsetHeight || ele.scrollHeight);
  5745. }
  5746.  
  5747. function getFormatJSON(obj){
  5748. if(!objIsArr(obj) || obj.length === 0)return "";
  5749. return JSON.stringify(obj, null, 4);
  5750. }
  5751.  
  5752. function globMatch(first, second) {
  5753. if (first === '*') {
  5754. return true;
  5755. }
  5756. if (first.length == 0 && second.length == 0){
  5757. return true;
  5758. }
  5759.  
  5760. if (first.length > 1 && first[0] == '*' &&
  5761. second.length == 0){
  5762. return false;
  5763. }
  5764.  
  5765. if ((first.length > 1 && first[0] == '?') ||
  5766. (first.length != 0 && second.length != 0 &&
  5767. first[0] == second[0])){
  5768. return globMatch(first.substring(1),
  5769. second.substring(1));
  5770. }
  5771.  
  5772. if (first.length > 0 && first[0] == '*'){
  5773. return globMatch(first.substring(1), second) ||
  5774. globMatch(first, second.substring(1));
  5775. }
  5776.  
  5777. return false;
  5778. }
  5779.  
  5780. let pageReady = false;
  5781. function initRules(callback) {
  5782. charset = (document.characterSet || document.charset || document.inputEncoding);
  5783. let equiv = document.querySelector('[http-equiv="Content-Type"]');
  5784. if (equiv && equiv.content) {
  5785. let innerCharSet = equiv.content.match(/charset\=([^;]+)/);
  5786. if (!innerCharSet) {
  5787. charsetValid = false;
  5788. } else if (innerCharSet[1].replace("-", "").toLowerCase() != charset.replace("-", "").toLowerCase()) {
  5789. charsetValid = false;
  5790. }
  5791. } else charsetValid = false;
  5792. storage.getItem("rulesData", data => {
  5793. /*0 wedata格式,1 pagetual格式*/
  5794. ruleUrls = [{
  5795. id: 1,
  5796. url: data && data.wedata2github ? 'https://hoothin.github.io/UserScripts/Pagetual/items_all.json' : 'http://wedata.net/databases/AutoPagerize/items_all.json',
  5797. type: 0,
  5798. }];
  5799. if (data) {
  5800. rulesData = data;
  5801. if (data.urls) ruleUrls = ruleUrls.concat(data.urls);
  5802. if (data.sort) {
  5803. let urls = [];
  5804. data.sort.forEach(id => {
  5805. for (let s = 0; s < ruleUrls.length; s++) {
  5806. if (id == ruleUrls[s].id) {
  5807. urls.push(ruleUrls[s]);
  5808. break;
  5809. }
  5810. }
  5811. });
  5812. ruleUrls = urls;
  5813. }
  5814. }
  5815. if (rulesData.blacklist && rulesData.blacklist.length > 0) {
  5816. let href = location.href.slice(0, 500);
  5817. let commentStart = false;
  5818. for (let i = 0; i < rulesData.blacklist.length; i++) {
  5819. let curGlob = rulesData.blacklist[i];
  5820. if (!curGlob) continue;
  5821. if (curGlob.indexOf("//") == 0) continue;
  5822. if (commentStart) {
  5823. if (/\*\/$/.test(curGlob)) {
  5824. commentStart = false;
  5825. }
  5826. continue;
  5827. }
  5828. if (curGlob.indexOf("/*") == 0) {
  5829. commentStart = true;
  5830. continue;
  5831. }
  5832. if (curGlob.indexOf("/") == 0) {
  5833. let regMatch = curGlob.match(/^\/(.*)\/(\w*)$/);
  5834. if (regMatch && new RegExp(regMatch[1], regMatch[2]).test(href)) {
  5835. forceState == 1;
  5836. return;
  5837. }
  5838. } else if (globMatch(curGlob, href)) {
  5839. forceState == 1;
  5840. return;
  5841. }
  5842. }
  5843. }
  5844. if (rulesData.lang) {
  5845. setLang(rulesData.lang);
  5846. }
  5847. _GM_registerMenuCommand(i18n("configure"), () => {
  5848. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  5849. });
  5850. _GM_registerMenuCommand(i18n("editCurrent"), () => {
  5851. picker.start();
  5852. });
  5853. ruleParser.initSavedRules(async () => {
  5854. let upBtnImg = rulesData.upBtnImg, downBtnImg = rulesData.downBtnImg, _sideControllerIcon = rulesData.sideControllerIcon;
  5855. if (upBtnImg && downBtnImg) {
  5856. downSvgCSS = downSvgCSS.replace("transform: rotate(180deg);", "");
  5857. } else if (upBtnImg && !downBtnImg) {
  5858. downBtnImg = upBtnImg;
  5859. } else if(downBtnImg && !upBtnImg) {
  5860. upBtnImg = downBtnImg;
  5861. }
  5862. if (upBtnImg) {
  5863. upSvg = /https?:|data/.test(upBtnImg) ? `<img class="pagetual" src="${upBtnImg}"/>` : `<span>${upBtnImg}</span>`;
  5864. }
  5865. if (downBtnImg) {
  5866. downSvg = /https?:|data/.test(downBtnImg) ? `<img class="pagetual" src="${downBtnImg}"/>` : `<span>${downBtnImg}</span>`;
  5867. }
  5868. if (_sideControllerIcon) {
  5869. sideControllerIcon = /https?:|data/.test(_sideControllerIcon) ? `<img class="pagetual" src="${_sideControllerIcon}"/>` : `<span>${_sideControllerIcon}</span>`;
  5870. }
  5871. setLoadingDiv(rulesData.loadingText || i18n("loadingText"));
  5872. if (typeof(rulesData.opacity) == "undefined") {
  5873. rulesData.opacity = 1;
  5874. }
  5875. if (typeof(rulesData.hideBar) == "undefined") {
  5876. rulesData.hideBar = false;
  5877. }
  5878. if (typeof(rulesData.dbClick2Stop) == "undefined") {
  5879. rulesData.dbClick2Stop = true;
  5880. }
  5881. if (typeof(rulesData.enableWhiteList) == "undefined") {
  5882. rulesData.enableWhiteList = false;
  5883. }
  5884. if (typeof(rulesData.enableHistory) == "undefined") {
  5885. rulesData.enableHistory = false;
  5886. }
  5887. if (typeof(rulesData.openInNewTab) == "undefined") {
  5888. rulesData.openInNewTab = false;
  5889. }
  5890. if (typeof(rulesData.enableDebug) == "undefined") {
  5891. rulesData.enableDebug = true;
  5892. }
  5893. if (typeof(rulesData.initRun) == "undefined") {
  5894. rulesData.initRun = true;
  5895. }
  5896. if (typeof(rulesData.preload) == "undefined") {
  5897. rulesData.preload = true;
  5898. }
  5899. if (typeof(rulesData.customFirst) == "undefined") {
  5900. rulesData.customFirst = false;
  5901. }
  5902. if (typeof(rulesData.manualMode) == "undefined") {
  5903. rulesData.manualMode = false;
  5904. }
  5905. if (typeof(rulesData.clickMode) == "undefined") {
  5906. rulesData.clickMode = false;
  5907. }
  5908. if (typeof(rulesData.pageBarMenu) == "undefined") {
  5909. rulesData.pageBarMenu = true;
  5910. }
  5911. if (typeof(rulesData.arrowToScroll) == "undefined") {
  5912. rulesData.arrowToScroll = false;
  5913. }
  5914. if (typeof(rulesData.hideLoadingIcon) == "undefined") {
  5915. rulesData.hideLoadingIcon = false;
  5916. }
  5917. if (typeof(rulesData.hideBarArrow) == "undefined") {
  5918. rulesData.hideBarArrow = false;
  5919. }
  5920. if (typeof(rulesData.lastPageTips) == "undefined") {
  5921. rulesData.lastPageTips = true;
  5922. }
  5923. if (rulesData.autoLoadNum && rulesData.initRun) {
  5924. autoLoadNum = parseInt(rulesData.autoLoadNum);
  5925. }
  5926. openInNewTab = rulesData.openInNewTab ? 1 : 0;
  5927. enableDebug = rulesData.enableDebug;
  5928.  
  5929. let _nextSwitch = await getData("nextSwitch_" + location.host);
  5930. if (typeof(_nextSwitch) !== "undefined") {
  5931. nextIndex = _nextSwitch;
  5932. }
  5933.  
  5934. let _forceState = await getData("forceState_" + location.host);
  5935. if (typeof(_forceState) == "undefined") {
  5936. _forceState = (rulesData.enableWhiteList ? 1 : 0);
  5937. }
  5938. forceState = _forceState;
  5939.  
  5940. autoScroll = await getData("autoScroll_" + location.host + location.pathname) || 0;
  5941.  
  5942. updateDate = await getData("ruleLastUpdate");
  5943.  
  5944. manualPause = !!await getData("pauseState_" + location.host);
  5945.  
  5946. let href = location.href.slice(0, 100);
  5947. try {
  5948. if (_unsafeWindow.initedPagetual) {
  5949. if (ruleImportUrlReg.test(href)) {
  5950. showTips(i18n('duplicate'));
  5951. }
  5952. return;
  5953. }
  5954. _unsafeWindow.initedPagetual = true;
  5955. } catch(e) {showTips(e)}
  5956. listenUrl();
  5957. _GM_registerMenuCommand(i18n("update"), () => {
  5958. showTips(i18n("beginUpdate"), "", 60000);
  5959. updateRules(() => {
  5960. showTips(i18n("updateSucc"));
  5961. location.reload();
  5962. },(rule, err) => {
  5963. showTips(`Failed to update ${rule.url} rules!`);
  5964. debug(err);
  5965. });
  5966. });
  5967. _GM_registerMenuCommand(i18n(forceState == 1 ? "enable" : "disableSite"), () => {
  5968. if (forceState == 1) {
  5969. forceState = 0;
  5970. showTips(i18n("enableSiteTips"));
  5971. changeStop(false);
  5972. } else {
  5973. forceState = 1;
  5974. showTips(i18n("disableSiteTips"));
  5975. changeStop(true);
  5976. sideController.remove();
  5977. }
  5978. storage.setItem("forceState_" + location.host, forceState);
  5979. if (!ruleParser.curSiteRule.url) location.reload();
  5980. });
  5981. _GM_registerMenuCommand(i18n("toggleAutoScroll"), () => {
  5982. autoScroll = (autoScroll ? 0 : prompt(i18n("autoScrollRate"), 50)) || 0;
  5983. autoScroll = parseInt(autoScroll) || 0;
  5984. if (autoScroll < 0) autoScroll = 0;
  5985. else if (autoScroll > 1000) autoScroll = 1000;
  5986. storage.setItem("autoScroll_" + location.host + location.pathname, autoScroll);
  5987. startAutoScroll();
  5988. });
  5989. startAutoScroll();
  5990.  
  5991.  
  5992. if (initConfig(href)) return;
  5993. pageReady = true;
  5994. if (forceState == 1) return;
  5995. let now = new Date().getTime();
  5996. if (!updateDate || now - updateDate > 2 * 24 * 60 * 60 * 1000) {
  5997. updateRules(() => {
  5998. }, (rule, err) => {}, true);
  5999. storage.setItem("ruleLastUpdate", now);
  6000. }
  6001. callback();
  6002. });
  6003. });
  6004. }
  6005.  
  6006. function requestDoc(url, callback) {
  6007. let postParams = url.match(/#p{(.*)}$/);
  6008. if (postParams) {
  6009. postParams = postParams[1];
  6010. url = url.replace(/#p{.*/, "");
  6011. }
  6012. let ruleHeaders = ruleParser.curSiteRule.headers;
  6013. let headers = {
  6014. 'Referer': location.href,
  6015. 'User-Agent': navigator.userAgent,
  6016. 'accept': 'text/html,application/xhtml+xml,application/xml',
  6017. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + charset,
  6018. };
  6019. if (ruleHeaders) {
  6020. if (ruleHeaders.referer) {
  6021. headers.referer = ruleHeaders.referer;
  6022. }
  6023. if (ruleHeaders.userAgent) {
  6024. headers.userAgent = ruleHeaders.userAgent;
  6025. }
  6026. if (ruleHeaders.accept) {
  6027. headers.accept = ruleHeaders.accept;
  6028. }
  6029. if (ruleHeaders.contentType) {
  6030. headers.contentType = ruleHeaders.contentType;
  6031. let ruleCharset = ruleHeaders.contentType.match(/charset\=([^;]+)/);
  6032. if (ruleCharset) charset = ruleCharset[1];
  6033. }
  6034. if (ruleHeaders.cookie) {
  6035. headers.cookie = ruleHeaders.cookie;
  6036. }
  6037. }
  6038. _GM_xmlhttpRequest({
  6039. url: url,
  6040. method: postParams ? 'POST' : 'GET',
  6041. data: postParams,
  6042. overrideMimeType: 'text/html;charset=' + charset,
  6043. headers: headers,
  6044. timeout: 20000,
  6045. onload: async function(res) {
  6046. if (isPause) return callback(false);
  6047. var doc = null, response = res.response;
  6048. let preCode = ruleParser.curSiteRule.pageElementPre || ruleParser.curSiteRule.pagePre;
  6049. if (preCode) {
  6050. try {
  6051. if (typeof preCode == 'function') {
  6052. response = preCode(response);
  6053. } else if (preCode.length == 2) {
  6054. response = response.replace(new RegExp(preCode[0], "gi"), preCode[1]);
  6055. } else {
  6056. response = Function("response",'"use strict";' + preCode)(response);
  6057. }
  6058. } catch(e) {
  6059. debug(e);
  6060. }
  6061. }
  6062. try {
  6063. doc = document.implementation.createHTMLDocument('');
  6064. doc.documentElement.innerHTML = response;
  6065. let base = doc.querySelector("base");
  6066. ruleParser.basePath = base ? base.href : url;
  6067. } catch (e) {
  6068. debug('parse error:' + e.toString());
  6069. }
  6070. if (charsetValid && !ruleHeaders) {
  6071. let equiv = doc.querySelector('[http-equiv="Content-Type"]');
  6072. if (equiv && equiv.content) {
  6073. let innerCharSet = equiv.content.match(/charset\=([^;]+)/);
  6074. if (innerCharSet && innerCharSet[1].replace("-", "").toLowerCase() != charset.replace("-", "").toLowerCase()) {
  6075. charset = innerCharSet[1];
  6076. return requestDoc(url, callback);
  6077. }
  6078. }
  6079. }
  6080. let pageElement = ruleParser.getPageElement(doc);
  6081. if ((!pageElement || pageElement.length == 0) && res.status >= 400) {
  6082. debug(res.status, "Error status");
  6083. return callback(false);
  6084. }
  6085. if (inCors && (!pageElement || pageElement.length == 0) && ruleParser.curSiteRule.singleUrl) {
  6086. let article = doc.querySelectorAll(mainSel);
  6087. if (article && article.length == 1) {
  6088. article = article[0];
  6089. ruleParser.curSiteRule.pageElement = article.nodeName.toLowerCase() + (article.id ? "#" + article.id : "") + (article.className ? "." + article.className.replace(/ /g, ".") : "") + ">*";
  6090. pageElement = article.children;
  6091. } else {
  6092. ruleParser.curSiteRule.pageElement = allOfBody;
  6093. pageElement = ruleParser.getPageElement(doc);
  6094. }
  6095. ruleParser.getInsert(true);
  6096. }
  6097. //只有1的話怕不是圖片哦
  6098. if (pageElement && (pageElement.length > 1 || (pageElement.length == 1 && !compareNodeName(pageElement[0], ["img"])))) {
  6099. await ruleParser.insertPage(doc, pageElement, url, callback, false);
  6100. if (ruleParser.curSiteRule.action == 1) {
  6101. isLoading = true;
  6102. requestFromIframe(url, (doc, eles) => {
  6103. if (eles) {
  6104. ruleParser.insertPage(doc, eles, url, callback, true);
  6105. } else isLoading = false;
  6106. });
  6107. } else ruleParser.curSiteRule.action = 0;
  6108. } else if ((ruleParser.curSiteRule.singleUrl || curPage == 1) && !inCors) {
  6109. ruleParser.curSiteRule.action = 1;
  6110. requestFromIframe(url, (doc, eles) => {
  6111. if (eles) {
  6112. ruleParser.insertPage(doc, eles, url, callback, true);
  6113. } else isLoading = false;
  6114. });
  6115. } else {
  6116. debug("Stop as no page element");
  6117. ruleParser.noValidContent(url);
  6118. changeStop(true);
  6119. callback(false);
  6120. }
  6121. },
  6122. onerror: function(e) {
  6123. debug(e, "NetError");
  6124. callback(false);
  6125. },
  6126. ontimeout: function(e) {
  6127. debug(e, "NetTimeout");
  6128. callback(false);
  6129. }
  6130. });
  6131. }
  6132.  
  6133. function initPage() {
  6134. ruleParser.initPage(() => {
  6135. if (ruleParser.curSiteRule.autoLoadNum) {
  6136. autoLoadNum = ruleParser.curSiteRule.autoLoadNum;
  6137. }
  6138. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  6139. _GM_registerMenuCommand(i18n("nextSwitch"), () => {
  6140. nextSwitch.start();
  6141. });
  6142. }
  6143. if (ruleParser.nextLinkHref) {
  6144. let isJs = ruleParser.hrefIsJs(ruleParser.nextLinkHref);
  6145. if (!isJs) {
  6146. let inForce = (forceState == 2 || forceState == 3);
  6147. _GM_registerMenuCommand(i18n(inForce ? "cancelForceIframe" : "forceIframe"), () => {
  6148. if (inForce) {
  6149. storage.setItem("forceState_" + location.host, "");
  6150. } else {
  6151. let _state = ruleParser.curSiteRule.action > 0 || confirm(i18n("forceAllBody")) ? 2 : 3;
  6152. storage.setItem("forceState_" + location.host, _state);
  6153. }
  6154. location.reload();
  6155. });
  6156. }
  6157. _GM_registerMenuCommand(i18n("loadNow"), () => {
  6158. let loadNum = window.prompt(i18n("loadConfirm"), "1");
  6159. if (loadNum === "" || loadNum === null) return;
  6160. autoLoadNum = Math.abs(parseInt(loadNum));
  6161. nextPage();
  6162. });
  6163. }
  6164. initListener();
  6165. });
  6166. }
  6167.  
  6168. var pageBarStyle, mainStyleEle, mainStyleStyle;
  6169. function initView() {
  6170. if (!mainStyleStyle) {
  6171. mainStyleStyle = `
  6172. .pagetual_pageBar{
  6173. -moz-transition:all 0.3s ease-in-out 0s;
  6174. -webkit-transition:all 0.3s ease-in-out 0s;
  6175. transition:all 0.3s ease-in-out 0s;
  6176. font-family: Arial,sans-serif !important;
  6177. text-align: center !important;
  6178. }
  6179. .pagetual_pageBar.stop {
  6180. -webkit-filter: invert(100%);
  6181. filter: invert(100%);
  6182. opacity: 1!important;
  6183. }
  6184. .pagetual_pageBar.hide {
  6185. display: none!important;
  6186. }
  6187. .pagetual-hide {
  6188. display: none!important;
  6189. }
  6190. .pagetual_pageBar:hover {
  6191. opacity: 1!important;
  6192. box-shadow: 0px 0px 10px 0px #000000aa;
  6193. border-radius: 20px;
  6194. background-color: rgb(240 240 240 / 80%);
  6195. border-color: transparent!important;
  6196. }
  6197. .pagetual_pageBar span {
  6198. vertical-align: super;
  6199. }
  6200. .pagetual_pageBar a::before,
  6201. .pagetual_pageBar a::after {
  6202. content: none;
  6203. }
  6204. .pagetual_pageBar a>span {
  6205. margin-top: 0!important;
  6206. pointer-events: none;
  6207. padding: unset;
  6208. opacity: 0;
  6209. -moz-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  6210. -webkit-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  6211. transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  6212. transform: none;
  6213. left: 0;
  6214. margin-left: calc(50% - 20px);
  6215. }
  6216. .pagetual_pageBar a>span:hover {
  6217. color: red;
  6218. }
  6219. .pagetual_pageBar a:hover>span {
  6220. opacity: 1;
  6221. }
  6222. .pagetual_pageBar span.prevScreen,
  6223. .pagetual_pageBar span.nextScreen {
  6224. display: block!important;
  6225. }
  6226. .pagetual_pageBar a:hover>span.prevScreen {
  6227. margin-top: -${rulesData.opacity == 1 ? 31 : 30}px!important;
  6228. pointer-events: all;
  6229. }
  6230. .pagetual_pageBar span.refreshRing {
  6231. position: absolute;
  6232. top: 0;
  6233. opacity: 0;
  6234. height: 30px;
  6235. margin-left: calc(50% - 23px);
  6236. display: block!important;
  6237. }
  6238. .pagetual_pageBar a:hover>span.refreshRing {
  6239. opacity: 0.3;
  6240. -webkit-animation: pagetual_ring 2.0s infinite linear;
  6241. animation: pagetual_ring 2.0s infinite linear;
  6242. }
  6243. @-webkit-keyframes pagetual_ring {
  6244. 0% { -webkit-transform: rotate(0deg) }
  6245. 100% {
  6246. -webkit-transform: rotate(360deg);
  6247. }
  6248. }
  6249. @keyframes pagetual_ring {
  6250. 0% {
  6251. transform: rotate(0deg);
  6252. -webkit-transform: rotate(0deg);
  6253. } 100% {
  6254. transform: rotate(360deg);
  6255. -webkit-transform: rotate(360deg);
  6256. }
  6257. }
  6258. .pagetual_pageBar a:hover>span.nextScreen {
  6259. margin-top: 30px!important;
  6260. pointer-events: all;
  6261. }
  6262. .pagetual_pageBar span>svg {
  6263. -moz-transition:transform 0.5s ease, opacity 0.3s ease;
  6264. -webkit-transition:transform 0.5s ease, opacity 0.3s ease;
  6265. transition:transform 0.5 ease, opacity 0.3s ease;
  6266. opacity: 0;
  6267. }
  6268. .pagetual_pageBar.stop span>svg{
  6269. opacity: 1;
  6270. }
  6271. .pagetual_pageBar.stop span>svg>path{
  6272. transform: scale(.8);
  6273. transform-origin: center;
  6274. -moz-transition:transform 0.3s ease;
  6275. -webkit-transition:transform 0.3s ease;
  6276. transition:transform 0.3 ease;
  6277. }
  6278. .pagetual_pageBar.stop:hover span>svg>path{
  6279. transform: unset;
  6280. }
  6281. .pagetual_pageBar:hover span>svg {
  6282. opacity: 1;
  6283. }
  6284. .pagetual_pageBar span>svg.upSvg:hover {
  6285. transform: rotate(360deg) scale3d(1.2, 1.2, 1.2);
  6286. }
  6287. .pagetual_pageBar span>svg.downSvg:hover {
  6288. transform: rotate(540deg) scale3d(1.2, 1.2, 1.2)!important;
  6289. }
  6290. .pagetual_pageBar .pagetual_pageNum{
  6291. color: #55555f;
  6292. }
  6293. .pagetual_pageBar .pagetual_pageNum:hover{
  6294. color: #ff6464;
  6295. }
  6296. .pagetual_tipsWords {
  6297. font-size: 50px;
  6298. font-weight: bold;
  6299. font-family: "黑体", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
  6300. "Oxygen", "Ubuntu", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
  6301. "Segoe UI Emoji", "Segoe UI Symbol";
  6302. color: #ffffff;
  6303. min-height: 70px;
  6304. max-width: 80%;
  6305. line-height: 70px;
  6306. position: fixed;
  6307. left: 50%;
  6308. top: 10%;
  6309. margin-left: -99999px;
  6310. padding: 0 15px;
  6311. z-index: 2147483647;
  6312. background-color: #000;
  6313. border: 1px solid #303030;
  6314. border-radius: 10px;
  6315. opacity: 0;
  6316. filter: alpha(opacity=65);
  6317. box-shadow: 5px 5px 20px 0px #000;
  6318. -moz-transition:opacity 0.3s ease-in-out 0s;
  6319. -webkit-transition:opacity 0.3s ease-in-out 0s;
  6320. transition:opacity 0.3s ease-in-out 0s;
  6321. pointer-events: none;
  6322. }
  6323. .pagetual_tipsWords>a {
  6324. color: #ffffff;
  6325. }
  6326. .pagetual_loading {
  6327. width: 50px;
  6328. height: 50px;
  6329. margin: 10px auto;
  6330. border-radius: 100%;
  6331. display: flex;
  6332. -webkit-animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  6333. animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  6334. }
  6335. @-webkit-keyframes pagetual_loading_scaleout {
  6336. 0% { -webkit-transform: scale(0.0) }
  6337. 100% {
  6338. -webkit-transform: scale(1.0);
  6339. opacity: 0;
  6340. }
  6341. }
  6342. @keyframes pagetual_loading_scaleout {
  6343. 0% {
  6344. transform: scale(0.0);
  6345. -webkit-transform: scale(0.0);
  6346. } 100% {
  6347. transform: scale(1.0);
  6348. -webkit-transform: scale(1.0);
  6349. opacity: 0;
  6350. }
  6351. }
  6352. .pagetual_loading_text {
  6353. white-space: nowrap;
  6354. -webkit-animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  6355. animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  6356. }
  6357. @-webkit-keyframes pagetual_loading_opacity {
  6358. 0% { opacity: 1 }
  6359. 50% { opacity: 0.2 }
  6360. 100% { opacity: 1 }
  6361. }
  6362. @keyframes pagetual_loading_opacity {
  6363. 0% { opacity: 1 }
  6364. 50% { opacity: 0.2 }
  6365. 100% { opacity: 1 }
  6366. }
  6367. `;
  6368. let bodyColor
  6369. 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%);"}`;
  6370. }
  6371. if (!mainStyleEle || !mainStyleEle.parentNode) {
  6372. mainStyleEle = _GM_addStyle(mainStyleStyle);
  6373. }
  6374. }
  6375. var loadingDiv = document.createElement("div");
  6376. 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;";
  6377.  
  6378. 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;`;
  6379. function setLoadingDiv(loadingText) {
  6380. 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>`}`);
  6381. }
  6382.  
  6383. 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>`;
  6384. 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;`;
  6385. 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>`;
  6386. 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);`;
  6387.  
  6388. 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;`;
  6389. 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;`;
  6390. var sideControllerIcon = '';
  6391.  
  6392. var tipsWords = document.createElement("div");
  6393. tipsWords.className = "pagetual_tipsWords";
  6394.  
  6395. var changeStopTimer;
  6396. function changeStop(stop) {
  6397. isPause = stop;
  6398. clearTimeout(changeStopTimer);
  6399. changeStopTimer = setTimeout(() => {
  6400. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar,#pagetual-sideController"), bar => {
  6401. if (isPause) {
  6402. bar.classList.add("stop");
  6403. } else {
  6404. bar.classList.remove("stop");
  6405. }
  6406. });
  6407. if (!isPause) ruleParser.showAddedElements();
  6408. manualPause = isPause;
  6409. if (sideController.inited) storage.setItem("pauseState_" + location.host, isPause ? true : "");
  6410. }, 350);
  6411. }
  6412.  
  6413. function changeHideBar(hide) {
  6414. isHideBar = hide;
  6415. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar"), bar => {
  6416. if (isHideBar) {
  6417. bar.classList.add("hide");
  6418. } else {
  6419. bar.classList.remove("hide");
  6420. }
  6421. });
  6422. }
  6423.  
  6424. function isInViewPort(element) {
  6425. if (!getBody(document).contains(element)) return false;
  6426. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  6427. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  6428. const {
  6429. top,
  6430. right,
  6431. bottom,
  6432. left,
  6433. } = element.getBoundingClientRect();
  6434.  
  6435. return (
  6436. top >= 0 &&
  6437. left >= 0 &&
  6438. right <= viewWidth + 1 &&
  6439. top <= viewHeight * (ruleParser.curSiteRule.rate || rulesData.rate || 1) &&
  6440. isVisible(element, _unsafeWindow)
  6441. );
  6442. }
  6443.  
  6444. function getPageBar() {
  6445. let preBar = null, nextBar = null;
  6446. let pageBars = [].slice.call(document.querySelectorAll(".pagetual_pageBar"));
  6447. for (let i = 0; i < pageBars.length; i++) {
  6448. let pageBar = pageBars[i];
  6449. if (!pageBar || !getBody(document).contains(pageBar)) continue;
  6450. let {
  6451. top,
  6452. right,
  6453. bottom,
  6454. left,
  6455. } = pageBar.getBoundingClientRect();
  6456. if (top > 500) {
  6457. nextBar = pageBar;
  6458. preBar = (i - 1 >= 0 ? pageBars[i - 1] : null);
  6459. if (pageBar && getBody(document).contains(pageBar)) {
  6460. let {
  6461. top,
  6462. right,
  6463. bottom,
  6464. left,
  6465. } = pageBar.getBoundingClientRect();
  6466. if (top < -500) {
  6467. preBar = pageBar;
  6468. } else preBar = (i - 2 >= 0 ? pageBars[i - 2] : null);
  6469. }
  6470. break;
  6471. }
  6472. }
  6473. if (!nextBar) preBar = pageBars[pageBars.length - 2];
  6474. return {preBar: preBar, nextBar: nextBar};
  6475. }
  6476.  
  6477. var urlChanged = false;
  6478. var urlChanging = false;
  6479. var urlchangeHandler = e => {
  6480. if (ruleParser && ruleParser.curSiteRule && ruleParser.curSiteRule.listenUrlChange == false) return;
  6481. isPause = true;
  6482. setTimeout(() => {
  6483. lastActiveUrl = location.href;
  6484. if (urlChanging) return;
  6485. urlChanging = true;
  6486. let href = location.href.slice(0, 60);
  6487. if (href == configPage[0]) {
  6488. setTimeout(() => {
  6489. initConfig(href);
  6490. urlChanging = false;
  6491. }, 1000);
  6492. } else {
  6493. setTimeout(() => {
  6494. if (guidePage.test(href)) {
  6495. setTimeout(() => {
  6496. initConfig(href);
  6497. urlChanging = false;
  6498. }, 1000);
  6499. } else {
  6500. urlChanged = true;
  6501. if (!ruleParser.nextLinkHref) {
  6502. isLoading = false;
  6503. }
  6504. urlChanging = false;
  6505. //if (!pageReady && !ruleImportUrlReg.test(href)) location.reload();
  6506. }
  6507. }, 500);
  6508. }
  6509. }, 1);
  6510. };
  6511. window.addEventListener('pagetual_pushState', urlchangeHandler);
  6512. /*var _wr = function(type) {
  6513. var orig = history[type];
  6514. return function() {
  6515. var rv = orig.apply(this, arguments);
  6516. var e = new Event('pagetual_' + type);
  6517. e.arguments = arguments;
  6518. window.dispatchEvent(e);
  6519. return rv;
  6520. };
  6521. };
  6522. history.pushState = _wr('pushState');*/
  6523.  
  6524. function listenUrl() {
  6525. var prevPathname = window.location.pathname;
  6526. var prevSearch = window.location.search;
  6527. var checkUrlTime = 100;
  6528. var checkUrlTimer;
  6529. var checkClickedEle = null;
  6530. var checkFunc = () => {
  6531. if (forceState == 1) return;
  6532. if (checkClickedEle) {
  6533. if (!clickedSth && checkClickedEle && checkClickedEle.nodeName) {
  6534. if (compareNodeName(checkClickedEle, ["a", "button"])) {
  6535. clickedSth = true;
  6536. } else {
  6537. let targetStyle = _unsafeWindow.getComputedStyle(checkClickedEle);
  6538. if (targetStyle.cursor == "pointer") clickedSth = true;
  6539. }
  6540. }
  6541. checkClickedEle = null;
  6542. }
  6543. if (checkUrlTime < 5000) {
  6544. checkUrlTime += checkUrlTime>>1;
  6545. }
  6546. clearTimeout(checkUrlTimer);
  6547. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  6548. if (document.hidden) return;
  6549. if ((prevPathname !== window.location.pathname || prevSearch !== window.location.search) && window.location.href != ruleParser.historyUrl) {
  6550. checkUrlTime = 2000;
  6551. urlWillChange = true;
  6552. var e = new Event('pagetual_pushState');
  6553. e.arguments = arguments;
  6554. window.dispatchEvent(e);
  6555. clickedSth = false;
  6556. }
  6557. prevPathname = window.location.pathname;
  6558. prevSearch = window.location.search;
  6559. };
  6560. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  6561.  
  6562. document.addEventListener("click", e => {
  6563. if (!checkClickedEle) {
  6564. checkClickedEle = e.target;
  6565. checkUrlTime = 300;
  6566. clearTimeout(checkUrlTimer);
  6567. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  6568. }
  6569. });
  6570. }
  6571.  
  6572. let scrollContainer;
  6573. function distToBottom () {
  6574. let scrolly = window.scrollY;
  6575. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  6576. if (!scrollContainer || !document.documentElement.contains(scrollContainer)) {
  6577. let pageEle = ruleParser.getPageElement(document);
  6578. if (pageEle && pageEle.length) {
  6579. let parent = pageEle[0].parentNode, pageScrollY = parent.scrollTop;;
  6580. while (parent && pageScrollY == 0) {
  6581. parent = parent.parentNode;
  6582. pageScrollY = parent.scrollTop;
  6583. }
  6584. if (pageScrollY) {
  6585. scrollContainer = parent;
  6586. return scrollContainer.scrollHeight - pageScrollY - windowHeight;
  6587. }
  6588. }
  6589. }
  6590. if (scrollContainer) {
  6591. return scrollContainer.scrollHeight - scrollContainer.scrollTop - windowHeight;
  6592. }
  6593.  
  6594. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  6595. return scrollH - scrolly - windowHeight;
  6596. }
  6597.  
  6598. let scrollHandler, clickToResetHandler, dblclickHandler, keydownHandler, hashchangeHandler, manualModeKeyHandler, pagetualNextHandler, keyupHandler;
  6599. function initListener () {
  6600. document.removeEventListener('scroll', scrollHandler, true);
  6601. document.removeEventListener('wheel', scrollHandler, true);
  6602. document.removeEventListener('dblclick', dblclickHandler);
  6603. document.removeEventListener('keydown', keydownHandler);
  6604. window.removeEventListener('hashchange', hashchangeHandler, false);
  6605. document.removeEventListener('keydown', manualModeKeyHandler);
  6606. document.removeEventListener('pagetual.next', pagetualNextHandler, false);
  6607. document.removeEventListener('keyup', keyupHandler);
  6608. let loadmoreBtn, loadingMore = true, lastScroll = 0, checkLoadMoreTimes = 0;
  6609. if (ruleParser.curSiteRule.singleUrl) {
  6610. loadingMore = false;
  6611. } else if (ruleParser.curSiteRule.loadMore) {
  6612. loadingMore = false;
  6613. }
  6614. clickMode = typeof ruleParser.curSiteRule.clickMode == 'undefined' ? rulesData.clickMode : ruleParser.curSiteRule.clickMode;
  6615. let clickingNext = false;
  6616. let clickNext = async () => {
  6617. if (clickingNext) return;
  6618. clickingNext = true;
  6619. setTimeout(() => {
  6620. clickingNext = false;
  6621. }, 1500);
  6622. let nextLink = ruleParser.nextLinkHref;
  6623. if (!nextLink) return;
  6624. let isJs = ruleParser.hrefIsJs(nextLink);
  6625. if (isJs) {
  6626. let nextBtn = ruleParser.nextLinkEle;
  6627. if (!nextBtn || !nextBtn.offsetParent) nextBtn = await ruleParser.getNextLink(document, true);
  6628. if (nextBtn) emuClick(nextBtn);
  6629. } else {
  6630. window.location.href = nextLink;
  6631. }
  6632. };
  6633. let checkScrollReach = () => {
  6634. let dist = distToBottom();
  6635. if (clickMode) {
  6636. if (dist < 10) {
  6637. clickNext();
  6638. }
  6639. } else if (dist < bottomGap) {
  6640. nextPage();
  6641. }
  6642. };
  6643. scrollHandler = e => {
  6644. if (urlChanged && !isLoading) {
  6645. ruleParser.initPage(() => {});
  6646. urlChanged = false;
  6647. loadingMore = false;
  6648. }
  6649. if (isPause) return;
  6650. if (!loadingMore) {
  6651. loadmoreBtn = getLoadMore(document, loadmoreBtn);
  6652. if (loadmoreBtn) {
  6653. if (isInViewPort(loadmoreBtn)) {
  6654. emuClick(loadmoreBtn);
  6655. loadingMore = true;
  6656. setTimeout(() => {loadingMore = false}, 200);
  6657. }
  6658. } else {
  6659. loadingMore = true;
  6660. if (!ruleParser.curSiteRule.singleUrl || checkLoadMoreTimes++ < 3) {
  6661. setTimeout(() => {loadingMore = false}, 200);
  6662. }
  6663. }
  6664. }
  6665. if (!isLoading && !stopScroll) {
  6666. checkScrollReach();
  6667. }
  6668. ruleParser.changeVisibility();
  6669. if (ruleParser.curSiteRule.lockScroll) {
  6670. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  6671. if (isLoading && Math.abs(lastScroll - curScroll) > 350) {
  6672. getBody(document).scrollTop = lastScroll;
  6673. document.documentElement.scrollTop = lastScroll;
  6674. } else {
  6675. lastScroll = curScroll;
  6676. }
  6677. }
  6678. };
  6679. dblclickHandler = e => {
  6680. if (forceState == 1 || compareNodeName(e.target, ["input", "textarea", "select", "a", "button", "svg", "use", "img", "path"])) return;
  6681. if (!rulesData.dbClick2StopKey) {
  6682. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  6683. (rulesData.dbClick2StopAlt && !e.altKey) ||
  6684. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  6685. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  6686. return;
  6687. }
  6688. }
  6689. if (!compareNodeName(e.target, ["body"]) && !e.target.classList.contains('pagetual_pageBar')) {
  6690. try {
  6691. let selection = window.getSelection();
  6692. let selStr = selection.toString().trim();
  6693. if (!selStr) {
  6694. selection = selection.getRangeAt(0);
  6695. selStr = selection && selection.cloneContents().children[0];
  6696. if (selStr && !compareNodeName(selStr, ["img"])) selStr = false;
  6697. }
  6698. if (selStr) {
  6699. return;
  6700. }
  6701. } catch (e) {}
  6702. }
  6703. if (rulesData.dbClick2Stop && (ruleParser.nextLinkHref || loadmoreBtn)) {
  6704. setTimeout(() => {
  6705. if (rulesData.hideBarButNoStop || rulesData.hideBar) {
  6706. changeHideBar(!isHideBar);
  6707. }
  6708. if (!rulesData.hideBarButNoStop) {
  6709. changeStop(!isPause);
  6710. showTips(i18n(isPause ? "disable" : "enable"));
  6711. }
  6712. if (!isPause) {
  6713. checkScrollReach();
  6714. }
  6715. }, 10);
  6716. }
  6717. };
  6718. document.addEventListener('dblclick', dblclickHandler);
  6719. clickToResetHandler = e => {
  6720. if (!ruleParser.nextLinkHref) isLoading = false;
  6721. };
  6722. document.addEventListener('click', clickToResetHandler);
  6723. if (rulesData.dbClick2StopKey) {
  6724. keydownHandler = e => {
  6725. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  6726. (rulesData.dbClick2StopAlt && !e.altKey) ||
  6727. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  6728. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  6729. return;
  6730. }
  6731. if (document.activeElement &&
  6732. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  6733. document.activeElement.contentEditable == 'true')) {
  6734. return;
  6735. }
  6736. var key = e.key.toLowerCase();
  6737. if (rulesData.dbClick2StopKey.toLowerCase() == key) {
  6738. if (forceState == 1) {
  6739. forceState = 0;
  6740. showTips(i18n("enableSiteTips"));
  6741. changeStop(false);
  6742. } else {
  6743. forceState = 1;
  6744. showTips(i18n("disableSiteTips"));
  6745. changeStop(true);
  6746. sideController.remove();
  6747. }
  6748. if (!ruleParser.curSiteRule.url) {
  6749. storage.setItem("forceState_" + location.host, forceState);
  6750. location.reload();
  6751. }
  6752. }
  6753. };
  6754. document.addEventListener('keydown', keydownHandler);
  6755. }
  6756. if (ruleParser.curSiteRule.listenHashChange) {
  6757. hashchangeHandler = () => {
  6758. isPause = true;
  6759. urlChanged = true;
  6760. if (!ruleParser.nextLinkHref) isLoading = false;
  6761. };
  6762. window.addEventListener('hashchange', hashchangeHandler, false);
  6763. }
  6764. let manualMode = typeof ruleParser.curSiteRule.manualMode == 'undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode;
  6765. if (manualMode) {
  6766. manualModeKeyHandler = e => {
  6767. if (document.activeElement &&
  6768. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  6769. document.activeElement.contentEditable == 'true')) {
  6770. return;
  6771. }
  6772. if (e.keyCode == 39) {
  6773. clickNext();
  6774. } else if (e.keyCode == 37) {
  6775. history.back();
  6776. }
  6777. };
  6778. document.addEventListener('keydown', manualModeKeyHandler);
  6779. pagetualNextHandler = () => {
  6780. clickNext();
  6781. };
  6782. document.addEventListener('pagetual.next', pagetualNextHandler, false);
  6783. return;
  6784. }
  6785. if (rulesData.arrowToScroll) {
  6786. keyupHandler = e => {
  6787. if (document.activeElement &&
  6788. (compareNodeName(document.activeElement, ["input", "textarea"]) ||
  6789. document.activeElement.contentEditable == 'true')) {
  6790. return;
  6791. }
  6792. if (e.keyCode == 39) {
  6793. let nextPageBar=getPageBar().nextBar;
  6794. if (nextPageBar) {
  6795. scrollToPageBar(nextPageBar);
  6796. } else {
  6797. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  6798. window.scrollTo({ top: scrollTop + (window.innerHeight || document.documentElement.clientHeight), behavior: 'instant'});
  6799. }
  6800. } else if (e.keyCode == 37) {
  6801. let prePageBar = getPageBar().preBar;
  6802. if (prePageBar) {
  6803. scrollToPageBar(prePageBar);
  6804. } else {
  6805. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  6806. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'instant'});
  6807. }
  6808. }
  6809. };
  6810. document.addEventListener('keyup', keyupHandler);
  6811. }
  6812. if (!ruleParser.curSiteRule.wheel) {
  6813. document.addEventListener('scroll', scrollHandler, true);
  6814. }
  6815. document.addEventListener('wheel', scrollHandler, true);
  6816. }
  6817.  
  6818. let hideTipsTimeout;
  6819. function showTips(content, href, time, wordColor, backColor) {
  6820. initView();
  6821. getBody(document).appendChild(tipsWords);
  6822. tipsWords.style.color = wordColor || 0xFFFFFF;
  6823. tipsWords.style.backgroundColor = backColor || 0x000;
  6824. let _time = 1500;
  6825. if (href) {
  6826. _time = 3500;
  6827. tipsWords.innerHTML = createHTML(`<a href='${href}'>${content}</a>`);
  6828. tipsWords.style.pointerEvents = 'all';
  6829. } else {
  6830. tipsWords.innerHTML = createHTML(content);
  6831. }
  6832. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  6833. setTimeout(() => {
  6834. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  6835. }, 0);
  6836. setTimeout(() => {
  6837. tipsWords.style.opacity = 0.8;
  6838. clearTimeout(hideTipsTimeout);
  6839. hideTipsTimeout = setTimeout(() => {
  6840. tipsWords.style.opacity = 0;
  6841. tipsWords.style.pointerEvents = '';
  6842. }, time || _time);
  6843. }, 1);
  6844. }
  6845.  
  6846. const loadmoreReg = /^\s*((点击)?加载更多|(點擊)?加載更多|load\s*more|もっと読み込む)[.…]*\s*$/i;
  6847. 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";
  6848. function getLoadMore(doc, loadmoreBtn) {
  6849. if (!loadmoreBtn || !getBody(doc).contains(loadmoreBtn) || /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  6850. if (!ruleParser.curSiteRule.singleUrl && !ruleParser.curSiteRule.loadMore) return null;
  6851. if (loadmoreBtn) return loadmoreBtn;
  6852. let btnSel = ruleParser.curSiteRule.loadMore || defaultLoadmoreSel;
  6853. if (btnSel) {
  6854. loadmoreBtn = getElement(btnSel, doc, null, true);
  6855. }
  6856. if (!loadmoreBtn) {
  6857. let buttons = doc.querySelectorAll("input,button,a,div[onclick]");
  6858. for (let i = 0; i < buttons.length; i++) {
  6859. let button = buttons[i];
  6860. if (!button.innerText || button.innerText.length > 20) continue;
  6861. if (button && loadmoreReg.test(button.innerText)) {
  6862. loadmoreBtn = button;
  6863. break;
  6864. }
  6865. }
  6866. }
  6867. if (loadmoreBtn && !ruleParser.curSiteRule.loadMore && loadmoreBtn.dataset.ajax !== "true") {
  6868. let href = loadmoreBtn.getAttribute("href");
  6869. if (href && href != "/" && !ruleParser.hrefIsJs(href)) {
  6870. loadmoreBtn = null;
  6871. }
  6872. }
  6873. if (loadmoreBtn && /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  6874. if (loadmoreBtn) debug(loadmoreBtn, 'Load more button');
  6875. return loadmoreBtn;
  6876. }
  6877.  
  6878. var lastPageBar;
  6879. function scrollToPageBar(bar){
  6880. let yOffset = -20;
  6881. if (typeof ruleParser.curSiteRule.pageBarTop !== 'undefined') {
  6882. yOffset = -ruleParser.curSiteRule.pageBarTop;
  6883. }
  6884. const y = bar.getBoundingClientRect().top + window.pageYOffset + yOffset;
  6885. window.scrollTo({ top: y, behavior: lastPageBar == bar ? 'instant' : 'smooth'});
  6886. }
  6887.  
  6888. const pageNumReg=/[&\/\?](p=|page[=\/_-]?)\d+|[_-]\d+\./;
  6889. function createPageBar(url) {
  6890. curPage++;
  6891. sideController.setup();
  6892. let posEle = null;
  6893. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  6894. let insert = ruleParser.getInsert();
  6895. if (!insert || !insert.parentNode) return;
  6896. if (forceState == 2) {
  6897. posEle = getBody(document);
  6898. posEle = posEle.children[posEle.children.length - 1];
  6899. } else {
  6900. posEle = insert;
  6901. }
  6902. while (posEle && !posEle.offsetParent) {
  6903. posEle = posEle.previousElementSibling || posEle.parentNode;
  6904. }
  6905. if (posEle) {
  6906. let actualBottom = getElementBottom(posEle);
  6907. bottomGap = scrollH - actualBottom + (window.innerHeight || document.documentElement.clientHeight) * (ruleParser.curSiteRule.rate || rulesData.rate || 1);
  6908. if (bottomGap < 100) bottomGap = 100;
  6909. } else {
  6910. bottomGap = 1000;
  6911. }
  6912. if (rulesData.opacity == 0 || ruleParser.curSiteRule.pageBar === 0) return null;
  6913. url = url.replace(/#p{.*/, "");
  6914. let example = (ruleParser.curSiteRule.insertPos == 2 || ruleParser.curSiteRule.insertPos == "in") ? insert.children[0] : (insert.parentNode.children[0] || insert);
  6915. while (example && (compareNodeName(example, ["script", "style"]) || example.className == "pagetual_pageBar")) {
  6916. example = example.nextElementSibling;
  6917. }
  6918. if (!example || !example.parentNode) example = insert;
  6919. if (example.nodeType != 1) {
  6920. example = example.previousElementSibling || example.parentNode;
  6921. if (!example || example.nodeType != 1) return;
  6922. }
  6923. let exampleStyle = _unsafeWindow.getComputedStyle(example);
  6924. let inTable, inLi;
  6925. if (forceState == 2) {
  6926. inTable = inLi = false;
  6927. } else {
  6928. inTable = compareNodeName(example.parentNode, ["table", "tbody"]) ||
  6929. compareNodeName(example, ["tr", "tbody"]) ||
  6930. exampleStyle.display == "table-row" ||
  6931. (example.nextElementSibling && compareNodeName(example.nextElementSibling, ["tr", "tbody"]));
  6932. inLi = compareNodeName(example, ["li"]) || (example.nextElementSibling && compareNodeName(example.nextElementSibling, ["li"]));
  6933. }
  6934. let pageBar = document.createElement(inTable ? "tr" : (inLi ? "li" : "div"));
  6935. let upSpan = document.createElement("span");
  6936. let downSpan = document.createElement("span");
  6937. let pageText = document.createElement("a");
  6938. let pageNum;
  6939. pageBar.className = isHideBar ? "pagetual_pageBar hide" : "pagetual_pageBar";
  6940. pageBar.id = "pagetual_pageBar" + curPage;
  6941. pageBar.setAttribute("translate", "no");
  6942. if (isPause) {
  6943. pageBar.classList.add("stop");
  6944. }
  6945. pageBar.style.cssText = pageBarStyle;
  6946. pageBar.title = i18n(isPause ? "enable" : "disable");
  6947. upSpan.innerHTML = createHTML(upSvg);
  6948. upSpan.children[0].style.cssText = upSvgCSS;
  6949. upSpan.title = i18n("toTop");
  6950. downSpan.innerHTML = createHTML(downSvg);
  6951. downSpan.children[0].style.cssText = downSvgCSS;
  6952. downSpan.title = i18n("toBottom");
  6953. upSpan.style.cssText = initStyle;
  6954. downSpan.style.cssText = initStyle;
  6955. pageText.href = url;
  6956. pageText.style.cssText = pageTextStyle;
  6957. pageText.title = i18n("current");
  6958. if (openInNewTab == 1) pageText.target = "_blank";
  6959. pageBar.appendChild(upSpan);
  6960. pageBar.appendChild(pageText);
  6961. let touched = false;
  6962. let touchBodyHandler = e => {
  6963. touched = false;
  6964. getBody(document).removeEventListener('touchstart', touchBodyHandler, { passive: false, capture: false });
  6965. };
  6966. pageText.addEventListener("touchstart", e => {
  6967. if (touched) return;
  6968. touched = true;
  6969. pageText.style.pointerEvents = 'none';
  6970. setTimeout(() => {
  6971. pageText.style.pointerEvents = 'all';
  6972. }, 250);
  6973. getBody(document).addEventListener("touchstart", touchBodyHandler, { passive: false, capture: false });
  6974. }, { passive: false, capture: false });
  6975. if (ruleParser.nextTitle) {
  6976. pageText.innerHTML = createHTML(ruleParser.nextTitle + " ");
  6977. pageText.title = ruleParser.nextTitle;
  6978. }
  6979. if (ruleParser.curSiteRule.pageNum || pageNumReg.test(url)) {
  6980. pageText.innerHTML = createHTML(pageText.innerHTML + i18n("page"));
  6981. pageNum = document.createElement("span");
  6982. let num = ruleParser.getPageNumFromUrl(url, curPage);
  6983. pageNum.innerHTML = createHTML(num);
  6984. pageNum.className = "pagetual_pageNum";
  6985. pageNum.title = i18n("inputPageNum");
  6986. pageNum.style.cssText = pageTextStyle;
  6987. pageNum.style.cursor = "pointer";
  6988. pageNum.style.color = "";
  6989. pageNum.style.marginLeft = "5px";
  6990. pageNum.addEventListener("click", e => {
  6991. let pageInput = prompt(i18n("inputPageNum"), num || "1");
  6992. if (pageInput) {
  6993. let localPageBar = document.querySelector("#pagetual_pageBar" + pageInput);
  6994. if (localPageBar) {
  6995. scrollToPageBar(localPageBar);
  6996. } else {
  6997. let pageLink = ruleParser.getLinkByPage(url, pageInput);
  6998. if (pageLink) {
  6999. _GM_openInTab(pageLink, {active:true});
  7000. }
  7001. }
  7002. }
  7003. e.preventDefault();
  7004. e.stopPropagation();
  7005. });
  7006. pageBar.appendChild(pageNum);
  7007. } else {
  7008. pageText.innerHTML = createHTML(pageText.innerHTML + i18n("page") + curPage);
  7009. }
  7010. let preBtn = document.createElement("span");
  7011. preBtn.innerHTML = createHTML("∧");
  7012. preBtn.title = i18n("prevPage");
  7013. preBtn.className = "prevScreen";
  7014. 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; ";
  7015. let nextBtn = document.createElement("span");
  7016. nextBtn.innerHTML = createHTML("∨");
  7017. nextBtn.title = i18n("nextPage");
  7018. nextBtn.className = "nextScreen";
  7019. 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; ";
  7020. let localPage = curPage;
  7021. preBtn.addEventListener("click", e => {
  7022. e.stopPropagation();
  7023. e.preventDefault();
  7024. let prePageBar = document.querySelector("#pagetual_pageBar" + (localPage - 1));
  7025. if (prePageBar) {
  7026. scrollToPageBar(prePageBar);
  7027. } else {
  7028. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  7029. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  7030. }
  7031. });
  7032. nextBtn.addEventListener("click", e => {
  7033. e.stopPropagation();
  7034. e.preventDefault();
  7035. let nextPageBar = document.querySelector("#pagetual_pageBar" + (localPage + 1));
  7036. if (nextPageBar) {
  7037. scrollToPageBar(nextPageBar);
  7038. } else {
  7039. scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7040. window.scrollTo({ top: scrollH || 9999999, behavior: 'instant'});
  7041. }
  7042. });
  7043. if (!rulesData.hideBarArrow) {
  7044. pageText.insertBefore(preBtn, pageText.firstChild);
  7045. pageText.insertBefore(nextBtn, pageText.firstChild);
  7046. }
  7047. if (curForceIframe) {
  7048. let bgRing = document.createElement("span");
  7049. bgRing.className = "refreshRing";
  7050. bgRing.style.display = "none";
  7051. bgRing.innerHTML = createHTML(upSvg);
  7052. pageText.title = "Refresh";
  7053. pageText.appendChild(bgRing);
  7054. pageText.addEventListener("click", e => {
  7055. e.stopPropagation();
  7056. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  7057. e.preventDefault();
  7058. let nextEle = pageBar && pageBar.nextElementSibling;
  7059. if (nextEle && nextEle.name == 'pagetual-iframe') {
  7060. if (curForceIframe == nextEle) {
  7061. nextEle.setAttribute("loaded", "refresh");
  7062. }
  7063. nextEle.src = nextEle.src;
  7064. }
  7065. });
  7066. } else if (rulesData.pageBarMenu) {
  7067. pageText.addEventListener("click", e => {
  7068. e.stopPropagation();
  7069. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  7070. e.preventDefault();
  7071. picker.start();
  7072. });
  7073. }
  7074. pageBar.appendChild(downSpan);
  7075. if (forceState == 2) {
  7076. pageBar.style.width = "99%";
  7077. } else {
  7078. let parentStyle = _unsafeWindow.getComputedStyle(example.parentNode);
  7079. let parentWidth = example.parentNode.offsetWidth || parseInt(parentStyle.width);
  7080. pageBar.style.width = parentWidth - parseInt(parentStyle.paddingLeft) - parseInt(parentStyle.paddingRight) - 10 + "px";
  7081. pageBar.style.margin = '10px 5px';
  7082. if (parentStyle.display == "grid" || parentStyle.display == "inline-grid") {
  7083. pageBar.style.gridColumn = "1/-1";
  7084. }
  7085. if (inTable) {
  7086. example = compareNodeName(example, ["tr", "tbody"]) ? example : example.nextElementSibling || example;
  7087. if (compareNodeName(example, ["tbody"])) example = example.querySelector("tr");
  7088. let nextTr = example;
  7089. while (nextTr && nextTr.children.length == 0) nextTr = nextTr.nextElementSibling;
  7090. if (nextTr) example = nextTr;
  7091. let tdNum = 0;
  7092. if (exampleStyle.display == "table-row") {
  7093. [].forEach.call(example.children, el => {
  7094. tdNum += el.colSpan || 1;
  7095. });
  7096. } else {
  7097. [].forEach.call(example.children, el => {
  7098. if (compareNodeName(el, ["td", "th"])) {
  7099. tdNum += el.colSpan || 1;
  7100. }
  7101. });
  7102. }
  7103. pageBar.style.cssText = "";
  7104. pageBar.style.display = "table-row";
  7105. pageBar.style.backgroundColor = "unset";
  7106. pageBar.style.lineHeight = "20px";
  7107. pageBar.style.boxShadow = "";
  7108. let td = document.createElement("td");
  7109. td.colSpan = tdNum || 1;
  7110. let inTd = document.createElement("div");
  7111. inTd.style.cssText = pageBarStyle;
  7112. inTd.style.display = "";
  7113. inTd.className = pageBar.className;
  7114. pageBar.className = "";
  7115. inTd.appendChild(upSpan);
  7116. inTd.appendChild(pageText);
  7117. if (pageNum) inTd.appendChild(pageNum);
  7118. inTd.appendChild(downSpan);
  7119. td.appendChild(inTd);
  7120. pageBar.appendChild(td);
  7121. } else if (inLi) {
  7122. example = compareNodeName(example, ["li"]) ? example : example.nextElementSibling || example;
  7123. pageBar.style.opacity = 1;
  7124. pageBar.style.display = getComputedStyle(example).display;
  7125. pageBar.style.backgroundColor = "unset";
  7126. pageBar.style.lineHeight = "20px";
  7127. pageBar.style.boxShadow = "";
  7128. pageBar.style.border = "";
  7129. pageBar.style.maxWidth = "unset";
  7130. pageBar.style.flex = "auto";
  7131. let inTd = document.createElement("div");
  7132. inTd.style.cssText = pageBarStyle;
  7133. inTd.style.display = "";
  7134. inTd.style.margin = "0"
  7135. inTd.style.padding = "0 0";
  7136. inTd.style.textAlign = "center";
  7137. inTd.style.minWidth = "150px";
  7138. inTd.style.width = 'calc(100% - 20px)';
  7139. inTd.className = pageBar.className;
  7140. pageBar.className = "";
  7141. inTd.appendChild(upSpan);
  7142. inTd.appendChild(pageText);
  7143. if (pageNum) inTd.appendChild(pageNum);
  7144. inTd.appendChild(downSpan);
  7145. if (pageBar.style.display === 'table-row') {
  7146. let td = document.createElement("td");
  7147. td.colSpan = example.children.length;
  7148. td.style.width = '100%';
  7149. td.appendChild(inTd);
  7150. pageBar.appendChild(td);
  7151. } else {
  7152. inTd.style.width = '100%';
  7153. pageBar.appendChild(inTd);
  7154. }
  7155. }
  7156. }
  7157.  
  7158. upSpan.addEventListener("click", e => {
  7159. getBody(document).scrollTop = 0;
  7160. document.documentElement.scrollTop = 0;
  7161. e.preventDefault();
  7162. e.stopPropagation();
  7163. });
  7164. downSpan.addEventListener("click", e => {
  7165. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  7166. changeStop(true);
  7167. }
  7168. pageBar.title = i18n(isPause ? "enable" : "disable");
  7169. scrollH=Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  7170. getBody(document).scrollTop = scrollH || 9999999;
  7171. document.documentElement.scrollTop = scrollH || 9999999;
  7172. e.preventDefault();
  7173. e.stopPropagation();
  7174. });
  7175. pageBar.addEventListener("click", e => {
  7176. changeStop(!isPause);
  7177. pageBar.title = i18n(isPause ? "enable" : "disable");
  7178. });
  7179. ruleParser.insertElement(pageBar);
  7180. ruleParser.runPageBar(pageBar);
  7181.  
  7182. lastPageBar = pageBar;
  7183. return pageBar;
  7184. }
  7185.  
  7186. async function waitForElement(sel, doc) {
  7187. if (!sel) return null;
  7188. return new Promise((resolve) => {
  7189. let checkInv = setInterval(() => {
  7190. let result = getElement(sel, doc, null, true);
  7191. if (result) {
  7192. clearInterval(checkInv);
  7193. resolve(result);
  7194. }
  7195. }, 100);
  7196. });
  7197. }
  7198.  
  7199. async function clickAction(sel, doc) {
  7200. let btn = await waitForElement(sel, doc);
  7201. emuClick(btn);
  7202. }
  7203.  
  7204. async function enterAction(sel, doc) {
  7205. let btn = await waitForElement(sel, doc);
  7206. let eventParam = { key: "Enter", keyCode: 13, bubbles: true };
  7207. let event = new KeyboardEvent('keydown', eventParam);
  7208. btn.dispatchEvent(event);
  7209. event = new KeyboardEvent('keyup', eventParam);
  7210. btn.dispatchEvent(event);
  7211. event = new KeyboardEvent('keypress', eventParam);
  7212. btn.dispatchEvent(event);
  7213. }
  7214.  
  7215. async function inputAction(sel, v, doc) {
  7216. let input = await waitForElement(sel, doc);
  7217. let event = new Event('focus', { bubbles: true });
  7218. input.dispatchEvent(event);
  7219. let lastValue = input.value;
  7220. if (input.nodeName.toUpperCase() == "INPUT") {
  7221. var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
  7222. nativeInputValueSetter.call(input, v);
  7223. } else if (input.nodeName.toUpperCase() == "TEXTAREA") {
  7224. var nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
  7225. nativeTextareaValueSetter.call(input, v);
  7226. } else {
  7227. input.innerHTML = createHTML(v);
  7228. }
  7229. event = new Event('input', { bubbles: true });
  7230. let tracker = input._valueTracker;
  7231. if (tracker) {
  7232. tracker.setValue(lastValue);
  7233. }
  7234. input.dispatchEvent(event);
  7235. event = new Event('change', { bubbles: true });
  7236. input.dispatchEvent(event);
  7237. debug(input, `input ${sel}`);
  7238. }
  7239.  
  7240. function emuClick(btn) {
  7241. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  7242. let orgHref = btn.getAttribute('href');
  7243. if (orgHref && orgHref.replace(location.origin + location.pathname, "").indexOf("#") === 0) {
  7244. let hashAction = e => {
  7245. e.preventDefault();
  7246. getBody(document).scrollTop = curScroll;
  7247. document.documentElement.scrollTop = curScroll;
  7248. btn.removeEventListener('click', hashAction, false);
  7249. };
  7250. btn.addEventListener('click', hashAction, false);
  7251. }
  7252. if (!PointerEvent) return btn.click();
  7253. let eventParam = {
  7254. isTrusted: true,
  7255. altKey: false,
  7256. azimuthAngle: 0,
  7257. bubbles: true,
  7258. button: 0,
  7259. buttons: 0,
  7260. clientX: 1,
  7261. clientY: 1,
  7262. cancelBubble: false,
  7263. cancelable: true,
  7264. composed: true,
  7265. ctrlKey: false,
  7266. defaultPrevented: false,
  7267. detail: 1,
  7268. eventPhase: 2,
  7269. fromElement: null,
  7270. height: 1,
  7271. isPrimary: false,
  7272. metaKey: false,
  7273. pointerId: 1,
  7274. pointerType: "mouse",
  7275. pressure: 0,
  7276. relatedTarget: null,
  7277. returnValue: true,
  7278. shiftKey: false,
  7279. toElement: null,
  7280. twist: 0,
  7281. which: 1
  7282. };
  7283. let mouseEvent = new PointerEvent("mousedown", eventParam);
  7284. btn.dispatchEvent(mouseEvent);
  7285. mouseEvent = new PointerEvent("mouseup", eventParam);
  7286. btn.dispatchEvent(mouseEvent);
  7287. let dispatchTouchEvent = (ele, type) => {
  7288. let touchEvent;
  7289. try {
  7290. touchEvent = document.createEvent('TouchEvent')
  7291. touchEvent.initTouchEvent(type, true, true)
  7292. } catch (err) {
  7293. try {
  7294. touchEvent = document.createEvent('UIEvent')
  7295. touchEvent.initUIEvent(type, true, true)
  7296. } catch (err) {
  7297. touchEvent = document.createEvent('Event')
  7298. touchEvent.initEvent(type, true, true)
  7299. }
  7300. }
  7301. if (touchEvent) {
  7302. try {
  7303. touchEvent.targetTouches = [{
  7304. pageX: 1,
  7305. pageY: 1,
  7306. clientX: 1,
  7307. clientY: 1,
  7308. target: btn
  7309. }];
  7310. touchEvent.touches = [{
  7311. pageX: 1,
  7312. pageY: 1,
  7313. clientX: 1,
  7314. clientY: 1,
  7315. target: btn
  7316. }];
  7317. touchEvent.changedTouches = [{
  7318. pageX: 1,
  7319. pageY: 1,
  7320. clientX: 1,
  7321. clientY: 1,
  7322. target: btn
  7323. }];
  7324. } catch (err) {}
  7325. ele.dispatchEvent(touchEvent);
  7326. }
  7327. }
  7328. dispatchTouchEvent(btn, "touchstart");
  7329. dispatchTouchEvent(btn, "touchend");
  7330.  
  7331. btn.click();
  7332. }
  7333.  
  7334. var failFromIframe = 0;
  7335. var inCors = false;
  7336. var checkRemoveIntv;
  7337. function requestFromIframe(url, callback){
  7338. if (location.protocol === 'https:' && !/^https:/.test(url)) {
  7339. ruleParser.noValidContent(url);
  7340. }
  7341. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  7342. let iframe = document.createElement('iframe');
  7343. iframe.name = 'pagetual-iframe';
  7344. iframe.width = '100%';
  7345. iframe.height = '1000';
  7346. iframe.frameBorder = '0';
  7347. if (ruleParser.curSiteRule.sandbox != false) {
  7348. iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  7349. }
  7350. 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;';
  7351. let waitTime = 100, checkEval;
  7352. ruleParser.runWait((_checkEval, _waitTime) => {
  7353. if (_checkEval) {
  7354. checkEval = _checkEval;
  7355. }
  7356. if (_waitTime) {
  7357. waitTime = _waitTime;
  7358. }
  7359. });
  7360. if (checkRemoveIntv) clearInterval(checkRemoveIntv);
  7361. checkRemoveIntv = setInterval(() => {
  7362. if (!iframe || !getBody(document).contains(iframe)) {
  7363. clearInterval(checkRemoveIntv);
  7364. loadPageOver();
  7365. }
  7366. }, 500);
  7367. let loadedHandler = e => {
  7368. if (e.data != 'pagetual-iframe:DOMLoaded' && e.type != 'load') return;
  7369. clearInterval(checkRemoveIntv);
  7370. window.removeEventListener('message', loadedHandler, false);
  7371. iframe.removeEventListener('load', loadedHandler, false);
  7372. let tryTimes = 0;
  7373. function checkIframe() {
  7374. if (urlChanged || isPause) {
  7375. return callback(false, false);
  7376. }
  7377. try {
  7378. let doc = iframe.contentDocument || iframe.contentWindow.document;
  7379. let base = doc.querySelector("base");
  7380. ruleParser.basePath = base ? base.href : url;
  7381. let eles = ruleParser.getPageElement(doc, iframe.contentWindow, tryTimes < 25);
  7382. if (checkEval && !checkEval(doc)) {
  7383. setTimeout(() => {
  7384. checkIframe();
  7385. }, waitTime);
  7386. return;
  7387. } else if (eles && eles.length > 0) {
  7388. callback(doc, eles);
  7389. } else if (tryTimes++ < 100) {
  7390. getBody(doc).scrollTop = 9999999;
  7391. doc.documentElement.scrollTop = 9999999;
  7392. setTimeout(() => {
  7393. checkIframe();
  7394. }, waitTime);
  7395. return;
  7396. } else {
  7397. if (failFromIframe++ > 2) {
  7398. failFromIframe = 0;
  7399. debug("Stop as failFromIframe");
  7400. changeStop(true);
  7401. callback(false, false);
  7402. } else {
  7403. ruleParser.noValidContent(url);
  7404. callback(false, false);
  7405. }
  7406. }
  7407. } catch(e) {
  7408. inCors = true;
  7409. if (forceState === 3) {
  7410. debug("Stop as cors");
  7411. isPause = true;
  7412. }
  7413. if (!ruleParser.curSiteRule.pageElement) {
  7414. ruleParser.curSiteRule.pageElement = allOfBody;
  7415. ruleParser.getInsert(true);
  7416. }
  7417. ruleParser.curSiteRule.action = 0;
  7418. ruleParser.nextLinkHref = url;
  7419. callback(false, false);
  7420. nextPage();
  7421. }
  7422. if (iframe && iframe.parentNode) iframe.parentNode.removeChild(iframe);
  7423. }
  7424. setTimeout(() => {
  7425. checkIframe();
  7426. }, waitTime);
  7427. };
  7428. let code = ruleParser.curSiteRule.iframeInit;
  7429. if (code) {
  7430. let checkReady = setInterval(() => {
  7431. let doc;
  7432. try {
  7433. doc = iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document);
  7434. } catch(e) {
  7435. clearInterval(checkReady);
  7436. return;
  7437. }
  7438. if (doc) {
  7439. try {
  7440. Function('win', 'iframe', '"use strict";' + code)(iframe.contentWindow, iframe);
  7441. clearInterval(checkReady);
  7442. } catch(e) {
  7443. debug(e);
  7444. }
  7445. }
  7446. }, 50);
  7447. }
  7448. window.addEventListener('message', loadedHandler, false);
  7449. iframe.addEventListener('load', loadedHandler, false);
  7450. iframe.src = url;
  7451. try {
  7452. getBody(document).appendChild(iframe);
  7453. } catch (e) {
  7454. return callback(false, false);
  7455. }
  7456. }
  7457.  
  7458. var emuIframe, lastActiveUrl, orgContent, meetCors = false;
  7459. function emuPage(callback) {
  7460. let orgPage = null, preContent = null, iframeDoc, checkTimes = 0, loadmoreBtn, pageEle, nextLink, loadmoreEnd = false, waitTimes = 80, changed = false;
  7461. function returnFalse(log) {
  7462. if (curPage > 1 && rulesData.lastPageTips) showTips(i18n("lastPage"));
  7463. debug(log);
  7464. isPause = true;
  7465. callback(false, false);
  7466. if (emuIframe && emuIframe.parentNode) {
  7467. emuIframe.parentNode.removeChild(emuIframe);
  7468. sideController.remove();
  7469. emuIframe = null;
  7470. }
  7471. }
  7472. async function checkPage() {
  7473. if (isPause) return loadPageOver();
  7474. try {
  7475. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  7476. } catch(e) {
  7477. returnFalse("Stop as cors");
  7478. return;
  7479. }
  7480.  
  7481. let waitTime = 200, checkEval;
  7482. ruleParser.runWait((_checkEval, _waitTime) => {
  7483. if (_checkEval) {
  7484. checkEval = _checkEval;
  7485. }
  7486. if (_waitTime) {
  7487. waitTime = _waitTime;
  7488. }
  7489. });
  7490.  
  7491. if (!orgPage) {
  7492. if (!loadmoreEnd) {
  7493. loadmoreBtn = getLoadMore(iframeDoc);
  7494. if (loadmoreBtn && isVisible(loadmoreBtn, emuIframe.contentWindow)) {
  7495. emuClick(loadmoreBtn);
  7496. let intv = setInterval(() => {
  7497. loadmoreBtn = getLoadMore(iframeDoc);
  7498. if (!loadmoreBtn || !getBody(document).contains(loadmoreBtn) || !isVisible(loadmoreBtn, emuIframe.contentWindow)) {
  7499. clearInterval(intv);
  7500. loadmoreEnd = true;
  7501. setTimeout(() => {
  7502. checkPage();
  7503. }, 500);
  7504. } else if (isInViewPort(loadmoreBtn)) {
  7505. emuClick(loadmoreBtn);
  7506. }
  7507. }, 200);
  7508. return;
  7509. } else {
  7510. loadmoreEnd = true;
  7511. }
  7512. }
  7513. if (checkEval && !checkEval(iframeDoc)) {
  7514. waitTimes = 50;
  7515. setTimeout(() => {
  7516. checkPage();
  7517. }, waitTime);
  7518. return;
  7519. } else {
  7520. if (!nextLink || !nextLink.offsetParent) nextLink = await ruleParser.getNextLink(iframeDoc, true);
  7521. if (nextLink) pageEle = ruleParser.getPageElement(iframeDoc, emuIframe.contentWindow, true);
  7522. if (!pageEle || pageEle.length == 0 || !nextLink) {
  7523. getBody(iframeDoc).scrollTop = 9999999;
  7524. iframeDoc.documentElement.scrollTop = 9999999;
  7525. if (waitTimes-- > 0) {
  7526. setTimeout(() => {
  7527. checkPage();
  7528. }, waitTime);
  7529. return;
  7530. }
  7531. }
  7532. }
  7533. if (!pageEle || pageEle.length == 0) {
  7534. returnFalse("Stop as no page when emu");
  7535. return;
  7536. }
  7537. pageEle = [].filter.call(pageEle, ele => {return ele && !compareNodeName(ele, ["style", "script", "meta"])});
  7538. if (compareNodeName(pageEle[0], ["ul"]) || pageEle.length == 1) pageEle = pageEle[0];
  7539. else if (pageEle[0].parentNode == pageEle[1].parentNode) {
  7540. pageEle = pageEle[0].parentNode;
  7541. } else {
  7542. pageEle = pageEle[0];
  7543. }
  7544. if (ruleParser.curSiteRule.singleUrl && orgContent != pageEle.innerHTML) {
  7545. orgContent = pageEle.innerHTML;
  7546. if (waitTimes-- > 0) {
  7547. setTimeout(() => {
  7548. checkPage();
  7549. }, waitTime);
  7550. return;
  7551. }
  7552. }
  7553. orgPage = pageEle;
  7554. if (nextLink) {
  7555. if (compareNodeName(orgPage, ["img"])) {
  7556. if (!ruleParser.curSiteRule.lazyImgSrc) ruleParser.curSiteRule.lazyImgSrc = "0";
  7557. if (orgPage.src) {
  7558. orgContent = orgPage.src;
  7559. } else {
  7560. setTimeout(() => {
  7561. checkPage();
  7562. }, 500);
  7563. return;
  7564. }
  7565. } else {
  7566. orgContent = orgPage.innerHTML;
  7567. }
  7568. preContent = orgContent;
  7569. if (!isVisible(nextLink, emuIframe.contentWindow)) {
  7570. returnFalse("Stop as next hide when emu");
  7571. } else {
  7572. emuClick(nextLink);
  7573. setTimeout(() => {
  7574. checkPage();
  7575. }, 500);
  7576. }
  7577. } else {
  7578. returnFalse("Stop as no next when emu");
  7579. }
  7580. return;
  7581. }
  7582. if (!ruleParser.checkStopSign(nextLink, iframeDoc)) {
  7583. return returnFalse("Stop as stopSign");;
  7584. }
  7585. if (checkTimes++ > 200) {
  7586. returnFalse("Stop as timeout when emu");
  7587. return;
  7588. }
  7589. let eles = ruleParser.getPageElement(iframeDoc, emuIframe.contentWindow, true), checkItem;
  7590. if (eles && eles.length > 0) {
  7591. eles = [].filter.call(eles, ele => {return ele && !compareNodeName(ele, ["style", "script", "meta"])});
  7592. if (compareNodeName(eles[0], ["ul"]) || eles.length == 1) checkItem = eles[0];
  7593. else if (eles[0].parentNode == eles[1].parentNode) {
  7594. checkItem = eles[0].parentNode;
  7595. } else {
  7596. checkItem = eles[0];
  7597. }
  7598. }
  7599. if (!checkItem || (checkEval && !checkEval(iframeDoc))) {
  7600. if (checkEval) checkTimes = 0;
  7601. setTimeout(() => {
  7602. checkPage();
  7603. }, waitTime);
  7604. } else {
  7605. let checkInner;
  7606. if (compareNodeName(checkItem, ["img"])) {
  7607. if (checkItem.src) {
  7608. checkInner = checkItem.src;
  7609. } else {
  7610. setTimeout(() => {
  7611. checkPage();
  7612. }, waitTime);
  7613. return;
  7614. }
  7615. } else {
  7616. checkInner = checkItem.innerHTML;
  7617. }
  7618. if (orgPage != checkItem || checkInner != preContent) {
  7619. changed = true;
  7620. orgPage = checkItem;
  7621. preContent = checkInner;
  7622. setTimeout(() => {
  7623. checkPage();
  7624. }, waitTime);
  7625. } else if (changed) {
  7626. checkTimes = 0;
  7627. if (orgContent == preContent && (ruleParser.curSiteRule.singleUrl || ruleParser.curSiteRule.stopSame)) {
  7628. returnFalse("Stop as same content");
  7629. } else {
  7630. orgContent = preContent;
  7631. callback(iframeDoc, eles);
  7632. }
  7633. } else {
  7634. if (checkTimes % 10 === 5) {
  7635. if (!nextLink || !nextLink.offsetParent) {
  7636. nextLink = await ruleParser.getNextLink(iframeDoc, true);
  7637. }
  7638. if (nextLink) {
  7639. emuClick(nextLink);
  7640. }
  7641. }
  7642. setTimeout(() => {
  7643. checkPage();
  7644. }, waitTime);
  7645. }
  7646. }
  7647. }
  7648. if (!emuIframe) {
  7649. let loaded = false;
  7650. emuIframe = document.createElement('iframe');
  7651. emuIframe.name = 'pagetual-iframe';
  7652. let notSetSandbox = typeof ruleParser.curSiteRule.sandbox == 'undefined';
  7653. if (notSetSandbox || ruleParser.curSiteRule.sandbox == true) {
  7654. emuIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  7655. } else if (ruleParser.curSiteRule.sandbox) {
  7656. emuIframe.sandbox = ruleParser.curSiteRule.sandbox;
  7657. }
  7658. emuIframe.width = '100%';
  7659. emuIframe.height = '100%';
  7660. emuIframe.frameBorder = '0';
  7661. 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;';
  7662. emuIframe.addEventListener("load", e => {
  7663. setTimeout(() => {
  7664. try {
  7665. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  7666. } catch(e) {
  7667. if (e.message && e.message.indexOf("cross-origin") != -1 && notSetSandbox && emuIframe.hasAttribute("sandbox")) {
  7668. emuIframe.removeAttribute("sandbox");
  7669. meetCors = true;
  7670. callback(false, false);
  7671. } else {
  7672. returnFalse("Stop as cors");
  7673. }
  7674. return;
  7675. }
  7676. meetCors = false;
  7677. let code = ruleParser.curSiteRule.init;
  7678. if (code) {
  7679. try {
  7680. 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)});
  7681. } catch(e) {
  7682. debug(e);
  7683. }
  7684. }
  7685. if (loaded) return;
  7686. loaded = true;
  7687. checkPage();
  7688. }, 500);
  7689. });
  7690. let code = ruleParser.curSiteRule.iframeInit;
  7691. if (code) {
  7692. let checkReady = setInterval(() => {
  7693. try {
  7694. iframeDoc = emuIframe.contentDocument || (emuIframe.contentWindow && emuIframe.contentWindow.document);
  7695. } catch(e) {
  7696. clearInterval(checkReady);
  7697. return;
  7698. }
  7699. if (iframeDoc) {
  7700. try {
  7701. Function('win', 'iframe', '"use strict";' + code)(emuIframe.contentWindow, emuIframe);
  7702. clearInterval(checkReady);
  7703. } catch(e) {
  7704. debug(e);
  7705. }
  7706. }
  7707. }, 50);
  7708. }
  7709. if (!lastActiveUrl) lastActiveUrl = location.href;
  7710. emuIframe.src = lastActiveUrl;
  7711. getBody(document).appendChild(emuIframe);
  7712. } else {
  7713. if (emuIframe.src != lastActiveUrl || meetCors) {
  7714. emuIframe.src = lastActiveUrl;
  7715. return;
  7716. }
  7717. checkPage();
  7718. }
  7719. }
  7720.  
  7721. var scrollToResizeInited = false;
  7722. var resizePool = [];
  7723. var scrollingToResize = false;
  7724.  
  7725. function isTouchViewPort(element) {
  7726. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  7727. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  7728. const {
  7729. top,
  7730. right,
  7731. bottom,
  7732. left,
  7733. } = element.getBoundingClientRect();
  7734.  
  7735. return (
  7736. top < viewHeight &&
  7737. left < viewWidth &&
  7738. right > 0 &&
  7739. bottom > 0
  7740. );
  7741. }
  7742.  
  7743. function resizeIframe(iframe, frameDoc, pageEle) {
  7744. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  7745. if (ruleParser.curSiteRule.singleUrl || forceState === 2) {
  7746. let height = (getBody(frameDoc).scrollHeight || getBody(frameDoc).offsetHeight || 500);
  7747. if (!iframe.style.height || height - parseInt(iframe.style.height) > window.innerHeight) {
  7748. iframe.style.height = height + "px";
  7749. iframe.style.minHeight = iframe.style.height;
  7750. }
  7751. iframe.style.width = "100%";
  7752. frameDoc.documentElement.scrollTop = 0;
  7753. frameDoc.documentElement.scrollLeft = 0;
  7754. } else {
  7755. if (pageEle) {
  7756. let fitWidth = ruleParser.curSiteRule.fitWidth !== false;
  7757. let targetElement = pageEle[0];
  7758. if (!targetElement) return;
  7759. if (pageEle.length > 1) {
  7760. targetElement = targetElement.parentNode;
  7761. }
  7762. let scrollHeight = targetElement.scrollHeight || targetElement.offsetHeight || 500;
  7763. iframe.style.height = scrollHeight + "px";
  7764. let scrollTop = 0, scrollLeft = 0;
  7765. getBody(frameDoc).scrollTop = 0;
  7766. getBody(frameDoc).scrollLeft = 0;
  7767. while (targetElement && targetElement.offsetParent) {
  7768. targetElement.offsetParent.scrollTop = targetElement.offsetTop;
  7769. if (targetElement.offsetParent.scrollTop == 0) {
  7770. scrollTop += targetElement.offsetTop;
  7771. }
  7772. if (fitWidth) {
  7773. targetElement.offsetParent.scrollLeft = targetElement.offsetLeft;
  7774. if (targetElement.offsetParent.scrollLeft == 0) {
  7775. scrollLeft += targetElement.offsetLeft;
  7776. }
  7777. }
  7778. targetElement = targetElement.offsetParent;
  7779. }
  7780. frameDoc.documentElement.scrollTop = scrollTop;
  7781. frameDoc.documentElement.scrollLeft = scrollLeft;
  7782. if (frameDoc.documentElement.scrollTop == 0 && frameDoc.documentElement.scrollLeft == 0) {
  7783. getBody(frameDoc).scrollTop += scrollTop;
  7784. getBody(frameDoc).scrollLeft += scrollLeft;
  7785. }
  7786. if (!fitWidth && iframe.style.marginLeft == '0px') {
  7787. iframe.style.width = "100vw";
  7788. iframe.style.maxWidth = "100vw";
  7789. iframe.style.minWidth = "100vw";
  7790. var cWidth = document.body.clientWidth || document.documentElement.clientWidth;
  7791. var iWidth = window.innerWidth;
  7792. iframe.style.marginLeft = -iframe.getBoundingClientRect().left - (iWidth - cWidth) / 2 + "px";
  7793. }
  7794. }
  7795. }
  7796. let newScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  7797. if (newScroll != curScroll) {
  7798. getBody(document).scrollTop = curScroll;
  7799. document.documentElement.scrollTop = curScroll;
  7800. }
  7801. }
  7802.  
  7803. function scrollToResize(e) {
  7804. if (scrollingToResize) return;
  7805. else {
  7806. scrollingToResize = true;
  7807. let resizeHandler = () => {
  7808. let touched = 0;
  7809. for (let i = 0; i < resizePool.length; i++) {
  7810. let resizeArr = resizePool[i];
  7811. let iframe = resizeArr[1]();
  7812. if (isTouchViewPort(iframe)) {
  7813. touched++;
  7814. let pageEle = resizeArr[0]();
  7815. let frameDoc = resizeArr[2]();
  7816. resizeIframe(iframe, frameDoc, pageEle);
  7817. } else if (touched) {
  7818. if (touched == 1) {
  7819. let pageEle = resizeArr[0]();
  7820. let frameDoc = resizeArr[2]();
  7821. resizeIframe(iframe, frameDoc, pageEle);
  7822. }
  7823. break;
  7824. } else if (!iframe.parentNode) {
  7825. resizePool.splice(i, 1);
  7826. break;
  7827. }
  7828. }
  7829. };
  7830. setTimeout(() => {
  7831. scrollingToResize = false;
  7832. }, 300);
  7833. resizeHandler();
  7834. }
  7835. }
  7836.  
  7837. var curForceIframe;
  7838. function forceIframe(url, callback) {
  7839. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  7840. let curIframe = document.createElement('iframe'), iframeDoc, pageElement = null, inAction = true;
  7841. let loadedHandler = () => {
  7842. let getPageEle = () => {
  7843. if (ruleParser.curSiteRule.singleUrl) {
  7844. return null;
  7845. } else {
  7846. if (!pageElement || pageElement.length === 0 || !pageElement[0].offsetParent) {
  7847. pageElement = ruleParser.getPageElement(iframeDoc, curIframe.contentWindow);
  7848. }
  7849. return pageElement;
  7850. }
  7851. };
  7852. resizeIframe(curIframe, iframeDoc, getPageEle());
  7853. let loaded = curIframe.getAttribute("loaded");
  7854. if (loaded == "true") {
  7855. return;
  7856. }
  7857. curIframe.setAttribute("loaded", "true");
  7858. let getIframe = () => {
  7859. return curIframe;
  7860. };
  7861. let getFrameDoc = () => {
  7862. return iframeDoc;
  7863. };
  7864. ruleParser.insertPage(iframeDoc, [], url, ele => {
  7865. callback(curIframe, loaded == "refresh");
  7866. inAction = false;
  7867. }, true);
  7868. if (!loaded) {
  7869. resizePool.push([getPageEle, getIframe, getFrameDoc]);
  7870. }
  7871. };
  7872. let checkIframeTimer = setInterval(() => {
  7873. if (!curIframe.parentNode) {
  7874. clearInterval(checkIframeTimer);
  7875. return curIframe.getAttribute("loaded") == "true" || callback(false);
  7876. }
  7877. }, 500);
  7878. let code = ruleParser.curSiteRule.iframeInit;
  7879. if (code) {
  7880. let checkReady = setInterval(() => {
  7881. try {
  7882. iframeDoc = curIframe.contentDocument || (curIframe.contentWindow && curIframe.contentWindow.document);
  7883. } catch(e) {
  7884. clearInterval(checkReady);
  7885. return;
  7886. }
  7887. if (iframeDoc) {
  7888. try {
  7889. Function('win', 'iframe', '"use strict";' + code)(curIframe.contentWindow, curIframe);
  7890. clearInterval(checkReady);
  7891. } catch(e) {
  7892. debug(e);
  7893. }
  7894. }
  7895. }, 50);
  7896. }
  7897. curIframe.name = 'pagetual-iframe';
  7898. curIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  7899. curIframe.frameBorder = '0';
  7900. curIframe.scrolling = "no";
  7901. 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;';
  7902. curIframe.addEventListener("load", e => {
  7903. clearInterval(checkIframeTimer);
  7904. if (isPause) return callback(false);
  7905. try {
  7906. iframeDoc = curIframe.contentDocument || curIframe.contentWindow.document;
  7907. } catch(e) {
  7908. debug("Stop as cors");
  7909. isPause = true;
  7910. callback(false);
  7911. return;
  7912. }
  7913. let css = ruleParser.curSiteRule.css || rulesData.customCss;
  7914. if (css) {
  7915. let cssArr = css.split("inIframe:");
  7916. if (cssArr && cssArr.length > 1) {
  7917. let styleEle = iframeDoc.createElement("style");
  7918. styleEle.innerHTML = cssArr[1];
  7919. iframeDoc.head.appendChild(styleEle);
  7920. }
  7921. }
  7922. loadedHandler();
  7923. let code = ruleParser.curSiteRule.init;
  7924. if (code) {
  7925. try {
  7926. 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)});
  7927. } catch(e) {
  7928. debug(e);
  7929. }
  7930. }
  7931. iframeDoc.addEventListener('wheel', e => {
  7932. document.dispatchEvent(new Event('wheel'));
  7933. }, true);
  7934. });
  7935. let checkTimes = 0, findPageEle = false;
  7936. let forceRefresh = e => {
  7937. if (inAction || !iframeDoc) return;
  7938. inAction = true;
  7939. let foundNext = () => {
  7940. document.removeEventListener("scroll", forceRefresh);
  7941. }
  7942. setTimeout(async () => {
  7943. inAction = false;
  7944. if (!ruleParser.nextLinkHref && !isPause) {
  7945. checkTimes++;
  7946. await ruleParser.getNextLink(iframeDoc, true);
  7947. if (ruleParser.nextLinkHref) {
  7948. foundNext();
  7949. if (isLoading) isLoading = false;
  7950. } else if (checkTimes >= 10) {
  7951. foundNext();
  7952. } else if (checkTimes >= 3 && !findPageEle) {
  7953. if (!pageElement) pageElement = ruleParser.getPageElement(iframeDoc, curIframe.contentWindow);
  7954. if (!pageElement) {
  7955. inAction = true;
  7956. curIframe.contentWindow.location.reload();
  7957. } else {
  7958. findPageEle = true;
  7959. }
  7960. }
  7961. } else {
  7962. foundNext();
  7963. }
  7964. }, 100);
  7965. };
  7966. document.addEventListener("scroll", forceRefresh);
  7967. curIframe.src = url;
  7968. curForceIframe = curIframe;
  7969. let insert = ruleParser.getInsert();
  7970. let body = getBody(document);
  7971. let curScroll = body.scrollTop || document.documentElement.scrollTop;
  7972. if (forceState == 2) {
  7973. document.documentElement.appendChild(loadingDiv);
  7974. body.appendChild(curIframe);
  7975. let bodyStyle = getComputedStyle(body);
  7976. if (bodyStyle.display == "flex" || bodyStyle.display == "inline-flex") {
  7977. body.style.flexDirection = "column";
  7978. }
  7979. } else {
  7980. ruleParser.insertElement(curIframe);
  7981. }
  7982. body.scrollTop = curScroll;
  7983. document.documentElement.scrollTop = curScroll;
  7984.  
  7985. if (!scrollToResizeInited) {
  7986. scrollToResizeInited = true;
  7987. document.addEventListener("scroll", scrollToResize);
  7988. }
  7989. return curIframe;
  7990. }
  7991.  
  7992. function loadPageOver() {
  7993. isLoading = false;
  7994. stopScroll = true;
  7995. setTimeout(() => {stopScroll = false}, 300);
  7996. if (loadingDiv.parentNode) {
  7997. loadingDiv.parentNode.removeChild(loadingDiv);
  7998. }
  7999. let rate = (ruleParser.curSiteRule.rate || rulesData.rate || 1);
  8000. if (rate != 1 && !clickMode) {
  8001. setTimeout(() => {
  8002. if (distToBottom() < bottomGap) {
  8003. nextPage();
  8004. }
  8005. }, 1);
  8006. }
  8007. }
  8008.  
  8009. function checkAutoLoadNum() {
  8010. if (autoLoadNum >= 0) {
  8011. if (autoLoadNum != 0 && --autoLoadNum == 0) {
  8012. autoLoadNum = -1;
  8013. } else {
  8014. setTimeout(() => nextPage(), 1);
  8015. }
  8016. }
  8017. }
  8018.  
  8019. var tryTimes = 0, showedLastPageTips = false;
  8020. async function nextPage() {
  8021. if (typeof ruleParser.curSiteRule.manualMode == 'undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode) return;
  8022. if (clickMode) return;
  8023. if (isPause || isLoading || forceState == 1) return;
  8024. if (ruleParser.curSiteRule.delay) {
  8025. try {
  8026. let checkDelay = ((typeof ruleParser.curSiteRule.delay == 'function') ? ruleParser.curSiteRule.delay : Function('"use strict";' + ruleParser.curSiteRule.delay))();
  8027. if (!checkDelay) return;
  8028. } catch(e) {
  8029. debug(e);
  8030. }
  8031. }
  8032. let nextLink = ruleParser.nextLinkHref;
  8033. if (!nextLink) {
  8034. isLoading = true;
  8035. if (curPage == 1) {
  8036. await ruleParser.getNextLink(document, true);
  8037. nextLink = ruleParser.nextLinkHref;
  8038. }
  8039. if (!nextLink) {
  8040. if (curPage == 1 && (ruleParser.curSiteRule.pinUrl || tryTimes++ <= 3)) {
  8041. setTimeout(() => {isLoading = false}, 500);
  8042. } else if (curPage > 1 && rulesData.lastPageTips && !showedLastPageTips) {
  8043. showTips(i18n("lastPage"));
  8044. showedLastPageTips = true;
  8045. }
  8046. return;
  8047. }
  8048. isLoading = false;
  8049. }
  8050. showedLastPageTips = false;
  8051. let pvGallery = document.querySelector("span.pv-gallery-container");
  8052. if (pvGallery && pvGallery.style.display != "none") return;
  8053. let insert = ruleParser.getInsert();
  8054. if (insert) {
  8055. if (curPage == 1) initView();
  8056. /*if (curPage == 1) {
  8057. window.postMessage({
  8058. command: 'pagetual.insert'
  8059. }, '*');
  8060. }*/
  8061. let isJs = ruleParser.curSiteRule.action == 3 || ruleParser.hrefIsJs(nextLink);
  8062. if (!isJs) {
  8063. emuIframe = null;
  8064. lastActiveUrl = nextLink;
  8065. if (location.protocol == "https:" && /^http:/.test(nextLink)) {
  8066. nextLink = nextLink.replace(/^http/, "https");
  8067. }
  8068. }
  8069. isLoading = true;
  8070. if (curPage != 1 || !isJs || !ruleParser.curSiteRule.singleUrl) {
  8071. ruleParser.beginLoading(loadingDiv);
  8072. }
  8073. let sleep = ruleParser.curSiteRule.sleep || 0;
  8074. setTimeout(() => {
  8075. if (ruleParser.curSiteRule.pageElementByJs) {
  8076. var over = eles => {
  8077. if (urlChanged || isPause) {
  8078. loadPageOver();
  8079. return;
  8080. }
  8081. if (eles) {
  8082. ruleParser.insertPage(document, eles, nextLink, () => {
  8083. createPageBar(nextLink);
  8084. checkAutoLoadNum();
  8085. }, true);
  8086. } else {
  8087. debug("Stop as no page when get by js");
  8088. isPause = true;
  8089. loadPageOver();
  8090. }
  8091. };
  8092. try {
  8093. ((typeof ruleParser.curSiteRule.pageElementByJs == 'function') ? ruleParser.curSiteRule.pageElementByJs : Function("over", "pageNum",'"use strict";' + ruleParser.curSiteRule.pageElementByJs))(over, curPage);
  8094. } catch(e) {
  8095. debug(e);
  8096. }
  8097. } else if ((forceState == 2 || ruleParser.curSiteRule.action == 2) && !isJs) {
  8098. forceIframe(nextLink, (iframe, refresh) => {
  8099. if (urlChanged || isPause) {
  8100. loadPageOver();
  8101. return;
  8102. }
  8103. if (!refresh) {
  8104. let pageBar = createPageBar(nextLink);
  8105. if (pageBar && iframe && iframe.parentNode) iframe.parentNode.insertBefore(pageBar, iframe);
  8106. }
  8107. loadPageOver();
  8108. checkAutoLoadNum();
  8109. });
  8110. } else if ((forceState == 3 || ruleParser.curSiteRule.action == 1) && !isJs) {
  8111. requestFromIframe(nextLink, (doc, eles) => {
  8112. if (urlChanged || isPause) {
  8113. loadPageOver();
  8114. return;
  8115. }
  8116. if (eles) {
  8117. ruleParser.insertPage(doc, eles, nextLink, () => {
  8118. createPageBar(nextLink);
  8119. checkAutoLoadNum();
  8120. }, true);
  8121. } else loadPageOver();
  8122. });
  8123. } else {
  8124. if (!isJs) {
  8125. requestDoc(nextLink, (eles) => {
  8126. if (urlChanged || isPause) {
  8127. loadPageOver();
  8128. return;
  8129. }
  8130. if (eles) {
  8131. createPageBar(nextLink);
  8132. checkAutoLoadNum();
  8133. } else loadPageOver();
  8134. });
  8135. } else {
  8136. emuPage((doc, eles) => {
  8137. if (urlChanged || isPause) {
  8138. loadPageOver();
  8139. return;
  8140. }
  8141. if (eles) {
  8142. ruleParser.insertPage(doc, eles, "", () => {
  8143. createPageBar(nextLink);
  8144. checkAutoLoadNum();
  8145. }, true);
  8146. } else loadPageOver();
  8147. });
  8148. }
  8149. }
  8150. }, sleep);
  8151. }
  8152. }
  8153.  
  8154. function init() {
  8155. if (document.readyState == 'loading' || document.readyState == 'uninitialized') {
  8156. let domReady = e => {
  8157. initRules(() => {
  8158. initPage();
  8159. });
  8160. document.removeEventListener("DOMContentLoaded", domReady, false);
  8161. }
  8162. document.addEventListener("DOMContentLoaded", domReady, false);
  8163. } else {
  8164. initRules(() => {
  8165. initPage();
  8166. });
  8167. }
  8168. }
  8169.  
  8170. function visibilitychangeHandler() {
  8171. document.removeEventListener('visibilitychange', visibilitychangeHandler);
  8172. init();
  8173. }
  8174.  
  8175. setTimeout(() => {
  8176. if (document.hidden) {
  8177. document.addEventListener('visibilitychange', visibilitychangeHandler);
  8178. } else {
  8179. init();
  8180. }
  8181. }, 300);
  8182. })();