东方永页机

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

目前为 2023-04-09 提交的版本。查看 最新版本

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