东方永页机

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

当前为 2023-08-02 提交的版本,查看 最新版本

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

QingJ © 2025

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