东方永页机

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

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

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