东方永页机

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

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

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