东方永页机

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

目前为 2023-05-16 提交的版本。查看 最新版本

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