东方永页机

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

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

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