东方永页机

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

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