东方永页机

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

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

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