東方永頁機

終極自動翻頁 - 加載並拼接下一分頁內容至當前頁尾,智能適配任意網頁

目前為 2023-04-28 提交的版本,檢視 最新版本

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

QingJ © 2025

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