东方永页机

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

目前为 2023-07-13 提交的版本。查看 最新版本

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