东方永页机

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

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

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