东方永页机

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

当前为 2023-05-19 提交的版本,查看 最新版本

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

QingJ © 2025

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