东方永页机

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

当前为 2023-03-22 提交的版本,查看 最新版本

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