东方永页机

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

当前为 2023-05-19 提交的版本,查看 最新版本

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