东方永页机

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

当前为 2023-04-18 提交的版本,查看 最新版本

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址