东方永页机

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

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

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

QingJ © 2025

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