东方永页机

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

目前为 2023-03-13 提交的版本,查看 最新版本

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