东方永页机

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

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

  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.21
  14. // @description Perpetual pages - Most powerful auto-pager script. Auto loading next paginated web pages and inserting into current page. Support thousands of web sites without any rule.
  15. // @description:zh-CN 终极自动翻页 - 加载并拼接下一分页内容至当前页尾,智能适配任意网页
  16. // @description:zh-TW 終極自動翻頁 - 加載並拼接下一分頁內容至當前頁尾,智能適配任意網頁
  17. // @description:ja Webページを自動で読み込み継ぎ足し表示を行うブラウザ拡張です、次のページ付けされた Web ページの自動読み込みと現在のページへの挿入 ルールなしで何千もの Web サイトをサポートします。
  18. // @description:ru Автоматическая подгрузка следующих страниц и вставка их содержимого в текущую страницу. Поддерживает тысячи сайтов даже с настройками по умолчанию.
  19. // @description:de Automatisches Laden der nächsten paginierten Webseiten und Einfügen in die aktuelle Seite. Unterstützen Sie Tausende von Websites ohne Regeln.
  20. // @description:es Carga automática de las siguientes páginas web paginadas e inserción en la página actual. Admite miles de sitios web sin ninguna regla.
  21. // @description:fr Chargement automatique des pages Web paginées suivantes et insertion dans la page en cours. Prend en charge des milliers de sites Web sans aucune règle.
  22. // @description:it Caricamento automatico delle pagine Web impaginate successive e inserimento nella pagina corrente. Supporta migliaia di siti web senza alcuna regola.
  23. // @description:ko 페이지가 매겨진 다음 웹 페이지를 자동으로 로드하고 현재 페이지에 삽입합니다. 규칙 없이 수천 개의 웹 사이트를 지원합니다.
  24. // @author hoothin
  25. // @license MPL License
  26. // @match *://*/*
  27. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAdVBMVEUAAAD3VU33VU32VEz8U073VU32VU33VU32VUz0Uk/3VE32VU32VUz2VU32VU32VU32VU33VU33U0z2VU34Wkv3VE32VUz/mpj/nJj2VUz2VU32VE33VEz2VU32VU32VUz3VE32VEz3VE3/mZf2Vkz2VU3/mpilFFolAAAAJXRSTlMA3Lp/GvTBT5YQLuawZ/DOyZwlPQeKc21N04+FX1bqpm9DNoB4T68ePwAAAitJREFUWMPt1tuasiAUBuCFCG5Rs3QybTPV1/1f4v/3PDkyIojn8x5qBrI+ltAfh32/yysmBKvyXb+njb6bDL9kzTd5SzjDAsYT8nFoGSxYe6BVqoNDp2jFDit25BRgVUAODB4YWcETWVTwVNGiGN5iWtBgg4YMCpsoI38dNunmmWyxUTvbPwwbsYR0fIzZLQ0pTG8eieRmBLMmpdH9uimQEf6TNRnXXKLZHixpJtywLzOgMHtFCqdM64DahHRnOE1dsrekm9wr2WtLcAlpdHwcp1pAJySXYnERclzp4+v19jXdmcTvQUJtz+ZaI4i05/V/UGYrCxbaAsOYoNfIKEQxpqQuzCgJJJ/3f42O8ywEZuMVWi/8hODxGj3GW2b0udkbGULLDOjimAG0S3fLGlBnXQM9irG1CiQdVQi0dqQsOSDlyEEz7Vy9OxxfR71VCXsSB23jMrKJYZXSjw57sqgLn5Z0wolsOCz0RyJkyeYjgz7pwwVq20eboZwtVUl2EnN5gJ50dQZFdryATvABRTr/tJXkUMdaAK5pwtCapwtFLskguwuyMh/Sd9WChQ4sIvIUYSk3PYqQvCQlOC04IfN7PkdjOyRKWhdKXMmiAFt9i3sJ5jxoRuR0vqAghxxwHuqfQE5OHGDKOrwEnqs1DgAZ2e4Eev1d45TN7JfhrQLKgfwMFYAsvp33dXII073aVQLI2gN5S58lfmGnKKFtah7nkgnBZB7zlP7Y/QNiTM6sYNzawwAAAABJRU5ErkJggg==
  28. // @grant GM_xmlhttpRequest
  29. // @grant GM_registerMenuCommand
  30. // @grant GM_notification
  31. // @grant GM_getValue
  32. // @grant GM_setValue
  33. // @grant GM_addStyle
  34. // @grant GM_openInTab
  35. // @grant GM_deleteValue
  36. // @grant GM_info
  37. // @grant GM_setClipboard
  38. // @grant GM.xmlHttpRequest
  39. // @grant GM.registerMenuCommand
  40. // @grant GM.notification
  41. // @grant GM.getValue
  42. // @grant GM.setValue
  43. // @grant GM.addStyle
  44. // @grant GM.openInTab
  45. // @grant GM.deleteValue
  46. // @grant GM.info
  47. // @grant GM.setClipboard
  48. // @supportURL https://github.com/hoothin/UserScripts/issues
  49. // @connect wedata.net
  50. // @connect githubusercontent.com
  51. // @connect ghproxy.com
  52. // @connect hoothin.github.io
  53. // @run-at document-idle
  54. // @connect *
  55. // ==/UserScript==
  56.  
  57. (function() {
  58. 'use strict';
  59.  
  60. if (window.name === 'pagetual-iframe' || (window.frameElement && window.frameElement.name === 'pagetual-iframe')) {
  61. var domloaded = function (){
  62. window.scroll(window.scrollX, 999999);
  63. window.parent.postMessage('pagetual-iframe:DOMLoaded', '*');
  64. };
  65. if (window.opera) {
  66. document.addEventListener('DOMContentLoaded', domloaded, false);
  67. } else {
  68. domloaded();
  69. }
  70. if (getComputedStyle(document.documentElement).display == 'none') document.documentElement.style.display = 'block';
  71. if (document.body && getComputedStyle(document.body).display == 'none') document.body.style.display = 'block';
  72. return;
  73. }
  74.  
  75. if (window.top != window.self) {
  76. try {
  77. if (window.self.innerWidth < 300 || window.self.innerHeight < 300) {
  78. return;
  79. }
  80. } catch(e) {
  81. return;
  82. }
  83. }
  84.  
  85. const noRuleTest = false;
  86. const lang = navigator.appName == "Netscape" ? navigator.language : navigator.userLanguage;
  87. let config = {};
  88. switch (lang) {
  89. case "zh-CN":
  90. case "zh-SG":
  91. config = {
  92. enableDebug: "调试模式,输出信息至控制台",
  93. disable: "暂时禁用",
  94. disableSite: "站点禁用开关",
  95. disableSiteTips: "已在此站禁用",
  96. enableSiteTips: "已在此站启用",
  97. enable: "启用自动翻页",
  98. toTop: "回到顶部",
  99. toBottom: "前往页尾",
  100. current: "当前页",
  101. forceIframe: "强制拼接",
  102. cancelForceIframe: "取消强制拼接",
  103. configure: "打开配置页面",
  104. firstUpdate: "点击此处初始化规则",
  105. update: "更新在线规则",
  106. click2update: "点击立即更新规则",
  107. loadNow: "立即翻页",
  108. loadConfirm: "要翻几页?(0为不间断)",
  109. noNext: "没有找到下一页,请新建规则",
  110. passSec: "更新于 #t# 秒前",
  111. passMin: "更新于 #t# 分钟前",
  112. passHour: "更新于 #t# 小时前",
  113. passDay: "更新于 #t# 天前",
  114. cantDel: "无法删除内置规则",
  115. confirmDel: "是否确认要删除此规则?",
  116. updateSucc: "更新成功",
  117. beginUpdate: "正在更新,请耐心等待,不要关闭页面",
  118. customUrls: "导入 Pagetual 或 AutoPagerize 规则 url,一行一条",
  119. customRules: "输入【东方永页机】格式的自定义规则 <a href='#t#'>贡献规则</a>",
  120. save: "保存设置",
  121. loadingText: "少女祈祷中...",
  122. opacity: "不透明值",
  123. opacityPlaceholder: "0: 隐藏分隔条",
  124. hideBar: "隐藏分页隔条",
  125. hideBarButNoStop: "隐藏但不停止",
  126. dbClick2Stop: "空白处双击暂停翻页",
  127. sortTitle: "排序在下次更新规则后生效",
  128. autoRun: "自动启用,否则为白名单模式",
  129. autoLoadNum: "自动加载指定页数",
  130. turnRate: "距离页尾【X】倍页面高度时就开始翻页",
  131. inputPageNum: "输入页码跳转",
  132. enableHistory: "翻页后写入历史记录",
  133. enableHistoryAfterInsert: "拼接后立即写入历史记录,否则浏览完毕后再行写入",
  134. contentVisibility: "自动切换 contentVisibility,提升渲染性能",
  135. initRun: "打开页面后立即尝试翻页,否则滚动至页尾再翻页",
  136. preload: "翻页前预读下一页,加速浏览",
  137. click2ImportRule: "点击下方添加特殊规则库,并静待更新成功:",
  138. forceAllBody: "是否拼接整个页面?",
  139. openInNewTab: "使拼接页面的内容在新页面打开",
  140. importSucc: "导入成功",
  141. import: "导入",
  142. editCurrent: "编辑此站规则",
  143. editBlacklist: "编辑黑名单网址,一行一条,支持? *通配符与正则",
  144. upBtnImg: "回到页首图标",
  145. downBtnImg: "前往页尾图标",
  146. sideControllerIcon: "侧边栏图标",
  147. loadingTextTitle: "加载中文字",
  148. dbClick2StopCtrl: "Ctrl 键",
  149. dbClick2StopAlt: "Alt 键",
  150. dbClick2StopShift: "Shift 键",
  151. dbClick2StopMeta: "Meta 键",
  152. dbClick2StopKey: "快捷键",
  153. pageElementCss: "页面主体框架的样式",
  154. customCss: "自定义 css",
  155. firstAlert: "你还未导入规则库,请选择合适的规则库导入哦",
  156. picker: "东方永页机主体元素抓取器",
  157. closePicker: "关闭东方永页机抓取器",
  158. pickerPlaceholder: "元素选择器,没想法建议留空",
  159. pickerCheck: "检查你编辑的选择器并复制",
  160. switchSelector: "点击切换元素",
  161. gotoEdit: "使用当前的选择器前往编辑规则",
  162. manualMode: "禁用拼接,手动用右方向键翻页,可使用左方向键返回",
  163. clickMode: "禁用拼接,滚动至页尾时自动点击下一页",
  164. pageBarMenu: "点击分隔条中间弹出菜单",
  165. nextSwitch: "切换其他页码",
  166. arrowToScroll: "左方向键滚动至上一页,右方向键滚动至下一页",
  167. sideController: "在侧边显示翻页控制栏",
  168. hideLoadingIcon: "隐藏加载动画",
  169. hideBarArrow: "隐藏分隔条定位箭头",
  170. duplicate: "检测到永页机重复安装,请删除其他脚本管理器中的永页机!",
  171. forceStateIframe: "以 iframe 嵌入整页",
  172. forceStateDynamic: "通过 iframe 加载动态内容后取出",
  173. forceStateDisable: "在此站禁用",
  174. 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), nextLeftPos = 0;
  1494. if (needCheckNext && this.initNext.getBoundingClientRect) {
  1495. nextLeftPos = this.initNext.getBoundingClientRect().left;
  1496. }
  1497. function checkElement(ele) {
  1498. if (/^(PRE|CODE)$/i.test(ele.nodeName)) {
  1499. self.curSiteRule.pageElement = geneSelector(ele.parentNode);
  1500. debug(self.curSiteRule.pageElement, 'Page element');
  1501. return [ele.parentNode];
  1502. }
  1503. if (ele.children && ele.children.length == 1) {
  1504. let hasText = false;
  1505. for (let i in ele.childNodes) {
  1506. let child = ele.childNodes[i];
  1507. if (child.nodeType == 3 && child.nodeValue.trim() !== '') {
  1508. hasText = true;
  1509. break;
  1510. }
  1511. }
  1512. if (!hasText) {
  1513. ele = ele.children[0];
  1514. curHeight = self.getValidHeight(ele);
  1515. curWidth = parseInt(ele.offsetWidth || ele.scrollWidth);
  1516. }
  1517. }
  1518. if (/^PICTURE$/i.test(ele.nodeName)) {
  1519. self.curSiteRule.pageElement = geneSelector(ele.parentNode) + ">" + ele.nodeName.toLowerCase();
  1520. debug(self.curSiteRule.pageElement, 'Page element');
  1521. return [ele];
  1522. }
  1523. if (curHeight / bodyHeight <= 0.25) {
  1524. let article = doc.querySelectorAll(mainSel);
  1525. if (article && article.length == 1) {
  1526. article = article[0];
  1527. self.curSiteRule.pageElement = article.nodeName.toLowerCase() + (article.id ? "#" + article.id : "") + (article.className ? "." + article.className.replace(/ /g, ".") : "") + ">*";
  1528. debug(self.curSiteRule.pageElement, 'Page element');
  1529. return article.children;
  1530. }
  1531. self.curSiteRule.pageElement = allOfBody;
  1532. debug(self.curSiteRule.pageElement, 'Page element');
  1533. return [body];
  1534. }
  1535. if (/^FORM$/i.test(ele.nodeName) && ele.parentNode != getBody(document)) {
  1536. self.curSiteRule.pageElement = geneSelector(ele) + ">*";
  1537. debug(self.curSiteRule.pageElement, 'Page element');
  1538. return ele.children;
  1539. }
  1540. if (ele.children.length == 0 && !self.curSiteRule.pageElement) {
  1541. if (/^P$/i.test(ele.parentNode.nodeName)) ele = ele.parentNode;
  1542. self.curSiteRule.pageElement = geneSelector(ele.parentNode) + ">" + ele.nodeName.toLowerCase();
  1543. debug(self.curSiteRule.pageElement, 'Page element');
  1544. return getAllElements(self.curSiteRule.pageElement, doc);
  1545. }
  1546. let i, minHeight = curHeight * 0.52, curMaxEle = null, curMaxArea = 0, minWidth = curWidth * 0.38;
  1547. let isHori, preOffsetTop = -1;
  1548. let articleNum = 0;
  1549. for (i = 0; i < ele.children.length; i++) {
  1550. let curNode = ele.children[i];
  1551. if (/^(CANVAS|NAV)$/i.test(curNode.nodeName)) continue;
  1552. if (!curNode.offsetParent) continue;
  1553. if (!/^IMG$/i.test(curNode.nodeName) && curNode.querySelector('img') == null && /^\s*$/.test(curNode.innerText)) continue;
  1554. if (needCheckNext && !curNode.contains(self.initNext) && getElementTop(curNode) > windowHeight) {
  1555. continue;
  1556. }
  1557. if (/^ARTICLE$/i.test(curNode.nodeName)) articleNum++;
  1558. let h = self.getValidHeight(curNode);
  1559. let w = curNode.scrollWidth;
  1560. if (isNaN(h) || isNaN(w)) continue;
  1561. isHori = preOffsetTop == curNode.offsetTop ? true : (preOffsetTop == -1 && curNode.nextElementSibling && curNode.nextElementSibling.offsetTop == curNode.offsetTop);
  1562. if (isHori && h <= 50) continue;
  1563. if (isHori && nextLeftPos && curMaxEle && curWidth > 500 && curHeight > 500) {
  1564. let curRect = curNode.getBoundingClientRect();
  1565. if (curRect.left <= nextLeftPos && curRect.right > nextLeftPos) {
  1566. continue;
  1567. }
  1568. }
  1569. let a = h * w, moreChild = curNode.children[0];
  1570. while (moreChild) {
  1571. let ch = self.getValidHeight(moreChild);
  1572. let cw = moreChild.scrollWidth;
  1573. if (h < ch) {
  1574. h = ch;
  1575. }
  1576. if (moreChild.innerText != "" && ch && cw) {
  1577. a += ch * cw;
  1578. }
  1579. moreChild = moreChild.nextElementSibling;
  1580. }
  1581. let isMax = false;
  1582. if (isHori) {
  1583. if (curMaxEle) {
  1584. if (curWidth < w) {
  1585. isMax = true;
  1586. } else if (curWidth < w + 300 && curMaxArea < a) {
  1587. isMax = true;
  1588. }
  1589. }
  1590. } else {
  1591. if (curMaxEle && curMaxEle.offsetParent == curNode.offsetParent && curMaxEle.offsetTop == curNode.offsetTop) {
  1592. if (curMaxArea * 2 > a) continue;
  1593. }
  1594. isMax = curMaxArea < a;
  1595. }
  1596. if (curMaxEle == null || isMax) {
  1597. if (isHori) {
  1598. if (curMaxEle && w < minWidth) {
  1599. continue;
  1600. }
  1601. }
  1602. if (h < minHeight) {
  1603. if (!needCheckNext || h < windowHeight || !ele.contains(self.initNext)) {
  1604. continue;
  1605. }
  1606. }
  1607. curHeight = h;
  1608. curMaxArea = a;
  1609. curWidth = w;
  1610. curMaxEle = curNode;
  1611. preOffsetTop = curNode.offsetTop;
  1612. }
  1613. }
  1614. if (curMaxEle) {
  1615. let sameClassNum = 0;
  1616. if (curMaxEle.className) {
  1617. for(i = 0; i < ele.children.length; i++) {
  1618. let curNode = ele.children[i];
  1619. if (curMaxEle != curNode && curNode.style.display !== 'none' && curMaxEle.className == curNode.className && curMaxEle.nodeName == curNode.nodeName){
  1620. sameClassNum++;
  1621. }
  1622. }
  1623. }
  1624. if (sameClassNum < 5) {
  1625. return checkElement(curMaxEle);
  1626. }
  1627. }
  1628. if (ele.parentNode.children.length == 1 && curWin.getComputedStyle(ele.parentNode).float == 'none') ele = ele.parentNode;
  1629. else if (/^(P|BR|TD)$/i.test(ele.nodeName)) ele = ele.parentNode;
  1630. else if (/^TBODY$/i.test(ele.nodeName)) {
  1631. self.curSiteRule.pageElement = geneSelector(ele) + ">*";
  1632. if (ele.children.length > 0 && ele.children[0].querySelector("th")) {
  1633. self.curSiteRule.pageElement += ":not(:first-child)";
  1634. }
  1635. debug(self.curSiteRule.pageElement, 'Page element');
  1636. return ele.children;
  1637. }
  1638. let imgs = ele.querySelectorAll('img');
  1639. if (imgs.length == 1) {
  1640. let img = imgs[0];
  1641. if (img.offsetWidth > ele.offsetWidth / 3 * 2 && img.offsetHeight > ele.offsetHeight / 2) {
  1642. ele = img;
  1643. }
  1644. }
  1645. self.curSiteRule.pageElement = geneSelector(ele);
  1646. let pf = false;
  1647. if (ele.parentNode) {
  1648. let paStyle = curWin.getComputedStyle(ele.parentNode);
  1649. let paDisplay = paStyle.display;
  1650. let paOverflow = paStyle.overflow;
  1651. pf = paDisplay.indexOf('flex') !== -1 || paDisplay.indexOf('grid') !== -1 || paOverflow == "hidden";
  1652. }
  1653. if (ele.children.length > 1) {
  1654. if (articleNum > 1) {
  1655. self.curSiteRule.pageElement += ">article";
  1656. ele = ele.children;
  1657. } else {
  1658. let hasText = false;
  1659. for (let i in ele.childNodes) {
  1660. let child = ele.childNodes[i];
  1661. if (child.nodeType == 3 && child.nodeValue.trim() !== '') {
  1662. hasText = true;
  1663. ele = [ele];
  1664. break;
  1665. }
  1666. }
  1667. if (!hasText) {
  1668. let gridArea = curWin.getComputedStyle(ele).gridArea;
  1669. if (gridArea && gridArea != "auto / auto / auto / auto") {
  1670. self.curSiteRule.pageElement += ">*";
  1671. ele = ele.children;
  1672. } else {
  1673. let middleChild = ele.children[parseInt(ele.children.length / 2)];
  1674. if (curWin.getComputedStyle(ele).display === 'flex' || (rulesData.opacity != 0 && !pf)) {
  1675. ele = [ele];
  1676. } else if ((middleChild.style && middleChild.style.position === "absolute" && middleChild.style.left && middleChild.style.top) || /^UL$/i.test(ele.nodeName) || curHeight == 0) {
  1677. ele = [ele];
  1678. } else {
  1679. self.curSiteRule.pageElement += ">*";
  1680. ele = ele.children;
  1681. }
  1682. }
  1683. }
  1684. }
  1685. } else if (pf) {
  1686. self.curSiteRule.pageElement += ">*";
  1687. ele = ele.children;
  1688. } else {
  1689. ele = [ele];
  1690. }
  1691. debug(self.curSiteRule.pageElement, 'Page element');
  1692. return ele;
  1693. }
  1694. pageElement = checkElement(body);
  1695. if (pageElement && pageElement.length > 0 && self.initNext) {
  1696. let lastBottom = getElementBottom(pageElement[pageElement.length - 1]);
  1697. if (lastBottom && getElementTop(self.initNext) - lastBottom > 1000) {
  1698. debug("Stop as too long between next & page element");
  1699. isPause = true;
  1700. pageElement = [];
  1701. } else {
  1702. if (pageElement.length == 1 && /^IMG$/i.test(pageElement[0].nodeName)) {
  1703. self.curSiteRule.pageBar = 0;
  1704. }
  1705. }
  1706. }
  1707. //if(pageElement)this.saveCurSiteRule();
  1708. }
  1709.  
  1710. if (doc !== document) {
  1711. this.setPageElementCss(pageElement);
  1712. this.lazyImgAction(pageElement);
  1713. } else if (!this.docPageElement) {
  1714. this.setPageElementCss(pageElement, true);
  1715. this.docPageElement = pageElement;
  1716. if (this.nextLinkHref) {
  1717. this.openInNewTab(pageElement);
  1718. }
  1719. }
  1720. if (this.curSiteRule.singleUrl && pageElement && pageElement.length > 0) {
  1721. let targetEle = pageElement.length > 1 ? pageElement[0].parentNode : pageElement[0];
  1722. let video = targetEle.querySelector("video") || targetEle.querySelector("iframe[id*=play],[id*=play]>iframe,iframe[src*=player],iframe[src*=m3u8]");
  1723. if (video && doc == document) {
  1724. if (video && video.offsetParent && video.name != 'pagetual-iframe') {
  1725. let scrollWidth = video.scrollWidth || video.offsetWidth;
  1726. let scrollHeight = video.scrollHeight || video.offsetHeight;
  1727. if (scrollWidth > 420 && scrollHeight > 420) {
  1728. debug("Disable when large media found");
  1729. } else if (scrollWidth > 100 && scrollHeight > 100) {
  1730. let winWidth = window.innerWidth || document.documentElement.clientWidth;
  1731. let winHeight = window.innerHeight || document.documentElement.clientHeight;
  1732. if (scrollWidth > winWidth>>1 || scrollHeight > winHeight>>1) {
  1733. debug("Disable when large media found under mobile");
  1734. } else {
  1735. video = null;
  1736. }
  1737. } else {
  1738. video = null;
  1739. }
  1740. } else {
  1741. video = null;
  1742. }
  1743. }
  1744. if (video) {
  1745. isPause = true;
  1746. this.clearAddedElements();
  1747. return null;
  1748. }
  1749. }
  1750. return pageElement;
  1751. }
  1752.  
  1753. changeVisibility() {
  1754. let contentVisibility = this.curSiteRule.contentVisibility || rulesData.contentVisibility;
  1755. if (!contentVisibility) return;
  1756. if (!this.changingVisibility) {
  1757. clearTimeout(this.changeVisibilityTimer);
  1758. this.changeVisibilityTimer = setTimeout(() => {
  1759. this.changingVisibility = true;
  1760. this.changeVisibility();
  1761. }, 300);
  1762. return;
  1763. }
  1764. this.changingVisibility = false;
  1765. if (!this.visibilityItems || !this.visibilityItems.length || this.visibleIndex < 0) return;
  1766. let tempIndex = this.visibleIndex, findVisible = false, lastVisible = 0;
  1767. let viewPortHeight = window.innerHeight || document.documentElement.clientHeight || getBody(document).clientHeight;
  1768. let checkItem = this.visibilityItems[tempIndex];
  1769. while(checkItem) {
  1770. if (checkItem.offsetParent) {
  1771. if (!checkItem.style.containIntrinsicSize) return;
  1772. let clientRect = checkItem.getBoundingClientRect();
  1773. let top = clientRect && clientRect.top;
  1774. let bottom = clientRect && clientRect.bottom;
  1775. if (bottom > 0 && top < viewPortHeight) {
  1776. if (!findVisible) {
  1777. findVisible = true;
  1778. lastVisible = tempIndex;
  1779. }
  1780. checkItem.style.contentVisibility = "visible";
  1781. } else {
  1782. if (top < viewPortHeight && checkItem.style.contentVisibility == "auto") {
  1783. break;
  1784. } else checkItem.style.contentVisibility = "auto";
  1785. }
  1786. }
  1787. if (tempIndex == 0) break;
  1788. tempIndex--;
  1789. checkItem = this.visibilityItems[tempIndex];
  1790. }
  1791. tempIndex = this.visibleIndex + 1;
  1792. if (findVisible) {
  1793. this.visibleIndex = lastVisible;
  1794. }
  1795. checkItem = this.visibilityItems[tempIndex];
  1796. while(checkItem) {
  1797. if (checkItem.offsetParent) {
  1798. if (!checkItem.style.containIntrinsicSize) return;
  1799. let clientRect = checkItem.getBoundingClientRect();
  1800. let top = clientRect && clientRect.top;
  1801. let bottom = clientRect && clientRect.bottom;
  1802. if (bottom > 0 && top < viewPortHeight) {
  1803. findVisible = true;
  1804. lastVisible = tempIndex;
  1805. checkItem.style.contentVisibility = "visible";
  1806. } else {
  1807. if (findVisible && checkItem.style.contentVisibility == "auto") {
  1808. break;
  1809. } else checkItem.style.contentVisibility = "auto";
  1810. }
  1811. }
  1812. if (tempIndex == this.visibilityItems.length - 1) break;
  1813. tempIndex++;
  1814. checkItem = this.visibilityItems[tempIndex];
  1815. }
  1816. if (findVisible) {
  1817. this.visibleIndex = lastVisible;
  1818. }
  1819. }
  1820.  
  1821. setPageElementCss(pageElement, init) {
  1822. let self = this;
  1823. if (pageElement && pageElement.length > 0) {
  1824. let pageElementCss = this.curSiteRule.pageElementCss || rulesData.pageElementCss;
  1825. if (!pageElementCss && init && !this.nextLinkHref) return;
  1826. let contentVisibility = this.curSiteRule.contentVisibility || rulesData.contentVisibility;
  1827. if (!contentVisibility && !pageElementCss) return;
  1828. [].forEach.call(pageElement, (ele, i) => {
  1829. if (!/LINK|META|STYLE|SCRIPT/i.test(ele.nodeName)) {
  1830. if (pageElementCss) {
  1831. if (pageElementCss !== '0' && !ele.dataset.pagetualPageElement) {
  1832. ele.style.cssText = (ele.style.cssText || '') + pageElementCss;
  1833. ele.dataset.pagetualPageElement = 1;
  1834. }
  1835. }
  1836. if (contentVisibility) {
  1837. ele.style.containIntrinsicSize = `auto ${ele.offsetHeight || self.preVisibleHeight || 100}px`;
  1838. if (ele.style.containIntrinsicSize) {
  1839. if (ele.offsetHeight) self.preVisibleHeight = ele.offsetHeight;
  1840. if (init) {
  1841. ele.style.contentVisibility = "visible";
  1842. self.visibilityItems.push(ele);
  1843. self.visibleIndex++;
  1844. } else {
  1845. ele.style.contentVisibility = emuIframe ? "visible" : "auto";
  1846. }
  1847. }
  1848. }
  1849. }
  1850. });
  1851. }
  1852. }
  1853.  
  1854. clearAddedElements() {
  1855. if (this.addedElePool && this.addedElePool.length) {
  1856. this.addedElePool.forEach(ele => {
  1857. if (ele.parentNode) ele.parentNode.removeChild(ele);
  1858. });
  1859. }
  1860. this.addedElePool = [];
  1861. sideController.remove();
  1862. }
  1863.  
  1864. async getPage(doc) {
  1865. if (document.documentElement.className.indexOf('discourse') != -1) return {};
  1866. let body = getBody(doc);
  1867. let canSave = false;//發現頁碼選擇器在其他頁對不上,還是別保存了
  1868. let url = this.curUrl.slice(0, 250).replace("index.php?", "?");
  1869. let _url = url.replace(/\.s?html?$/i, "").toLowerCase();
  1870. let pageNum = 1, preStr = "", afterStr = "";
  1871. let pageTwoReg = /^[\/\?&]?[_-]?(p|page)?=?\/?2(\/|\?|&|$)/i;
  1872. let pageMatch1 = url.match(/(.*[\?&]p(?:age)?=)(\d+)($|[#&].*)/i);
  1873. let doubtTextReg = /^\s*(»|>>)\s*$/;
  1874. if (pageMatch1) {
  1875. preStr = pageMatch1[1];
  1876. pageNum = parseInt(pageMatch1[2]);
  1877. afterStr = pageMatch1[3];
  1878. } else {
  1879. let pageMatch2 = url.match(/(.*[a-z\/\-_](?:p|page)?\/?)(\d+)(\.s?html?$|\/?$)/i);
  1880. if (pageMatch2) {
  1881. preStr = pageMatch2[1];
  1882. pageNum = parseInt(pageMatch2[2]);
  1883. afterStr = pageMatch2[3];
  1884. if (/^\/?$/.test(afterStr) && !/(p(age)?|_|\-|\/)$/.test(preStr)) {
  1885. preStr = "";
  1886. afterStr = "";
  1887. }
  1888. }
  1889. }
  1890. if (pageNum > 999) {
  1891. pageNum = 1;
  1892. preStr = "";
  1893. afterStr = "";
  1894. }
  1895. let curPage = doc, i, cur, jsNext;
  1896. let next1, next2, next3, next4, nextJs1, nextJs2, nextJs3;
  1897. let next = body.querySelector(".page-next>a") ||
  1898. body.querySelector("a.next_page") ||
  1899. body.querySelector("#next_page") ||
  1900. body.querySelector(".nextPage") ||
  1901. body.querySelector(".pagination-next>a") ||
  1902. body.querySelector("a[data-pagination=next]") ||
  1903. body.querySelector("ul.pagination>li.active+li>a") ||
  1904. body.querySelector("[class^=pag] .current+a") ||
  1905. body.querySelector(".pageButtonsCurrent+a") ||
  1906. body.querySelector("a[class*=nextpage]") ||
  1907. body.querySelector("li.page-current+li>a") ||
  1908. body.querySelector(".pager-section a[rel=next]") ||
  1909. body.querySelector(".pagination a[rel=next]") ||
  1910. body.querySelector(".pagination-nav__item--next>a");
  1911. if (!next) {
  1912. await sleep(1);
  1913. next = body.querySelector("a.pageright") ||
  1914. body.querySelector(".page-numbers.current+a") ||
  1915. body.querySelector("input[value='next']") ||
  1916. body.querySelector("input[value='Next page']") ||
  1917. body.querySelector("input[value='下一页']") ||
  1918. body.querySelector("input[value='下一頁']") ||
  1919. body.querySelector("a#pb_next") ||
  1920. body.querySelector("a#rightFix") ||
  1921. body.querySelector("a#btnPreGn") ||
  1922. body.querySelector("a.page-next") ||
  1923. body.querySelector("a.pages-next") ||
  1924. body.querySelector("a.page.right");
  1925. }
  1926. if (!next) {
  1927. await sleep(1);
  1928. next = body.querySelector("a#next") ||
  1929. body.querySelector(".next>a") ||
  1930. body.querySelector(".next>button") ||
  1931. body.querySelector("a[alt=next]") ||
  1932. body.querySelector(".pg_area>em+a") ||
  1933. body.querySelector("button.next:not([disabled])") ||
  1934. body.querySelector(".btn_next:not([disabled])") ||
  1935. body.querySelector(".btn-next:not([disabled])") ||
  1936. body.querySelector("[title=next]") ||
  1937. body.querySelector("a#linkNext") ||
  1938. body.querySelector("a[class*=page__next]");
  1939. }
  1940. if (!next) {
  1941. await sleep(1);
  1942. let nexts = body.querySelectorAll("a.next");
  1943. for (i = 0; i < nexts.length; i++) {
  1944. if (nexts[i].style.display !== "none" &&
  1945. nexts[i].parentNode.style.display !== "none" &&
  1946. !/^\s*([上前首尾]|previous)/i.test(nexts[i].innerText.trim())) {
  1947. next = nexts[i];
  1948. break;
  1949. }
  1950. }
  1951. }
  1952. if (next && (!next.href || /^(javascript|#)/.test(next.href.replace(location.href, "")))) {
  1953. jsNext = next;
  1954. next = null;
  1955. }
  1956. if (!next) {
  1957. next = body.querySelectorAll("[aria-label='Next page']");
  1958. if (next && next.length == 1) {
  1959. next = next[0];
  1960. if (!next.href || /^(javascript|#)/.test(next.href.replace(location.href, ""))) {
  1961. if (!jsNext) jsNext = next;
  1962. next = null;
  1963. }
  1964. } else {
  1965. next = null;
  1966. }
  1967. }
  1968. if (jsNext) {
  1969. if (jsNext.className) {
  1970. if (/slick|slide|gallery/i.test(jsNext.className)) jsNext = null;
  1971. else if (jsNext.classList && jsNext.classList.contains('disabled')) jsNext = null;
  1972. }
  1973. if (jsNext) {
  1974. let ariaLabel = jsNext.getAttribute("aria-label");
  1975. if (ariaLabel && /slick|slide|gallery/i.test(ariaLabel)) jsNext = null;
  1976. }
  1977. }
  1978. if (next && nextTextReg2.test(next.innerText.trim())) {
  1979. next2 = next;
  1980. next = null;
  1981. }
  1982. if (!next) {
  1983. next = body.querySelector("a.curr+a") ||
  1984. body.querySelector("div.wp-pagenavi>span.current+a,div.page-nav>span.current+a,div.article-paging>span+a") ||
  1985. body.querySelector(".number>ul>li.active+li>a");;
  1986. }
  1987. if (!next) {
  1988. let pageDiv = body.querySelector("div.pages>ul");
  1989. if (pageDiv) {
  1990. cur = pageDiv.querySelector("li>b");
  1991. if (cur) next = cur.parentNode.nextElementSibling;
  1992. if (next) next = next.querySelector("a");
  1993. }
  1994. }
  1995. if (!next) {
  1996. next = body.querySelector(".pages>a[href='javascript:;']+a");
  1997. if (next && (next.href == "javascript:;" || next.getAttribute("href") == "#")) next = null;
  1998. }
  1999. if (!next) {
  2000. await sleep(1);
  2001. let pageDiv = body.querySelector(".pagination");
  2002. if (pageDiv) {
  2003. cur = pageDiv.querySelector("[class*=current]");
  2004. if (cur) next = cur.parentNode.nextElementSibling;
  2005. if (next) next = next.querySelector("a");
  2006. }
  2007. }
  2008. if (!next) {
  2009. let aTags = body.querySelectorAll("a,button,[type='button']");
  2010. for (i = aTags.length - 1; i >= 0; i--) {
  2011. if (next1) break;
  2012. if (i % 300 == 0) {
  2013. await sleep(1);
  2014. }
  2015. let aTag = aTags[i];
  2016. if (aTag.style.display == "none") continue;
  2017. let innerText = (aTag.innerText || aTag.value || aTag.title || '');
  2018. if (innerText) {
  2019. if (innerText == "§") continue;
  2020. innerText = innerText.trim();
  2021. if (innerText.length > 80) continue;
  2022. }
  2023. let availableHref = aTag.href && aTag.href.length < 250 && /^http/.test(aTag.href);
  2024. if (availableHref && /next$/i.test(aTag.href)) continue;
  2025. if (aTag.className) {
  2026. if (/slick|slide|gallery/i.test(aTag.className)) continue;
  2027. if (aTag.classList && aTag.classList.contains('disabled')) continue;
  2028. }
  2029. let ariaLabel = aTag.getAttribute("aria-label");
  2030. if (ariaLabel && /slick|slide|gallery/i.test(ariaLabel)) continue;
  2031. if (aTag.parentNode) {
  2032. if (aTag.parentNode.className && /slick|slide|gallery/i.test(aTag.parentNode.className)) continue;
  2033. if (aTag.parentNode.classList && aTag.parentNode.classList.contains('disabled')) continue;
  2034. if (aTag.parentNode.classList && aTag.parentNode.classList.contains('active')) continue;
  2035. if (/^BLOCKQUOTE$/i.test(aTag.parentNode.nodeName)) continue;
  2036. }
  2037. if (aTag.previousElementSibling && /\b(play|volume)\b/.test(aTag.previousElementSibling.className)) continue;
  2038. if (aTag.nextElementSibling && /\b(play|volume)\b/.test(aTag.nextElementSibling.className)) continue;
  2039. let isJs = !aTag.href || !aTag.href.replace || /^(javascript|#)/.test(aTag.href.replace(location.href, ""));
  2040. if (innerText) {
  2041. innerText = innerText.split(/\n/)[0].replace(/ /g, '');
  2042. if (isJs && /^(»|>>|>|›|→|❯)$/.test(innerText)) continue;
  2043. if (innerText && innerText.length <= 25) {
  2044. if (!next1) {
  2045. if (nextTextReg1.test(innerText)) {
  2046. if (isJs) {
  2047. if (!nextJs1) nextJs1 = aTag;
  2048. } else {
  2049. next1 = aTag;
  2050. }
  2051. }
  2052. }
  2053. if (!next4) {
  2054. if (!next2) {
  2055. if (nextTextReg2.test(innerText) || /nextpage|pager\-older/i.test(aTag.className) || /^(»|>>)$/.test(innerText)) {
  2056. if (isJs) {
  2057. if (!nextJs2) nextJs2 = aTag;
  2058. } else {
  2059. next2 = aTag;
  2060. }
  2061. }
  2062. }
  2063. if (!next3) {
  2064. if (/^(next\s*(»|>>|>|›|→|❯)?|&gt;|▶|>|›|→|❯)$/i.test(innerText)) {
  2065. if (isJs) {
  2066. if (!nextJs3) nextJs3 = aTag;
  2067. } else {
  2068. next3 = aTag;
  2069. }
  2070. }
  2071. }
  2072. }
  2073. }
  2074. }
  2075. if (isJs) continue;
  2076. if (!next4) {
  2077. let prevEle = aTag.previousElementSibling;
  2078. if (prevEle && (/^(B|SPAN|STRONG)$/i.test(prevEle.nodeName))) {
  2079. if (/^\d+$/.test(aTag.innerText.trim()) && /^\d+$/.test(prevEle.innerText.trim()) && parseInt(aTag.innerText) == parseInt(prevEle.innerText) + 1) {
  2080. next4 = aTag;
  2081. }
  2082. }
  2083. }
  2084. if (!next4 && availableHref) {
  2085. if (aTag.href.indexOf(location.hostname) === -1) continue;
  2086. let _aHref = aTag.href.replace("?&", "?").replace("index.php?", "?").toLowerCase();
  2087. if (preStr || afterStr) {
  2088. let _aHrefTrim = _aHref;
  2089. if (preStr) _aHrefTrim = _aHrefTrim.replace(preStr, "");
  2090. if (afterStr) _aHrefTrim = _aHrefTrim.replace(afterStr, "");
  2091. if (_aHrefTrim == pageNum + 1) {
  2092. next4 = aTag;
  2093. }
  2094. } else if (this.curUrl != aTag.href) {
  2095. _aHref = _aHref.replace(/\.s?html?$/i, "");
  2096. if (_aHref.indexOf(_url) != -1) {
  2097. let pageTwoMatch = _aHref.replace(_url, "").match(pageTwoReg);
  2098. if (pageTwoMatch) {
  2099. afterStr = pageTwoMatch[2];
  2100. next4 = aTag;
  2101. }
  2102. }
  2103. }
  2104. if (next4) {
  2105. let curHref = next4.getAttribute("href");
  2106. let curPageReg = new RegExp("(.*)" + (pageNum + 1) + afterStr.replace(/([\.\?])/g, '\\$1'));
  2107. let otherPageHref = curHref.replace(curPageReg, `$1${pageNum}${afterStr}`);
  2108. let otherPageEle = body.querySelector(`a[href='${otherPageHref}']`);
  2109. if (!otherPageEle) {
  2110. otherPageHref = curHref.replace(curPageReg, `$1${pageNum + 2}${afterStr}`);
  2111. otherPageEle = body.querySelector(`a[href='${otherPageHref}']`);
  2112. }
  2113. if (otherPageEle) {
  2114. let parent = otherPageEle.parentNode;
  2115. if (parent && parent.parentNode) {
  2116. parent = parent.parentNode;
  2117. if (parent.parentNode) {
  2118. parent = parent.parentNode;
  2119. }
  2120. }
  2121. if (parent && parent.contains(otherPageEle) && !/^\d+$/.test(otherPageEle.innerText.trim())) {
  2122. next4 = null;
  2123. }
  2124. }
  2125. }
  2126. }
  2127. }
  2128. if (next2 && doubtTextReg.test(next2.innerText)) {
  2129. next2 = this.verifyNext(next2, doc);
  2130. }
  2131. if (nextJs2 && doubtTextReg.test(nextJs2.innerText)) {
  2132. nextJs2 = this.verifyNext(nextJs2, doc);
  2133. }
  2134. if (next3) {
  2135. next3 = this.verifyNext(next3, doc);
  2136. }
  2137. if (nextJs3) {
  2138. nextJs3 = this.verifyNext(nextJs3, doc);
  2139. }
  2140. }
  2141. if (!next) next = next1 || next4 || next3 || next2;
  2142. if (!next) {
  2143. next = jsNext || nextJs1 || nextJs3 || nextJs2;
  2144. if (next && next.parentNode.className.indexOf('tab') != -1) next = null;
  2145. }
  2146. if (next && next.classList && next.classList.contains("results-more")) next=null;
  2147. if (next && next.hasAttribute && next.hasAttribute("disabled")) next=null;
  2148. return {next:next, canSave:canSave};
  2149. }
  2150.  
  2151. verifyNext(next, doc) {
  2152. if (!next) return null;
  2153. if (next.previousElementSibling && /^BR$/i.test(next.previousElementSibling.nodeName)) return null;
  2154. let eles = getAllElements(`//${next.nodeName}[text()='${next.innerText}']`, doc);
  2155. if (eles.length >= 2 && eles[0].href != eles[1].href) {
  2156. next = null;
  2157. } else if (doc == document) {
  2158. let left = getElementLeft(next);
  2159. if (left < 20 || (document.documentElement.scrollWidth > 500 && left < 250)) {
  2160. next = null;
  2161. } else {
  2162. let top = getElementTop(next);
  2163. if (top < 20) {
  2164. next = null;
  2165. } else {
  2166. let bottom = top + next.offsetHeight || 0;
  2167. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  2168. if (scrollH - bottom < 10) next = null;
  2169. }
  2170. }
  2171. }
  2172. return next;
  2173. }
  2174.  
  2175. canonicalUri(src) {
  2176. if (!src) {
  2177. return "";
  2178. }
  2179. if (src.charAt(0) == "#") return this.curUrl + src;
  2180. if (src.charAt(0) == "?") return this.curUrl.replace(/^([^\?#]+).*/, "$1" + src);
  2181. let origin = location.protocol + '//' + location.host;
  2182. let url = this.basePath || origin;
  2183. url = url.replace(/(\?|#).*/, "");
  2184. if (/https?:\/\/[^\/]+$/.test(url)) url = url + '/';
  2185. if (url.indexOf("http") !== 0) url = origin + url;
  2186. var root_page = /^[^\?#]*\//.exec(url)[0],
  2187. root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  2188. absolute_regex = /^\w+\:\/\//;
  2189. this.updateUrl = false;
  2190. while (src.indexOf("../") === 0) {
  2191. src = src.substr(3);
  2192. root_page = root_page.replace(/\/[^\/]+\/$/, "/");
  2193. this.updateUrl = true;
  2194. }
  2195. src = src.replace(/\.\//, "");
  2196. if (/^\/\/\/?/.test(src)) {
  2197. src = location.protocol + src;
  2198. }
  2199. return (absolute_regex.test(src) ? src : ((src.charAt(0) == "/" ? root_domain : root_page) + src));
  2200. }
  2201.  
  2202. getLinkByPage(url, pageNum) {
  2203. if (!url) return;
  2204. if (this.curSiteRule.pageNum) {
  2205. let result = this.curSiteRule.pageNum;
  2206. let strMatch = result.match(/\{.*?}/);
  2207. if (!strMatch) return null;
  2208. let urlReg = new RegExp("(" + result.replace(strMatch[0], ")\\d+(") + ")", "i");
  2209. let code = strMatch[0].replace(/^{/, "").replace(/}$/, "").replace(/\$p/g, pageNum);
  2210. if (code == pageNum) {
  2211. result = url.replace(urlReg, "$1" + code + "$2");
  2212. } else {
  2213. try {
  2214. code = Function('"use strict";return ' + code)();
  2215. result = url.replace(urlReg, "$1" + code + "$2");
  2216. } catch(e) {
  2217. debug(e);
  2218. }
  2219. }
  2220. if (result != url) {
  2221. return result;
  2222. }
  2223. }
  2224. return url.replace(/([&\/\?](p=|page[=\/_-]?))\d+/i, "$1" + pageNum).replace(/([_-])\d+\./i, "$1" + pageNum + ".");
  2225. }
  2226.  
  2227. getPageNumFromUrl(url) {
  2228. if (!url) return curPage;
  2229. if (this.curSiteRule.pageNum) {
  2230. let result = this.curSiteRule.pageNum;
  2231. let strMatch = result.match(/\{.*?}/);
  2232. if (!strMatch) return null;
  2233. let urlReg = new RegExp(".*" + result.replace(strMatch[0], "(\\d+)") + ".*", "i");
  2234. let curShowNum = url.replace(urlReg, "$1");
  2235. if (curShowNum != url) {
  2236. let code = strMatch[0].replace(/^{/, "").replace(/}$/, "");
  2237. if (code == "$p") {
  2238. return curShowNum;
  2239. } else {
  2240. try {
  2241. let page1 = Function('"use strict";return ' + code.replace("$p", "0"))();
  2242. let page2 = Function('"use strict";return ' + code.replace("$p", "1"))();
  2243. let numGap = page2 - page1;
  2244. return (curShowNum - page1) / numGap;
  2245. } catch(e) {
  2246. debug(e);
  2247. }
  2248. }
  2249. } else {
  2250. return curPage;
  2251. }
  2252. }
  2253. let pageNum = url.replace(/.*[&\/\?](p=|page[=\/_-]?)(\d+).*/i, "$2");
  2254. return pageNum == url ? curPage : (pageNum.length > 4 ? curPage : pageNum);
  2255. }
  2256.  
  2257. async getNextLink(doc) {
  2258. let nextLink = null, page, href;
  2259. let getNextLinkByForm = (form, submitBtn, n) => {
  2260. let params = [];
  2261. let formData = new FormData(form);
  2262. if (submitBtn && submitBtn.getAttribute) {
  2263. let btnValue, btnName;
  2264. btnName = submitBtn.getAttribute("name");
  2265. btnValue = submitBtn.getAttribute("value");
  2266. if (btnName && btnValue) params = [btnName + "=" + btnValue];
  2267. }
  2268. for (let [key, value] of formData) {
  2269. if (n && /^(p|page)$/i.test(key)) {
  2270. params.push(key + '=' + n);
  2271. } else {
  2272. params.push(key + '=' + encodeURIComponent(value));
  2273. }
  2274. }
  2275. params = params.join('&');
  2276. return form.action + (form.action.indexOf('?') == -1 ? '?' : '&') + params + (form.method == 'post' ? '#p{' + params + '}' : '');
  2277. };
  2278. if (this.curSiteRule.pageElementByJs) {
  2279. this.nextLinkHref = "#";
  2280. return true;
  2281. } else if (this.curSiteRule.nextLinkByJs) {
  2282. try {
  2283. let over = _url => {
  2284. };
  2285. let targetUrl = await ((typeof _unsafeWindow.pagetualNextLinkByJs == 'undefined') ? new AsyncFunction("doc", '"use strict";' + this.curSiteRule.nextLinkByJs) : _unsafeWindow.pagetualNextLinkByJs)(doc);
  2286. if (targetUrl) nextLink = {href: targetUrl};
  2287. } catch(e) {
  2288. debug(e);
  2289. }
  2290. } else if (this.curSiteRule.nextLinkByUrl) {
  2291. let targetUrl = this.curUrl.replace(new RegExp(this.curSiteRule.nextLinkByUrl[0], "i"), this.curSiteRule.nextLinkByUrl[1]);
  2292. if (targetUrl != this.curUrl) {
  2293. let includeSel = this.curSiteRule.nextLinkByUrl[2];
  2294. let excludeSel = this.curSiteRule.nextLinkByUrl[3];
  2295. if (includeSel) {
  2296. includeSel = includeSel.trim();
  2297. if (!getElement(includeSel, doc)) {
  2298. this.nextLinkHref=false;
  2299. return null;
  2300. }
  2301. }
  2302. if (excludeSel) {
  2303. excludeSel = excludeSel.trim();
  2304. if (getElement(excludeSel, doc)) {
  2305. this.nextLinkHref=false;
  2306. return null;
  2307. }
  2308. }
  2309. let reps = targetUrl.match(/{.*?}/g);
  2310. if (reps) {
  2311. reps.forEach(rep => {
  2312. let code = rep.replace("{", "").replace("}", "").replace(/\(\)/g, "0");
  2313. let result = code.match(/^(\d*)\+1$/);
  2314. if (result) {
  2315. result = parseInt(result[1] || 1) + 1;
  2316. } else {
  2317. try {
  2318. result = Function('"use strict";return ' + code)();
  2319. } catch(e) {
  2320. debug(e);
  2321. }
  2322. }
  2323. targetUrl = targetUrl.replace(rep, result);
  2324. });
  2325. }
  2326. }
  2327. nextLink = {href: targetUrl};
  2328. } else if (this.curSiteRule.nextLink) {
  2329. let nextLinkSel = this.curSiteRule.nextLink;
  2330. if (nextLinkSel != 0) {
  2331. if (Array && Array.isArray && Array.isArray(nextLinkSel)) {
  2332. nextLink = getElement(nextLinkSel[nextIndex], doc);
  2333. if (!nextLink && curPage == 1 && nextIndex != 0) {
  2334. nextIndex = 0;
  2335. nextLink = getElement(nextLinkSel[nextIndex], doc);
  2336. }
  2337. } else nextLink = getElement(nextLinkSel, doc);
  2338. }
  2339. if (nextLink && (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2)) {
  2340. let form = doc.querySelector('#search-form');
  2341. if (!nextLink.href && nextLink.hasAttribute && nextLink.hasAttribute("onclick") && form) {
  2342. if (/^\d+$/.test(nextLink.innerText)) {
  2343. nextLink.href = getNextLinkByForm(form, nextLink, nextLink.innerText);
  2344. }
  2345. } else if (/^INPUT$/i.test(nextLink.nodeName) || nextLink.type == "submit") {
  2346. form = nextLink.parentNode;
  2347. while (form) {
  2348. if (/^FORM$/i.test(form.nodeName)) break;
  2349. else form = form.parentNode;
  2350. }
  2351. if (form) {
  2352. nextLink.href = getNextLinkByForm(form, nextLink);
  2353. }
  2354. }
  2355. if (nextLink.href && this.curSiteRule.action != 0) {
  2356. nextLink.href = nextLink.href.replace(/#p{.*/, "");
  2357. }
  2358. }
  2359. } else {
  2360. page = await this.getPage(doc);
  2361. nextLink = page.next;
  2362. if (nextLink) {
  2363. if (/^INPUT$/i.test(nextLink.nodeName) || nextLink.type == "submit") {
  2364. let form = nextLink.parentNode;
  2365. while (form) {
  2366. if (/^FORM$/i.test(form.nodeName)) break;
  2367. else form = form.parentNode;
  2368. }
  2369. if (form) {
  2370. nextLink.href = getNextLinkByForm(form, nextLink);
  2371. }
  2372. }
  2373. let parent = nextLink;
  2374. while (parent && !/^BODY$/i.test(parent.nodeName)) {
  2375. if (/^ASIDE$/i.test(parent.nodeName)) {
  2376. this.nextLinkHref = false;
  2377. return null;
  2378. }
  2379. if (parent.hasAttribute && parent.hasAttribute("disabled")) {
  2380. this.nextLinkHref = false;
  2381. return null;
  2382. }
  2383. if (parent.className && parent.classList) {
  2384. if (parent.classList.contains("noClick") || parent.classList.contains("no-pages") || parent.classList.contains("disabled")) {
  2385. this.nextLinkHref = false;
  2386. return null;
  2387. }
  2388. }
  2389. if (parent.style && parent.style.display === "none") {
  2390. this.nextLinkHref = false;
  2391. return null;
  2392. }
  2393. parent = parent.parentNode;
  2394. }
  2395. if (doc == document) {
  2396. if ((!nextLink.href || /^(javascript|#)/.test(nextLink.href.replace(location.href, ""))) && !isVisible(nextLink, _unsafeWindow)) {
  2397. this.nextLinkHref = false;
  2398. return null;
  2399. } else {
  2400. let nextLinkCs = _unsafeWindow.getComputedStyle(nextLink);
  2401. if (nextLinkCs.cursor == "not-allowed") {
  2402. this.nextLinkHref = false;
  2403. return null;
  2404. }
  2405. this.initNext = nextLink;
  2406. }
  2407. }
  2408. let form = doc.querySelector('#search-form');
  2409. if (!nextLink.href && nextLink.hasAttribute("onclick") && form) {
  2410. if (form && /^\d+$/.test(nextLink.innerText)) {
  2411. href = getNextLinkByForm(form, nextLink, nextLink.innerText);
  2412. }
  2413. }
  2414. }
  2415. }
  2416. if (nextLink) {
  2417. if (!this.checkStopSign(nextLink, doc)) return null;
  2418. if (this.curSiteRule.action == 3) {
  2419. if (doc == document) debug(nextLink, 'Next link');
  2420. this.nextLinkHref = '#';
  2421. } else {
  2422. let needUrl = (this.curSiteRule.action == 0 || this.curSiteRule.action == 1 || this.curSiteRule.action == 2);
  2423. if (!href) href = nextLink.href;
  2424. if (href && nextLink.getAttribute) {
  2425. let _href = nextLink.getAttribute("href");
  2426. if (_href) {
  2427. if (_href.charAt(0) == "#" || _href == "?"){
  2428. href = "#";
  2429. } else {
  2430. href = _href;
  2431. }
  2432. }
  2433. }
  2434.  
  2435. if (needUrl && (href === "" || href === null)) {
  2436. this.nextLinkHref = false;
  2437. } else if (needUrl && /^(javascript:|#)/.test(href)) {
  2438. this.nextLinkHref = false;
  2439. } else {
  2440. this.nextLinkHref = (href && !/^(javascript:|#)/.test(href)) ? this.canonicalUri(href) : "#";
  2441. let tempUrl = this.nextLinkHref.replace(/#p{.*/, "");
  2442. 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 + "#"))) {
  2443. this.nextLinkHref = false;
  2444. } else if (doc == document) {
  2445. debug(nextLink, 'Next link');
  2446. }
  2447. }
  2448. }
  2449. } else {
  2450. this.nextLinkHref = false;
  2451. }
  2452. this.nextLinkEle = nextLink;
  2453. this.preload();
  2454. return nextLink;
  2455. }
  2456.  
  2457. compareUrl(url1, url2) {
  2458. if (url1 == url2) return true;
  2459. if (!url1 || !url2) return false;
  2460. let url1Arr = url1.split("?");
  2461. let url2Arr = url2.split("?");
  2462. if (url1Arr[0] != url2Arr[0]) return false;
  2463. if (!url1Arr[1] || !url2Arr[1]) return false;
  2464. url1Arr = url1Arr[1].split("&").sort().join("&");
  2465. url2Arr = url2Arr[1].split("&").sort().join("&");
  2466. return url1Arr == url2Arr;
  2467. }
  2468.  
  2469. checkStopSign(nextLink, doc) {
  2470. if (this.curSiteRule.stopSign) {
  2471. if (Array && Array.isArray && Array.isArray(this.curSiteRule.stopSign)) {
  2472. let includeSel = this.curSiteRule.stopSign[0];
  2473. let excludeSel = this.curSiteRule.stopSign[1];
  2474. let curSign = this.curSiteRule.stopSign[2];
  2475. let maxSign = this.curSiteRule.stopSign[3];
  2476. if (Array && Array.isArray && Array.isArray(includeSel) && !curSign) {
  2477. curSign = includeSel;
  2478. includeSel = false;
  2479. }
  2480. if (Array && Array.isArray && Array.isArray(excludeSel) && !maxSign) {
  2481. maxSign = excludeSel;
  2482. excludeSel = false;
  2483. }
  2484. if (includeSel) {
  2485. includeSel = includeSel.trim();
  2486. if (!getElement(includeSel, doc)) {
  2487. isPause = true;
  2488. this.nextLinkHref = false;
  2489. return false;
  2490. }
  2491. }
  2492. if (excludeSel) {
  2493. excludeSel = excludeSel.trim();
  2494. if (getElement(excludeSel, doc)) {
  2495. isPause = true;
  2496. this.nextLinkHref = false;
  2497. return false;
  2498. }
  2499. }
  2500. if (curSign && maxSign) {
  2501. let currentEle = getElement(curSign[0], doc);
  2502. let maxEle = getElement(maxSign[0], doc);
  2503. if (currentEle && maxEle) {
  2504. let currentSignNum, maxSignNum;
  2505. if (/\(.*\)/.test(curSign[1])) {
  2506. currentSignNum = currentEle.innerText.match(new RegExp(curSign[1]));
  2507. if (currentSignNum) currentSignNum = currentSignNum[1];
  2508. } else if (currentEle.getAttribute) {
  2509. currentSignNum = currentEle.getAttribute(curSign[1]);
  2510. }
  2511. if (/\(.*\)/.test(maxSign[1])) {
  2512. maxSignNum = maxEle.innerText.match(new RegExp(maxSign[1]));
  2513. if (maxSignNum) maxSignNum = maxSignNum[1];
  2514. } else if (maxEle.getAttribute) {
  2515. maxSignNum = maxEle.getAttribute(maxSign[1]);
  2516. }
  2517. if (currentSignNum && maxSignNum && currentSignNum == maxSignNum) {
  2518. isPause = true;
  2519. this.nextLinkHref = false;
  2520. return false;
  2521. }
  2522. }
  2523. }
  2524. } else {
  2525. try {
  2526. let stopSign = ((typeof _unsafeWindow.stopSign == 'undefined') ? Function("doc", "nextLink", '"use strict";' + this.curSiteRule.stopSign) : _unsafeWindow.stopSign)(doc, nextLink);
  2527. if (stopSign) {
  2528. isPause = true;
  2529. this.nextLinkHref = false;
  2530. return false;
  2531. }
  2532. } catch(e) {
  2533. debug(e);
  2534. }
  2535. }
  2536. }
  2537. return true;
  2538. }
  2539.  
  2540. preload() {
  2541. if (!rulesData.preload) return;
  2542. if (!this.nextLinkHref || this.nextLinkHref == "#") return;
  2543. let self = this, url = this.nextLinkHref;
  2544. let postParams = url.match(/#p{(.*)}$/);
  2545. if (postParams) {
  2546. postParams = postParams[1];
  2547. url = url.replace(/#p{.*/, "");
  2548. }
  2549. _GM_xmlhttpRequest({
  2550. url: url,
  2551. method: postParams ? 'POST' : 'GET',
  2552. data: postParams,
  2553. overrideMimeType: 'text/html;charset=' + (document.characterSet || document.charset || document.inputEncoding),
  2554. headers: {
  2555. 'Referer': location.href,
  2556. 'User-Agent': navigator.userAgent,
  2557. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + (document.characterSet || document.charset || document.inputEncoding),
  2558. },
  2559. timeout: 10000,
  2560. onload: function(res) {
  2561. var doc = null;
  2562. try {
  2563. doc = document.implementation.createHTMLDocument('');
  2564. doc.documentElement.innerHTML = res.response;
  2565. var body = getBody(doc);
  2566. if (body && body.firstChild) {
  2567. self.lazyImgAction(body.children);
  2568. }
  2569. if (!self.preloadDiv) {
  2570. self.preloadDiv = document.createElement('div');
  2571. self.preloadDiv.id = "pagetual-preload";
  2572. self.preloadDiv.style.cssText = 'display:none!important;';
  2573. getBody(document).appendChild(self.preloadDiv);
  2574. self.checkedImgs = {};
  2575. }
  2576. [].forEach.call(doc.images, i => {
  2577. let iSrc = i.src;
  2578. if (iSrc && !self.checkedImgs[iSrc]) {
  2579. self.checkedImgs[iSrc] = true;
  2580. let img = document.createElement('img');
  2581. img.src = iSrc;
  2582. self.preloadDiv.appendChild(img);
  2583. }
  2584. });
  2585. let code = self.curSiteRule.preloadImages;
  2586. if (code) {
  2587. let imgSrcArr = new Function("doc", '"use strict";' + code)(doc);
  2588. if (imgSrcArr && imgSrcArr.length) {
  2589. imgSrcArr.forEach(imgSrc => {
  2590. if (imgSrc && !self.checkedImgs[imgSrc]) {
  2591. self.checkedImgs[imgSrc] = true;
  2592. let img = document.createElement('img');
  2593. img.src = imgSrc;
  2594. self.preloadDiv.appendChild(img);
  2595. }
  2596. });
  2597. }
  2598. }
  2599. }
  2600. catch(e) {
  2601. debug(e);
  2602. return;
  2603. }
  2604. }
  2605. });
  2606. }
  2607.  
  2608. getInsert(refresh) {
  2609. if (refresh) {
  2610. this.insert = null;
  2611. }
  2612. if (this.insert && document.documentElement.contains(this.insert)) {
  2613. return this.insert;
  2614. }
  2615. if (this.curSiteRule.insert) {
  2616. let insertSel = this.curSiteRule.insert;
  2617. if (Array && Array.isArray && Array.isArray(insertSel)) {
  2618. insertSel = insertSel[nextIndex < insertSel.length ? nextIndex : 0];
  2619. }
  2620. this.insert = getElement(insertSel, document);
  2621. } else {
  2622. if (refresh) this.docPageElement = null;
  2623. let pageElement = this.getPageElement(document, _unsafeWindow);
  2624. if (this.curSiteRule.singleUrl && this.nextLinkHref == "#" && this.curSiteRule.pageElement === 'body') {
  2625. debug("Stop as jsNext & whole body");
  2626. isPause = true;
  2627. return null;
  2628. }
  2629. if (pageElement && pageElement.length > 0) {
  2630. var pELast = pageElement[pageElement.length - 1];
  2631. this.insert = pELast.nextSibling ? pELast.nextSibling : pELast.parentNode.appendChild(document.createTextNode(' '));
  2632. }
  2633. }
  2634. return this.insert;
  2635. }
  2636.  
  2637. pageInit(doc,eles){
  2638. let code=this.curSiteRule.pageInit;
  2639. if(code){
  2640. let initFunc=((typeof _unsafeWindow.pagetualPageInit=='undefined') ? Function("doc", "eles", '"use strict";' + code) : _unsafeWindow.pagetualPageInit);
  2641. let checkInit=(resolve)=>{
  2642. try{
  2643. if(initFunc(doc, eles)===false){
  2644. setTimeout(()=>{
  2645. checkInit(resolve);
  2646. },100);
  2647. } else {
  2648. resolve(true);
  2649. }
  2650. }catch(e){
  2651. resolve(false);
  2652. debug(e);
  2653. }
  2654. };
  2655. return new Promise((resolve) => {
  2656. checkInit(function(e) {
  2657. resolve(e)
  2658. });
  2659. })
  2660. }
  2661. }
  2662.  
  2663. pageAction(doc,eles) {
  2664. let code = this.curSiteRule.pageAction;
  2665. if (code) {
  2666. try {
  2667. ((typeof _unsafeWindow.pagetualPageAction == 'undefined') ? Function("doc", "eles", '"use strict";' + code) : _unsafeWindow.pagetualPageAction)(doc, eles);
  2668. } catch(e) {
  2669. debug(e);
  2670. }
  2671. }
  2672. this.openInNewTab(eles);
  2673. this.replaceElement(doc);
  2674. }
  2675.  
  2676. openInNewTab(eles) {
  2677. if (openInNewTab) {
  2678. [].forEach.call(eles, ele => {
  2679. if (/^A$/i.test(ele.nodeName) && ele.href && !/^(mailto:|javascript:)|#/.test(ele.href)) {
  2680. ele.setAttribute('target', openInNewTab == 1 ? '_blank' : '_self');
  2681. } else {
  2682. [].forEach.call(ele.querySelectorAll('a[href]:not([href^="mailto:"]):not([href^="javascript:"]):not([href^="#"])'), a => {
  2683. if (openInNewTab == 1) {
  2684. a.setAttribute('target', '_blank');
  2685. if (a.getAttribute('onclick') == 'atarget(this)') {
  2686. a.removeAttribute('onclick');
  2687. }
  2688. } else a.setAttribute('target', '_self');
  2689. });
  2690. }
  2691. });
  2692. }
  2693. }
  2694.  
  2695. lazyImgAction(eles) {
  2696. if (!eles || eles.length == 0) return;
  2697. let lazyImgSrc = this.curSiteRule.lazyImgSrc;
  2698. if (lazyImgSrc === 0 || lazyImgSrc === '0') return;
  2699. let setLazyImg = img => {
  2700. let realSrc;
  2701. if (lazyImgSrc) {
  2702. if (!Array.isArray(lazyImgSrc)) {
  2703. lazyImgSrc = [lazyImgSrc];
  2704. }
  2705. realSrc = img.getAttribute(lazyImgSrc[0]);
  2706. if (lazyImgSrc.length == 2) {
  2707. let removeProps = lazyImgSrc[1].split(",");
  2708. removeProps.forEach(prop => {
  2709. img.removeAttribute(prop.trim());
  2710. });
  2711. }
  2712. }
  2713. if (!realSrc) {
  2714. if (img.getAttribute("_src") && !img.src) {
  2715. realSrc = img.getAttribute("_src");
  2716. } else {
  2717. for (let i in lazyImgAttr) {
  2718. let attrName = lazyImgAttr[i];
  2719. let attrValue = img.getAttribute(attrName);
  2720. if (attrValue) {
  2721. realSrc = attrValue;
  2722. break;
  2723. }
  2724. }
  2725. }
  2726. if (!realSrc && img._lazyrias && img._lazyrias.srcset) {
  2727. realSrc = img._lazyrias.srcset[img._lazyrias.srcset.length - 1];
  2728. }
  2729. if (realSrc) {
  2730. img.removeAttribute("srcset");
  2731. } else if (img.srcset) {
  2732. var srcs = img.srcset.split(/[xw],/i), largeSize = 0;
  2733. srcs.forEach(srci => {
  2734. let srcInfo = srci.trim().split(" "), curSize = parseInt(srcInfo[1]);
  2735. if (srcInfo[1] && curSize > largeSize) {
  2736. largeSize = curSize;
  2737. realSrc = srcInfo[0];
  2738. }
  2739. });
  2740. }
  2741. }
  2742. if (realSrc) {
  2743. img.src = realSrc;
  2744. if (img.style.display == "none") {
  2745. img.style.display = "";
  2746. }
  2747. if (img.style.visibility == "hidden") {
  2748. img.style.visibility = "";
  2749. }
  2750. if (img.style.opacity == 0) {
  2751. img.style.opacity = "";
  2752. }
  2753. }
  2754. };
  2755. [].forEach.call(eles, ele => {
  2756. if (/^IMG$/i.test(ele.nodeName)) {
  2757. setLazyImg(ele);
  2758. } else {
  2759. [].forEach.call(ele.querySelectorAll("img,picture>source"), img => {
  2760. setLazyImg(img);
  2761. });
  2762. [].forEach.call(ele.querySelectorAll("div[data-src][data-thumb]"), div => {
  2763. div.style.setProperty("background-image", "url(" + div.dataset.src + ")", "important");
  2764. });
  2765. }
  2766. if (/^A$/i.test(ele.nodeName) && ele.classList.contains("lazyload")) {
  2767. if (ele.dataset.original) {
  2768. ele.style.backgroundImage = 'url("' + ele.dataset.original + '")';
  2769. }
  2770. } else {
  2771. [].forEach.call(ele.querySelectorAll("a.lazyload"), a => {
  2772. if (a.dataset.original) {
  2773. a.style.backgroundImage = 'url("' + a.dataset.original + '")';
  2774. }
  2775. });
  2776. }
  2777. });
  2778. }
  2779.  
  2780. initPage(callback) {
  2781. let self = this;
  2782. if (self.initing) return;
  2783. self.initing = true;
  2784. setTimeout(() => {
  2785. self.initing = false;
  2786. }, 100);
  2787. curPage = 1;
  2788. urlChanged = false;
  2789. this.clearAddedElements();
  2790. this.insert = null;
  2791. this.visibilityItems = [];
  2792. this.visibleIndex = -1;
  2793. this.pageDoc = document;
  2794. this.nextLinkHref = null;
  2795. this.curUrl = location.href;
  2796. this.oldUrl = "";
  2797. this.initUrl = location.href;
  2798. this.historyUrl = "";
  2799. let base = document.querySelector("base");
  2800. this.basePath = base ? base.href : location.href;
  2801. this.getRule(async () => {
  2802. isPause = false;
  2803. if (self.curSiteRule.enable == 0) {
  2804. debug("Stop as rule disable");
  2805. isPause = true;
  2806. _GM_registerMenuCommand(i18n("enable"), () => {
  2807. showTips(i18n("enableSiteTips"));
  2808. if(!self.customRules) {
  2809. self.customRules = [];
  2810. }
  2811. for (let i in self.customRules) {
  2812. if (self.customRules[i].url == self.curSiteRule.url) {
  2813. self.customRules.splice(i, 1);
  2814. break;
  2815. }
  2816. }
  2817. self.curSiteRule.enable = 1;
  2818. self.customRules.unshift(self.curSiteRule);
  2819. storage.setItem("customRules", self.customRules);
  2820. location.reload();
  2821. });
  2822. return;
  2823. }
  2824. //若是再亂匹配就不緩存wedata,或者只在找完本地規則之後再考慮wedata的緩存
  2825. if (self.curSiteRule.singleUrl) {
  2826. delete self.curSiteRule.pageElement;
  2827. self.smartRules = self.smartRules.filter(item => {return item && item.url != self.curSiteRule.url});
  2828. self.smartRules.unshift(self.curSiteRule);
  2829. if (self.smartRules.length > 100) {
  2830. self.smartRules.pop();
  2831. }
  2832. storage.setItem("smartRules", self.smartRules);
  2833. } else if (self.curSiteRule && self.curSiteRule.url.length > 13) {
  2834. self.addToHpRules();
  2835. }
  2836. let css = self.curSiteRule.css || rulesData.customCss;
  2837. if (css) {
  2838. let cssArr = css.split("inIframe:");
  2839. if (cssArr && cssArr.length) {
  2840. _GM_addStyle(cssArr[0]);
  2841. }
  2842. }
  2843. if (/sidesearch=(1|true)$/.test(self.curUrl)) {
  2844. openInNewTab = 0;
  2845. } else if (typeof self.curSiteRule.openInNewTab !== 'undefined') {
  2846. openInNewTab = self.curSiteRule.openInNewTab ? 1 : 2;
  2847. }
  2848. let autoClick = self.curSiteRule.autoClick;
  2849. if (autoClick) {
  2850. let autoClickBtn;
  2851. autoClickBtn = getElement(autoClick, document);
  2852. if (autoClickBtn) {
  2853. emuClick(autoClickBtn);
  2854. }
  2855. }
  2856. let code = self.curSiteRule.init;
  2857. if (code) {
  2858. try {
  2859. ((typeof _unsafeWindow.pagetualInit == 'undefined') ? Function('doc','win','iframe','"use strict";' + code) : _unsafeWindow.pagetualInit)(null, null, null);
  2860. } catch(e) {
  2861. debug(e);
  2862. }
  2863. }
  2864. await self.getNextLink(document);
  2865. self.refreshByClick();
  2866.  
  2867. let pageElementCss = self.curSiteRule.pageElementCss || rulesData.pageElementCss;
  2868. if (pageElementCss && pageElementCss !== '0') {
  2869. self.getPageElement(document, _unsafeWindow);
  2870. }
  2871. callback();
  2872. let initRun = typeof self.curSiteRule.initRun == 'undefined' ? rulesData.initRun : self.curSiteRule.initRun;
  2873. if (initRun && initRun != false && self.nextLinkHref) nextPage();
  2874. });
  2875. }
  2876.  
  2877. beginLoading() {
  2878. isLoading = true;
  2879. lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  2880. ruleParser.insertElement(loadingDiv);
  2881. if (forceState == 2) {
  2882. getBody(document).appendChild(loadingDiv);
  2883. } else {
  2884. let parent = loadingDiv.parentNode;
  2885. if (/^TBODY$/i.test(parent.nodeName)) {
  2886. parent = parent.parentNode;
  2887. }
  2888. if (/^TABLE$/i.test(parent.nodeName)) {
  2889. parent.parentNode.appendChild(loadingDiv);
  2890. }
  2891. }
  2892. getBody(document).scrollTop = lastScrollTop;
  2893. document.documentElement.scrollTop = lastScrollTop;
  2894. lastScrollTop = 0;
  2895. }
  2896.  
  2897. insertElement(ele) {
  2898. if (!this.insert || !this.insert.parentNode) {
  2899. this.getInsert();
  2900. }
  2901. if (this.insert) {
  2902. this.addedElePool.push(ele);
  2903. if (this.curSiteRule.insertPos == 2) {
  2904. this.insert.appendChild(ele);
  2905. } else {
  2906. this.insert.parentNode.insertBefore(ele, this.insert);
  2907. }
  2908. }
  2909. }
  2910.  
  2911. async insertPage(doc, eles, url, callback, tried) {
  2912. this.oldUrl = this.curUrl;
  2913. let oldTitle = this.pageDoc.title;
  2914. this.pageDoc = doc;
  2915. this.curUrl = url;
  2916. if (lastScrollTop == 0) lastScrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  2917. isLoading = true;
  2918. let nextLink = await this.getNextLink(doc);
  2919. this.nextTitle = "";
  2920. if (this.curSiteRule.pageBarText) {
  2921. if (this.curSiteRule.pageBarText == 1 || this.curSiteRule.pageBarText == true) {
  2922. this.nextTitle = doc.title;
  2923. } else {
  2924. try {
  2925. this.nextTitle = ((typeof _unsafeWindow.pagetualPageBarText == 'undefined') ? Function("doc",'"use strict";' + this.curSiteRule.pageBarText) : _unsafeWindow.pagetualPageBarText)(doc);
  2926. } catch(e) {
  2927. debug(e);
  2928. }
  2929. }
  2930. }
  2931. if (curPage == 1 && !tried && !nextLink && this.curSiteRule.singleUrl && this.curSiteRule.pageElement && this.curSiteRule.action != 0) {
  2932. this.curSiteRule.action = 1;
  2933. this.curUrl = location.href;
  2934. isLoading = false;
  2935. return false;
  2936. }
  2937. if (callback) callback(eles);
  2938. this.getInsert();
  2939. var self = this, newEles = [];
  2940. if (!eles || eles.length == 0 || !self.insert || !self.insert.parentNode) {
  2941. } else {
  2942. await this.pageInit(doc, eles);
  2943. [].forEach.call(eles, ele => {
  2944. let newEle = ele.cloneNode(true);
  2945. let oldCanvass = ele.querySelectorAll("canvas");
  2946. let newCanvass = newEle.querySelectorAll("canvas");
  2947. if (self.updateUrl) {
  2948. [].forEach.call(newEle.querySelectorAll("img"), img => {
  2949. if (img.getAttribute("src")) img.src = self.canonicalUri(img.getAttribute("src"));
  2950. });
  2951. [].forEach.call(newEle.querySelectorAll("a"), a => {
  2952. if (a.getAttribute("href")) a.href = self.canonicalUri(a.getAttribute("href"));
  2953. });
  2954. }
  2955. for (let i = 0; i < oldCanvass.length; i++) {
  2956. let oldCanvas = oldCanvass[i];
  2957. let newCanvas = newCanvass[i];
  2958. newCanvas.getContext('2d').drawImage(oldCanvas, 0, 0);
  2959. }
  2960. if (!/^(STYLE|SCRIPT)$/.test(newEle.nodeName)) self.visibilityItems.push(newEle);
  2961. self.insertElement(newEle);
  2962. newEles.push(newEle);
  2963. });
  2964. }
  2965. loadPageOver();
  2966. getBody(document).scrollTop = lastScrollTop;
  2967. document.documentElement.scrollTop = lastScrollTop;
  2968. lastScrollTop = 0;
  2969. this.pageAction(doc, newEles);
  2970. let enableHistory = this.curSiteRule.history;
  2971. let enableHistoryAfterInsert = false;
  2972. if (enableHistory == 1) {
  2973. enableHistory = true;
  2974. } else if (enableHistory == 2) {
  2975. enableHistory = true;
  2976. enableHistoryAfterInsert = true;
  2977. } else if (enableHistory == 0) {
  2978. enableHistory = false;
  2979. } else {
  2980. enableHistory = rulesData.enableHistory;
  2981. enableHistoryAfterInsert = rulesData.enableHistoryAfterInsert;
  2982. }
  2983. if (enableHistory) {
  2984. this.historyUrl = enableHistoryAfterInsert ? this.curUrl : this.oldUrl;
  2985. if(this.historyUrl != location.href) {
  2986. let isJs = /^(javascript|#)/.test(this.historyUrl.replace(location.href, ""));
  2987. if (!isJs) {
  2988. let historyTitle = enableHistoryAfterInsert ? doc.title : oldTitle;
  2989. _unsafeWindow.history.replaceState(undefined, historyTitle, this.historyUrl);
  2990. document.title = historyTitle;
  2991. }
  2992. }
  2993. }
  2994. isLoading = false;
  2995. return true;
  2996. }
  2997. }
  2998. var ruleParser = new RuleParser();
  2999.  
  3000. class SideController {
  3001. //static controller;
  3002. constructor() {
  3003. this.inited = false;
  3004. }
  3005.  
  3006. /*static getInstance() {
  3007. if (!SideController.controller) {
  3008. SideController.controller = new SideController();
  3009. }
  3010. return SideController.controller;
  3011. }*/
  3012.  
  3013. setup() {
  3014. if (ruleParser.curSiteRule.sideController === false) return;
  3015. if (!rulesData.sideController && !ruleParser.curSiteRule.sideController) return;
  3016. this.addToStage();
  3017. }
  3018.  
  3019. init() {
  3020. if (this.inited) return;
  3021. this.inited = true;
  3022. let self = this;
  3023. this.cssText = `
  3024. #pagetual-sideController {
  3025. position: fixed;
  3026. top: calc(50% - 83px);
  3027. left: calc(99% - 40px);
  3028. width: 40px;
  3029. border-radius: 20px;
  3030. box-shadow: rgb(0 0 0) 0px 0px 10px;
  3031. text-align: center;
  3032. background: #ffffffd0!important;
  3033. user-select: none;
  3034. z-index: 2147483646!important;
  3035. padding: 0!important;
  3036. opacity: 0.5;
  3037. transition: opacity .5s ease, background .5s, box-shadow .5s;
  3038. }
  3039. #pagetual-sideController:hover {
  3040. opacity: 1;
  3041. }
  3042. #pagetual-sideController * {
  3043. font-weight: bold;
  3044. font-family: arial;
  3045. font-style: normal;
  3046. font-size: 20px!important;
  3047. color: black!important;
  3048. line-height: normal;
  3049. float: none;
  3050. }
  3051. #pagetual-sideController.stop {
  3052. -webkit-filter: invert(100%);
  3053. filter: invert(100%);
  3054. }
  3055. .pagetual-sideController-btn {
  3056. padding: 5px 0;
  3057. cursor: pointer;
  3058. transition: transform .15s ease-in-out, opacity .3s ease;
  3059. }
  3060. #pagetual-sideController .pagetual-sideController-btn:hover {
  3061. transform: scale(1.5);
  3062. color: red!important;
  3063. }
  3064. #pagetual-sideController.minSize {
  3065. box-shadow: rgb(0 0 0 / 0%) 0px 0px 0px;
  3066. background: #00000000!important;
  3067. }
  3068. #pagetual-sideController.minSize .pagetual-sideController-btn {
  3069. opacity: 0;
  3070. }
  3071. #pagetual-sideController #pagetual-sideController-move > svg {
  3072. transition: transform .3s ease;
  3073. }
  3074. #pagetual-sideController #pagetual-sideController-move > svg:hover {
  3075. transform: scale(1.2);
  3076. }
  3077. #pagetual-sideController.minSize #pagetual-sideController-move > svg {
  3078. background: white;
  3079. opacity: 0;
  3080. }
  3081. #pagetual-sideController #pagetual-sideController-move > img,
  3082. #pagetual-sideController #pagetual-sideController-move > span {
  3083. width: 35px;
  3084. height: 35px;
  3085. cursor: pointer;
  3086. }
  3087. #pagetual-sideController.minSize #pagetual-sideController-move > img,
  3088. #pagetual-sideController.minSize #pagetual-sideController-move > span {
  3089. border-radius: 50px;
  3090. text-shadow: rgb(255 255 255) 0px 0px 10px;
  3091. }
  3092. #pagetual-sideController #pagetual-sideController-pagenum {
  3093. font-size: 15px!important;
  3094. line-height: 30px;
  3095. text-align: center;
  3096. position: absolute;
  3097. right: calc(50% - 15px);
  3098. top: calc(50% - 15px);
  3099. border: 1px solid #00000099;
  3100. display: inline-block;
  3101. width: 30px;
  3102. height: 30px;
  3103. box-sizing: border-box;
  3104. border-radius: 50%;
  3105. background: white;
  3106. opacity: 0;
  3107. transition: opacity .5s ease;
  3108. pointer-events: none;
  3109. }
  3110. #pagetual-sideController.minSize #pagetual-sideController-pagenum {
  3111. opacity: 0.6;
  3112. }
  3113. `;
  3114. let frame = document.createElement("div");
  3115. frame.id = "pagetual-sideController";
  3116. frame.innerHTML = createHTML(`
  3117. <div id="pagetual-sideController-top" class="pagetual-sideController-btn">⊼</div>
  3118. <div>
  3119. <div id="pagetual-sideController-pre" class="pagetual-sideController-btn">∧</div>
  3120. <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>
  3121. <div id="pagetual-sideController-next" class="pagetual-sideController-btn">∨</div>
  3122. </div>
  3123. <div id="pagetual-sideController-bottom" class="pagetual-sideController-btn">⊻</div>
  3124. `);
  3125. let top = frame.querySelector("#pagetual-sideController-top");
  3126. let pre = frame.querySelector("#pagetual-sideController-pre");
  3127. let move = frame.querySelector("#pagetual-sideController-move");
  3128. let next = frame.querySelector("#pagetual-sideController-next");
  3129. let bottom = frame.querySelector("#pagetual-sideController-bottom");
  3130. let pagenum = frame.querySelector("#pagetual-sideController-pagenum");
  3131. if (sideControllerIcon) move.innerHTML = sideControllerIcon;
  3132.  
  3133. frame.addEventListener("dblclick", e => {
  3134. e.preventDefault();
  3135. e.stopPropagation();
  3136. }, true);
  3137.  
  3138. frame.addEventListener("mouseenter", e => {
  3139. clearTimeout(self.hideTimer);
  3140. frame.classList.remove("minSize");
  3141. });
  3142.  
  3143. frame.addEventListener("mouseleave", e => {
  3144. clearTimeout(self.hideTimer);
  3145. self.hideTimer = setTimeout(() => {
  3146. frame.classList.add("minSize");
  3147. }, 800);
  3148. });
  3149.  
  3150. pre.addEventListener("click", e => {
  3151. let prePageBar = getPageBar().preBar;
  3152. if (prePageBar) {
  3153. scrollToPageBar(prePageBar);
  3154. } else {
  3155. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3156. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  3157. }
  3158. }, true);
  3159.  
  3160. next.addEventListener("click", e => {
  3161. let pageBarObj = getPageBar();
  3162. let nextPageBar = pageBarObj.nextBar;
  3163. if (nextPageBar) {
  3164. scrollToPageBar(nextPageBar);
  3165. } else {
  3166. if (pageBarObj.preBar) {
  3167. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  3168. window.scrollTo({ top: (scrollH || 9999999), behavior: 'smooth'});
  3169. } else {
  3170. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  3171. window.scrollTo({ top: scrollTop + (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  3172. }
  3173. }
  3174. }, true);
  3175.  
  3176. top.addEventListener("click", e => {
  3177. getBody(document).scrollTop=0;
  3178. document.documentElement.scrollTop=0;
  3179. e.preventDefault();
  3180. e.stopPropagation();
  3181. }, true);
  3182.  
  3183. bottom.addEventListener("click", e => {
  3184. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  3185. changeStop(true);
  3186. }
  3187. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  3188. getBody(document).scrollTop = scrollH || 9999999;
  3189. document.documentElement.scrollTop = scrollH || 9999999;
  3190. e.preventDefault();
  3191. e.stopPropagation();
  3192. }, true);
  3193.  
  3194. let initX, initY, moving = false;
  3195. move.addEventListener("click", e => {
  3196. if (!moving) {
  3197. changeStop(!isPause);
  3198. }
  3199. }, true);
  3200.  
  3201. move.oncontextmenu = e => {
  3202. e.preventDefault();
  3203. picker.start();
  3204. };
  3205. let removeTimer;
  3206.  
  3207. let mouseMoveHandler = e => {
  3208. if (moving) {
  3209. let windowHeight=window.innerHeight || document.documentElement.clientHeight;
  3210. let windowWidth=window.innerWidth || document.documentElement.clientWidth;
  3211. initX = (e.clientX - 10 + 40) / windowWidth * 100;
  3212. initY = (e.clientY - 83 + 83) / windowHeight * 100;
  3213. this.frame.style.top = `calc(${initY}% - 83px)`;
  3214. this.frame.style.left = `calc(${initX}% - 40px)`;
  3215. } else if (Math.abs(e.clientX - initX) + Math.abs(e.clientY - initY) > 20) {
  3216. moving = true;
  3217. clearTimeout(removeTimer);
  3218. }
  3219. };
  3220. let mouseUpHandler = e => {
  3221. clearTimeout(removeTimer);
  3222. document.removeEventListener("mousemove", mouseMoveHandler, true);
  3223. document.removeEventListener("mouseup", mouseUpHandler, true);
  3224. if (moving) {
  3225. rulesData.sideControllerPos = {x: parseInt(initX), y: parseInt(initY)};
  3226. storage.setItem("rulesData", rulesData);
  3227. }
  3228. };
  3229.  
  3230. move.addEventListener("mousedown", e => {
  3231. initX = e.clientX;
  3232. initY = e.clientY;
  3233. moving = false;
  3234. clearTimeout(removeTimer);
  3235. removeTimer = setTimeout(() => {
  3236. self.remove();
  3237. }, 1500);
  3238. document.addEventListener("mousemove", mouseMoveHandler, true);
  3239. document.addEventListener("mouseup", mouseUpHandler, true);
  3240. }, true);
  3241.  
  3242. this.frame = frame;
  3243. this.pagenum = pagenum;
  3244. if (rulesData.sideControllerPos) {
  3245. this.frame.style.top = `calc(${rulesData.sideControllerPos.y}% - 83px)`;
  3246. this.frame.style.left = `calc(${rulesData.sideControllerPos.x}% - 40px)`;
  3247. }
  3248. }
  3249.  
  3250. addToStage() {
  3251. this.init();
  3252. if (!this.styleEle || !this.styleEle.parentNode) {
  3253. this.styleEle = _GM_addStyle(this.cssText);
  3254. }
  3255. if (!isPause) {
  3256. this.frame.classList.remove("stop");
  3257. }
  3258. this.pagenum.innerText = curPage;
  3259. this.frame.title = i18n("page") + curPage;
  3260. if (this.frame.parentNode) return;
  3261. getBody(document).appendChild(this.frame);
  3262. clearTimeout(this.hideTimer);
  3263. this.frame.classList.add("minSize");
  3264. }
  3265.  
  3266. remove() {
  3267. if (this.frame && this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  3268. }
  3269. }
  3270. const sideController = new SideController();
  3271.  
  3272. class NextSwitch {
  3273. //static nextSwitch;
  3274. constructor() {
  3275. this.inited = false;
  3276. }
  3277.  
  3278. /*static getInstance() {
  3279. if (!NextSwitch.nextSwitch) {
  3280. NextSwitch.nextSwitch = new NextSwitch();
  3281. }
  3282. return NextSwitch.nextSwitch;
  3283. }*/
  3284.  
  3285. init() {
  3286. if (this.inited) return;
  3287. this.inited = true;
  3288. let self = this;
  3289. this.cssText = `
  3290. #pagetual-nextSwitch {
  3291. position: fixed;
  3292. top: 10px;
  3293. left: calc(50% - 160px);
  3294. background: aliceblue;
  3295. padding: 10px;
  3296. border-radius: 5px;
  3297. text-align: center;
  3298. opacity: 0.95;
  3299. color: #161616;
  3300. z-index: 2147483647;
  3301. font-size: 16px;
  3302. box-shadow: rgb(0 0 0) 0px 0px 10px;
  3303. }
  3304. #pagetual-nextSwitch>.title {
  3305. margin: -5px 45px 10px 45px;
  3306. font-size: 20px;
  3307. font-weight: bold;
  3308. border-bottom: 1px solid black;
  3309. user-select: none;
  3310. color: orangered;
  3311. }
  3312. #pagetual-nextSwitch>.group {
  3313. display: flex;
  3314. flex-direction: column;
  3315. }
  3316. #pagetual-nextSwitch>.group>span {
  3317. color: #161616;
  3318. cursor: pointer;
  3319. margin: 3px;
  3320. font-size: larger;
  3321. }
  3322. #pagetual-nextSwitch>.group>span:hover {
  3323. color: red;
  3324. }
  3325. #pagetual-nextSwitch>.group>span.current {
  3326. border: 2px dotted red;
  3327. border-radius: 10px;
  3328. }
  3329. #pagetual-nextSwitch>.closeSwitch {
  3330. position: absolute;
  3331. top: 3px;
  3332. right: 10px;
  3333. background: none;
  3334. border: none;
  3335. vertical-align: top;
  3336. transition: transform .15s ease-in-out;
  3337. float: right;
  3338. cursor: pointer;
  3339. }
  3340. #pagetual-nextSwitch svg {
  3341. width: 30px;
  3342. height: 30px;
  3343. vertical-align: middle;
  3344. fill: #161616;
  3345. overflow: hidden;
  3346. }
  3347. #pagetual-nextSwitch button:hover {
  3348. transform: scale(1.2);
  3349. }
  3350. `;
  3351. let frame = document.createElement("div");
  3352. frame.id = "pagetual-nextSwitch";
  3353. frame.innerHTML = createHTML(`
  3354. <div class="title">${i18n("nextSwitch")}</div>
  3355. <button type="button" class="closeSwitch">
  3356. <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2754">
  3357. <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">
  3358. </path>
  3359. </svg>
  3360. </button>
  3361. <div class="group"></div>
  3362. `);
  3363. let group = frame.querySelector(".group");
  3364. let closeBtn = frame.querySelector(".closeSwitch");
  3365. closeBtn.addEventListener("click", e => {
  3366. self.close();
  3367. }, true);
  3368. this.frame = frame;
  3369. let currentSpan;
  3370. ruleParser.curSiteRule.nextLink.forEach((link, i) => {
  3371. let span = document.createElement("span");
  3372. let target = getElement(link, document);
  3373. let index = "<b>" + (i + 1) + "</b>: ";
  3374. if (target) {
  3375. let targetInner = target.innerText.trim();
  3376. span.innerHTML = index + (targetInner || link);
  3377. } else {
  3378. span.innerHTML = index + "Not Found";
  3379. }
  3380. span.title = link;
  3381. span.addEventListener("click", e => {
  3382. if (currentSpan) currentSpan.classList.remove("current");
  3383. span.classList.add("current");
  3384. currentSpan = span;
  3385. nextIndex = i;
  3386. storage.setItem("nextSwitch_" + location.host, nextIndex === 0 ? "" : nextIndex);
  3387. ruleParser.curUrl += "#pagetual";
  3388. ruleParser.oldUrl = ruleParser.curUrl;
  3389. autoLoadNum = -1;
  3390. if (!ruleParser.nextLinkHref) {
  3391. isLoading = false;
  3392. }
  3393. ruleParser.getNextLink(ruleParser.pageDoc || document);
  3394. self.close();
  3395. }, true);
  3396. if (i == nextIndex) {
  3397. span.classList.add("current");
  3398. currentSpan = span;
  3399. }
  3400. group.appendChild(span);
  3401. });
  3402. }
  3403.  
  3404. start() {
  3405. this.init();
  3406. if (!this.styleEle || !this.styleEle.parentNode) {
  3407. this.styleEle = _GM_addStyle(this.cssText);
  3408. }
  3409. document.documentElement.appendChild(this.frame);
  3410. }
  3411.  
  3412. close() {
  3413. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  3414. }
  3415. }
  3416. const nextSwitch = new NextSwitch();
  3417.  
  3418. class Picker {
  3419. //static picker;
  3420. constructor() {
  3421. this.inited = false;
  3422. }
  3423.  
  3424. /*static getInstance() {
  3425. if (!Picker.picker) {
  3426. Picker.picker = new Picker();
  3427. }
  3428. return Picker.picker;
  3429. }*/
  3430.  
  3431. init() {
  3432. if (this.inited) return;
  3433. this.inited = true;
  3434. let self = this;
  3435. this.signList = [];
  3436. this.cssText = `
  3437. body.pagetual-picker,
  3438. body.pagetual-picker *:hover,
  3439. body.pagetual-picker a:hover {
  3440. cursor: crosshair !important;
  3441. }
  3442. #pagetual-picker {
  3443. position: fixed;
  3444. top: 10px;
  3445. left: calc(50% - 178px);
  3446. background: aliceblue;
  3447. padding: 10px;
  3448. border-radius: 5px;
  3449. text-align: center;
  3450. opacity: 0.95;
  3451. color: #161616;
  3452. z-index: 2147483646;
  3453. font-size: 16px;
  3454. box-shadow: rgb(0 0 0) 0px 0px 10px;
  3455. }
  3456. #pagetual-picker * {
  3457. margin: 0;
  3458. padding: 0;
  3459. font-family: Times New Roman;
  3460. overflow: initial;
  3461. user-select: none;
  3462. }
  3463. #pagetual-picker>.title {
  3464. margin: -5px 45px 10px 45px;
  3465. font-size: 20px;
  3466. font-weight: bold;
  3467. cursor: move;
  3468. border-bottom: 1px solid black;
  3469. user-select: none;
  3470. color: orangered;
  3471. height: initial;
  3472. width: initial;
  3473. position: initial;
  3474. }
  3475. #pagetual-picker button {
  3476. background: none;
  3477. border: none;
  3478. vertical-align: top;
  3479. transition: transform .15s ease-in-out;
  3480. float: right;
  3481. cursor: pointer;
  3482. overflow: hidden;
  3483. }
  3484. #pagetual-picker button:hover {
  3485. transform: scale(1.2);
  3486. }
  3487. #pagetual-picker>.closePicker {
  3488. position: absolute;
  3489. top: 3px;
  3490. right: 10px;
  3491. }
  3492. #pagetual-picker>.logoIcon {
  3493. position: absolute;
  3494. top: 3px;
  3495. left: 10px;
  3496. }
  3497. #pagetual-picker>.logoIcon.showSign>svg>path {
  3498. fill: gray;
  3499. }
  3500. #pagetual-picker textarea{
  3501. display: inline-block;
  3502. width: calc(100% - 65px);
  3503. height: 40px;
  3504. min-width: 290px;
  3505. max-width: calc(65vw - 50px);
  3506. min-height: unset;
  3507. padding: 6px 12px;
  3508. font-size: 16px;
  3509. font-weight: 400;
  3510. line-height: 1.5;
  3511. color: #495057;
  3512. background-color: #fff;
  3513. background-clip: padding-box;
  3514. border: 1px solid #ced4da;
  3515. border-radius: 4px;
  3516. transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
  3517. box-sizing: content-box;
  3518. margin-right: 5px;
  3519. resize: both;
  3520. box-shadow: 0 1px 5px 1px #ddd;
  3521. }
  3522. #pagetual-picker textarea:focus {
  3523. color: black;
  3524. background-color: #fff;
  3525. border-color: #80bdff;
  3526. outline: 0;
  3527. box-shadow: 0 0 0 3.2px rgb(0 123 255 / 25%);
  3528. }
  3529. #pagetual-picker [type=checkbox],
  3530. #pagetual-picker [type=radio] {
  3531. line-height: 20px;
  3532. height: 25px;
  3533. width: 25px;
  3534. margin-left: 5px;
  3535. vertical-align: middle;
  3536. appearance: auto;
  3537. display: inline-block;
  3538. position: initial;
  3539. }
  3540. #pagetual-picker label {
  3541. font-size: 18px;
  3542. line-height: 25px;
  3543. vertical-align: middle;
  3544. display: inline-block;
  3545. color: black;
  3546. position: initial;
  3547. cursor: pointer;
  3548. }
  3549. #pagetual-picker .bottom {
  3550. text-align: left;
  3551. margin: 10px 0;
  3552. width: 100%;
  3553. }
  3554. #pagetual-picker .bottom>button {
  3555. float: right;
  3556. }
  3557. #pagetual-picker svg {
  3558. width: 30px;
  3559. height: 30px;
  3560. vertical-align: middle;
  3561. fill: #161616;
  3562. overflow: hidden;
  3563. }
  3564. #pagetual-picker svg * {
  3565. pointer-events: none;
  3566. }
  3567. #pagetual-picker .allpath {
  3568. font-size: 18px;
  3569. margin: 10px auto;
  3570. max-width: 330px;
  3571. word-break: break-all;
  3572. cursor: context-menu;
  3573. overflow: hidden;
  3574. max-height: 42px;
  3575. -moz-transition:max-height 1s ease-in;
  3576. -webkit-transition:max-height 1s ease-in;
  3577. transition:max-height 1s ease-in;
  3578. color: black;
  3579. }
  3580. #pagetual-picker .allpath:hover {
  3581. max-height: calc(100vh - 130px);
  3582. overflow: auto;
  3583. }
  3584. #pagetual-picker .allpath>span.path {
  3585. cursor: pointer;
  3586. }
  3587. #pagetual-picker .allpath>span.path:hover {
  3588. color: orangered;
  3589. }
  3590. #pagetual-picker .moreConfig {
  3591. display: flex;
  3592. justify-content: space-between;
  3593. border-top: 1px solid;
  3594. padding-top: 10px;
  3595. width: 100%;
  3596. }
  3597. #pagetual-picker .command {
  3598. width: 100%;
  3599. color: black!important;
  3600. text-align: center;
  3601. font-size: large;
  3602. margin-top: 10px;
  3603. }
  3604. #pagetual-picker .command:hover {
  3605. color: orangered;
  3606. }
  3607. #pagetual-picker #showDetail {
  3608. float: initial;
  3609. margin-top: 10px;
  3610. }
  3611. #pagetual-picker #showDetail.showDetail {
  3612. float: right;
  3613. }
  3614. #pagetual-picker #showDetail>svg {
  3615. -moz-transition:transform 0.3s ease;
  3616. -webkit-transition:transform 0.3s ease;
  3617. transition:transform 0.3 ease;
  3618. }
  3619. #pagetual-picker #showDetail.showDetail>svg {
  3620. transform: rotate(180deg);
  3621. }
  3622. #pagetual-picker .tempRule {
  3623. margin-top: 10px;
  3624. height: 300px;
  3625. min-height: 150px;
  3626. }
  3627. #pagetual-picker #saveDetail {
  3628. display: none;
  3629. position: absolute;
  3630. bottom: 10px;
  3631. right: 8px;
  3632. }
  3633. #pagetual-picker .showDetail~#saveDetail {
  3634. display: inline-block;
  3635. }
  3636. #pagetual-picker #saveDetail svg {
  3637. width: 35px;
  3638. height: 35px;
  3639. }
  3640. #pagetual-picker .addProp {
  3641. display: none;
  3642. flex-direction: column;
  3643. position: absolute;
  3644. bottom: 45px;
  3645. right: 12px;
  3646. }
  3647. #pagetual-picker .showDetail~.addProp {
  3648. display: flex;
  3649. }
  3650. #pagetual-picker .addProp>button {
  3651. font-size: 30px;
  3652. font-family: Arial,sans-serif;
  3653. line-height: 35px;
  3654. color: #161616;
  3655. }
  3656. `;
  3657. this.mainSignDiv = this.createSignDiv();
  3658. this.allSignDiv = [];
  3659. let frame = document.createElement("div");
  3660. frame.id = "pagetual-picker";
  3661. frame.innerHTML = createHTML(`
  3662. <button title="Pagetual" type="button" class="logoIcon">
  3663. <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>
  3664. </button>
  3665. <div class="title" title="${i18n("configure")}">${i18n("picker")}</div>
  3666. <button title="${i18n("closePicker")}" type="button" class="closePicker">
  3667. <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>
  3668. </button>
  3669. <div class="allpath" title="${i18n("switchSelector")}"></div>
  3670. <div>
  3671. <textarea class="selector" spellcheck="false" name="selector" placeholder="${i18n("pickerPlaceholder")}"></textarea>
  3672. <button id="check" title="${i18n("pickerCheck")}" type="button">
  3673. <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>
  3674. </button>
  3675. </div>
  3676. <div class="bottom">
  3677. <input name="xpath" id="checkbox_id" type="checkbox" />
  3678. <label for="checkbox_id">XPath</label>
  3679. <button id="edit" title="${i18n("gotoEdit")}" type="button">
  3680. <svg viewBox="0 0 1024 1024" style="color: orangered;fill: orangered;" version="1.1" xmlns="http://www.w3.org/2000/svg">
  3681. <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">
  3682. </path>
  3683. </svg>
  3684. </button>
  3685. </div>
  3686. <div class="moreConfig">
  3687. <div title="${i18n('forceStateIframe')}">
  3688. <input name="forceState" id="forceStateIframe" type="radio" />
  3689. <label for="forceStateIframe">${i18n('iframe')}</label>
  3690. </div>
  3691. <div title="${i18n('forceStateDynamic')}">
  3692. <input name="forceState" id="forceStateDynamic" type="radio" />
  3693. <label for="forceStateDynamic">${i18n('dynamic')}</label>
  3694. </div>
  3695. <div title="${i18n('forceStateDisable')}">
  3696. <input name="forceState" id="forceStateDisable" type="radio" />
  3697. <label for="forceStateDisable">${i18n('disable')}</label>
  3698. </div>
  3699. </div>
  3700. <button id="nextSwitch" class="command" title="${i18n("nextSwitch")}" type="button">${i18n("nextSwitch")}</button>
  3701. <button id="loadNow" class="command" title="${i18n("loadNow")}" type="button">${i18n("loadNow")}</button>
  3702. <div>
  3703. <textarea style="display: none;" class="tempRule" spellcheck="false" placeholder="{Rule object}" title="Rule for current site"></textarea>
  3704. <button id="showDetail" title="" type="button">
  3705. <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>
  3706. </button>
  3707. <div class="addProp">
  3708. <button id="addOtherProp" title="${i18n("addOtherProp")}" type="button">+</button>
  3709. <button id="addNextSelector" title="${i18n("addNextSelector")}" type="button">></button>
  3710. <button id="addPageSelector" title="${i18n("addPageSelector")}" type="button">❏</button>
  3711. </div>
  3712. <button id="saveDetail" title="${i18n("save")}" type="button">
  3713. <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>
  3714. </button>
  3715. </div>
  3716. `);
  3717. let forceStateIframe = frame.querySelector("#forceStateIframe");//forceState 1 禁用 2 强嵌 3 动态
  3718. let forceStateDynamic = frame.querySelector("#forceStateDynamic");
  3719. let forceStateDisable = frame.querySelector("#forceStateDisable");
  3720. let clickRadio = e => {
  3721. let radio = e.currentTarget.querySelector('input');
  3722. if (radio.checked) {
  3723. forceState = "";
  3724. } else {
  3725. switch (radio.id) {
  3726. case "forceStateIframe":
  3727. forceState = 2;
  3728. break;
  3729. case "forceStateDynamic":
  3730. forceState = 3;
  3731. break;
  3732. case "forceStateDisable":
  3733. forceState = 1;
  3734. break;
  3735. default:
  3736. return;
  3737. }
  3738. }
  3739. storage.setItem("forceState_"+location.host, forceState);
  3740. self.close();
  3741. location.reload();
  3742. };
  3743. forceStateIframe.parentNode.addEventListener("mousedown", clickRadio);
  3744. forceStateDynamic.parentNode.addEventListener("mousedown", clickRadio);
  3745. forceStateDisable.parentNode.addEventListener("mousedown", clickRadio);
  3746. if (forceState == 1) forceStateDisable.checked = true;
  3747. else if (forceState == 2) forceStateIframe.checked = true;
  3748. else if (forceState == 3) forceStateDynamic.checked = true;
  3749. let closeBtn = frame.querySelector(".closePicker");
  3750. let logoBtn = frame.querySelector(".logoIcon");
  3751. let title = frame.querySelector(".title");
  3752. let allpath = frame.querySelector(".allpath");
  3753. let selectorInput = frame.querySelector(".selector");
  3754. let xpath = frame.querySelector("#checkbox_id");
  3755. let checkBtn = frame.querySelector("#check");
  3756. let editBtn = frame.querySelector("#edit");
  3757. let nextSwitchBtn = frame.querySelector("#nextSwitch");
  3758. let loadNow = frame.querySelector("#loadNow");
  3759. let tempRule = frame.querySelector(".tempRule");
  3760. let showDetailBtn = frame.querySelector("#showDetail");
  3761. let saveDetailBtn = frame.querySelector("#saveDetail");
  3762. let addOtherProp = frame.querySelector("#addOtherProp");
  3763. let addNextSelector = frame.querySelector("#addNextSelector");
  3764. let addPageSelector = frame.querySelector("#addPageSelector");
  3765. addOtherProp.addEventListener("click", e => {
  3766. let propName = prompt(i18n("propName"));
  3767. if (!propName) return;
  3768. let propValue = prompt(i18n("propValue"));
  3769. if (!propValue) return;
  3770. if (propValue === "true") propValue = true;
  3771. else if (propValue === "false") propValue = false;
  3772. else if (/^\d+$/.test(propValue)) propValue = parseInt(propValue);
  3773. let editTemp = self.getTempRule();
  3774. if (!editTemp) return;
  3775. editTemp[propName] = propValue;
  3776. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  3777. }, true);
  3778. addNextSelector.addEventListener("click", e => {
  3779. let editTemp = self.getTempRule();
  3780. if (!editTemp) return;
  3781. let selector = self.selectorInput.value;
  3782. if (selector) {
  3783. editTemp.nextLink = selector;
  3784. }
  3785. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  3786. }, true);
  3787. addPageSelector.addEventListener("click", e => {
  3788. let editTemp = self.getTempRule();
  3789. if (!editTemp) return;
  3790. let selector = self.selectorInput.value;
  3791. if (selector) {
  3792. editTemp.pageElement = selector;
  3793. }
  3794. self.tempRule.value = JSON.stringify(editTemp, null, 4);
  3795. }, true);
  3796. showDetailBtn.addEventListener("click", e => {
  3797. if (tempRule.style.display == "none") {
  3798. tempRule.style.display = "";
  3799. showDetailBtn.classList.add("showDetail");
  3800. } else {
  3801. tempRule.style.display = "none";
  3802. showDetailBtn.classList.remove("showDetail");
  3803. }
  3804. }, true);
  3805. saveDetailBtn.addEventListener("click", e => {
  3806. let editTemp = self.getTempRule();
  3807. if(!ruleParser.customRules) {
  3808. ruleParser.customRules = [];
  3809. }
  3810. for (let i in ruleParser.customRules) {
  3811. if (ruleParser.customRules[i].url == editTemp.url) {
  3812. ruleParser.customRules.splice(i, 1);
  3813. break;
  3814. }
  3815. }
  3816. if (tempRule.value) {
  3817. ruleParser.customRules.unshift(editTemp);
  3818. ruleParser.curSiteRule = editTemp;
  3819. } else {
  3820. ruleParser.curSiteRule = {};
  3821. isPause = true;
  3822. }
  3823. storage.setItem("customRules", ruleParser.customRules);
  3824. if (ruleParser.hpRules && ruleParser.curSiteRule && !ruleParser.curSiteRule.singleUrl) {
  3825. ruleParser.addToHpRules(true);
  3826. }
  3827. if (window.confirm(i18n("reloadPage"))) {
  3828. setTimeout(() => {location.reload()}, 100);
  3829. }
  3830. }, true);
  3831. nextSwitchBtn.addEventListener("click", e => {
  3832. self.close();
  3833. nextSwitch.start();
  3834. }, true);
  3835. loadNow.addEventListener("click", e => {
  3836. self.close();
  3837. let loadNum=window.prompt(i18n("loadConfirm"), "1");
  3838. if(loadNum==="" || loadNum===null)return;
  3839. autoLoadNum=Math.abs(parseInt(loadNum));
  3840. nextPage();
  3841. }, true);
  3842. closeBtn.addEventListener("click", e => {
  3843. self.close();
  3844. }, true);
  3845. this.showSign = true;
  3846. logoBtn.addEventListener("click", e => {
  3847. logoBtn.classList.toggle("showSign");
  3848. self.showSign = !self.showSign;
  3849. getBody(document).classList.toggle("pagetual-picker");
  3850. }, true);
  3851. let moving = false;
  3852. let initX = 0, initY = 0, initPos = {x: 0, y: 0};
  3853. let moveHanlder = e => {
  3854. if (moving) {
  3855. frame.style.left = e.clientX - initX + "px";
  3856. frame.style.top = e.clientY - initY + "px";
  3857. e.stopPropagation();
  3858. e.preventDefault();
  3859. } else if(Math.abs(e.clientX - initPos.x) + Math.abs(e.clientY - initPos.y) > 20) {
  3860. moving = true;
  3861. }
  3862. };
  3863. let upHanlder = e => {
  3864. if (moving) {
  3865. moving = false;
  3866. } else {
  3867. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  3868. }
  3869. document.removeEventListener("mousemove", moveHanlder, true);
  3870. title.removeEventListener("mouseup", upHanlder, true);
  3871. e.stopPropagation();
  3872. e.preventDefault();
  3873. };
  3874. title.addEventListener("mousedown", e => {
  3875. initPos = {x: e.clientX, y: e.clientY};
  3876. initX = e.clientX - parseInt(getComputedStyle(frame).left);
  3877. initY = e.clientY - parseInt(getComputedStyle(frame).top);
  3878. document.addEventListener("mousemove", moveHanlder, true);
  3879. title.addEventListener("mouseup", upHanlder, true);
  3880. });
  3881. frame.addEventListener("mouseenter", e => {
  3882. if (!self.showSign || moving) return;
  3883. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  3884. self.checkInputSelector();
  3885. });
  3886. frame.addEventListener("mouseleave", e => {
  3887. if (!self.showSign) {
  3888. if (self.mainSignDiv.parentNode) self.mainSignDiv.parentNode.removeChild(self.mainSignDiv);
  3889. self.clearSigns();
  3890. return;
  3891. }
  3892. if (moving) return;
  3893. getBody(document).appendChild(self.mainSignDiv);
  3894. self.clearSigns();
  3895. });
  3896. checkBtn.addEventListener("click", e => {
  3897. self.checkInputSelector();
  3898. if (this.selectorInput.value) _GM_setClipboard(this.selectorInput.value);
  3899. showTips(i18n("copied"));
  3900. });
  3901. xpath.addEventListener("click", e => {
  3902. if (!selectorInput.value) {
  3903. self.setSelectorDiv("");
  3904. return;
  3905. }
  3906. let element = getElement(selectorInput.value, document);
  3907. let selector = self.getSelectorFromEle(element);
  3908. self.setSelectorDiv(selector);
  3909. selectorInput.value = selector;
  3910. });
  3911. editBtn.addEventListener("click", e => {
  3912. rulesData.editTemp = self.getTempRule();
  3913. storage.setItem("rulesData", rulesData);
  3914. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  3915. });
  3916. editBtn.oncontextmenu = e => {
  3917. e.preventDefault();
  3918. _GM_openInTab(rulesData.configPage || configPage[0], {active: true});
  3919. };
  3920. this.frame = frame;
  3921. this.xpath = xpath;
  3922. this.allpath = allpath;
  3923. this.selectorInput = selectorInput;
  3924. this.nextSwitchBtn = nextSwitchBtn;
  3925. this.loadNow = loadNow;
  3926. this.tempRule = tempRule;
  3927. this.logoBtn = logoBtn;
  3928. let setTitleTimer;
  3929. this.moveHandler = e => {
  3930. if (!self.showSign || e.target === document) return;
  3931. let target = self.getTarget(e.target);
  3932. self.adjustSignDiv(self.mainSignDiv, target);
  3933. clearTimeout(setTitleTimer);
  3934. setTitleTimer = setTimeout(() => {
  3935. if (self.inPicker && target.hasAttributes()) {
  3936. let title = target.nodeName + "\n";
  3937. for (const attr of target.attributes) {
  3938. title += `${attr.name}${attr.value ? " ➡️ " + attr.value : ""}\n`;
  3939. }
  3940. getBody(document).title = title;
  3941. }
  3942. }, 500);
  3943. };
  3944. this.clickHandler = e => {
  3945. if (!self.showSign) return;
  3946. if (self.inPicker) {
  3947. e.stopPropagation();
  3948. e.preventDefault();
  3949. }
  3950. let target = self.getTarget(e.target);
  3951. let selector = self.getSelectorFromEle(target);
  3952. selectorInput.value = selector;
  3953. self.setSelectorDiv(selector);
  3954. };
  3955. }
  3956.  
  3957. getTempRule() {
  3958. if (this.tempRule.value) {
  3959. try {
  3960. this.editTemp = JSON.parse(this.tempRule.value);
  3961. } catch (e) {
  3962. this.editTemp = null;
  3963. }
  3964. }
  3965. if (!this.editTemp) {
  3966. if (ruleParser.curSiteRule.url && !ruleParser.curSiteRule.singleUrl) {
  3967. this.editTemp = ruleParser.curSiteRule;
  3968. } else {
  3969. this.editTemp = {
  3970. name: document.title,
  3971. url: "^" + (location.origin + location.pathname).replace(/[^\/]*$/, "").replace(/^https?/, "https?").replace(/\./g, "\\."),
  3972. example: location.href
  3973. };
  3974. }
  3975. delete this.editTemp.from;
  3976. delete this.editTemp.type;
  3977. delete this.editTemp.updatedAt;
  3978. }
  3979. if (this.selectorInput.value && this.tempRule.style.display == "none") {
  3980. this.editTemp.pageElement = this.selectorInput.value;
  3981. }
  3982. return this.editTemp;
  3983. }
  3984.  
  3985. getTarget(ele) {
  3986. while (ele.parentNode && (ele.offsetWidth === 0 || ele.offsetHeight === 0)) {
  3987. ele = ele.parentNode;
  3988. }
  3989. return ele;
  3990. }
  3991.  
  3992. close() {
  3993. this.clearSigns();
  3994. if (this.frame.parentNode) this.frame.parentNode.removeChild(this.frame);
  3995. if (this.mainSignDiv.parentNode) this.mainSignDiv.parentNode.removeChild(this.mainSignDiv);
  3996. getBody(document).classList.remove("pagetual-picker");
  3997. getBody(document).removeEventListener("mousemove", this.moveHandler, true);
  3998. getBody(document).removeEventListener("click", this.clickHandler, true);
  3999. getBody(document).title = "";
  4000. this.inPicker = false;
  4001. }
  4002.  
  4003. setImportant(ele, prop, value) {
  4004. ele.style.setProperty(prop, value, "important");
  4005. }
  4006.  
  4007. createSignDiv() {
  4008. let signDiv = document.createElement("div");
  4009. this.setImportant(signDiv, "position", "absolute");
  4010. this.setImportant(signDiv, "pointer-events", "none");
  4011. this.setImportant(signDiv, "z-index", "2147483646");
  4012. this.setImportant(signDiv, "background", "rgba(120, 170, 210, 0.6)");
  4013. this.setImportant(signDiv, "transition", "all 0.15s ease-out");
  4014. this.setImportant(signDiv, "box-shadow", "rgb(0 0 0) 0px 0px 3px 0px");
  4015. return signDiv;
  4016. }
  4017.  
  4018. adjustSignDiv(div, target) {
  4019. let rect = target.getBoundingClientRect();
  4020. this.setImportant(div, "width", rect.width + "px");
  4021. this.setImportant(div, "height", rect.height + "px");
  4022. this.setImportant(div, "left", rect.left + window.scrollX + "px");
  4023. this.setImportant(div, "top", rect.top + window.scrollY + "px");
  4024. }
  4025.  
  4026. getSelectorFromEle(ele) {
  4027. return this.xpath.checked ? createXPathFromElement(ele) : geneSelector(ele, true);
  4028. }
  4029.  
  4030. fillTempRuleTextarea() {
  4031. if (this.tempRule.style.display == "none") this.tempRule.value = JSON.stringify(this.getTempRule(), null, 4);
  4032. }
  4033.  
  4034. setSelectorDiv(selector) {
  4035. this.fillTempRuleTextarea();
  4036. let self = this;
  4037. this.allpath.innerHTML = createHTML("");
  4038. if (!selector) return;
  4039. if (this.xpath.checked) {
  4040. let span = document.createElement("span");
  4041. span.innerText = selector;
  4042. span.addEventListener("click", e => {
  4043. self.selectorInput.value = selector;
  4044. self.checkInputSelector();
  4045. }, true);
  4046. this.allpath.appendChild(span);
  4047. } else {
  4048. selector.split(">").forEach((item, index) => self.geneSelectorItem(item, index));
  4049. }
  4050. }
  4051.  
  4052. geneSelectorItem(item, index) {
  4053. let self = this;
  4054. item = item.trim();
  4055. if (!item) return;
  4056. if (index !== 0) {
  4057. let span = document.createElement("span");
  4058. span.innerText = " > ";
  4059. this.allpath.appendChild(span);
  4060. }
  4061. let span = document.createElement("span");
  4062. span.className = "path";
  4063. span.innerText = item;
  4064. span.addEventListener("click", e => {
  4065. let selector = "";
  4066. let target = e.target;
  4067. while (target) {
  4068. selector = target.innerText + selector;
  4069. target = target.previousElementSibling;
  4070. }
  4071. self.selectorInput.value = selector;
  4072. self.checkInputSelector();
  4073. }, true);
  4074. this.allpath.appendChild(span);
  4075. }
  4076.  
  4077. checkInputSelector() {
  4078. let self = this;
  4079. this.clearSigns();
  4080. if (!this.selectorInput.value) return;
  4081. let eles = getAllElements(this.selectorInput.value, document);
  4082. if (eles && eles.length > 0) {
  4083. eles.forEach(ele => {
  4084. let sign = self.createSignDiv();
  4085. getBody(document).appendChild(sign);
  4086. self.adjustSignDiv(sign, ele);
  4087. self.signList.push(sign);
  4088. });
  4089. this.fillTempRuleTextarea();
  4090. }
  4091. }
  4092.  
  4093. clearSigns() {
  4094. this.signList.forEach(sign => {
  4095. if (sign.parentNode) sign.parentNode.removeChild(sign);
  4096. });
  4097. this.signList = [];
  4098. }
  4099.  
  4100. start() {
  4101. this.init();
  4102. if (this.inPicker) return;
  4103. this.inPicker = true;
  4104. if (!this.styleEle || !this.styleEle.parentNode) {
  4105. this.styleEle = _GM_addStyle(this.cssText);
  4106. }
  4107. document.documentElement.appendChild(this.frame);
  4108. getBody(document).appendChild(this.mainSignDiv);
  4109. getBody(document).classList.add("pagetual-picker");
  4110.  
  4111. this.logoBtn.classList.remove("showSign");
  4112. this.showSign = true;
  4113.  
  4114. getBody(document).addEventListener("mousemove", this.moveHandler, true);
  4115. getBody(document).addEventListener("click", this.clickHandler, true);
  4116. this.xpath.checked = isXPath(ruleParser.curSiteRule.pageElement);
  4117.  
  4118. this.loadNow.style.display = ruleParser.nextLinkHref ? "block" : "none";
  4119. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  4120. this.nextSwitchBtn.style.display = "block";
  4121. } else {
  4122. this.nextSwitchBtn.style.display = "none";
  4123. }
  4124.  
  4125. let pageElementSel = ruleParser.curSiteRule.pageElement || "";
  4126. if (Array && Array.isArray && Array.isArray(pageElementSel)) {
  4127. pageElementSel = pageElementSel[nextIndex < pageElementSel.length ? nextIndex : 0];
  4128. }
  4129. this.setSelectorDiv(pageElementSel);
  4130. }
  4131. }
  4132. const picker = new Picker();
  4133.  
  4134. var editor, editorChanged = false;
  4135. function createEdit() {
  4136. var options = {
  4137. mode: 'code',
  4138. modes: ['code', 'tree'],
  4139. templates: [
  4140. {
  4141. text: 'New site',
  4142. title: 'Insert a new site',
  4143. className: 'jsoneditor-type-object',
  4144. field: 'SiteTemplate',
  4145. value: {
  4146. 'name': 'Site name',
  4147. 'url': 'Site url'
  4148. }
  4149. }
  4150. ],
  4151. schema: {
  4152. "title": "Sites data",
  4153. "description": "Object containing site config",
  4154. "type": "array",
  4155. "items": {
  4156. "type": 'object',
  4157. "properties": {
  4158. "name": {
  4159. "title": "Site Name",
  4160. "description": "The site's name.",
  4161. "examples": [
  4162. "Google"
  4163. ],
  4164. "type": "string"
  4165. },
  4166. "url": {
  4167. "title": "Site Url",
  4168. "description": "The Regexp of site's url.",
  4169. "examples": [
  4170. "^https:\/\/yande\\.re\/"
  4171. ],
  4172. "type": "string"
  4173. }
  4174. },
  4175. "required": ["name", "url"]
  4176. }
  4177. },
  4178. onChange: () => {
  4179. editorChanged = true;
  4180. }
  4181. };
  4182. var container = document.getElementById("jsoneditor");
  4183. container.style.height = '800px';
  4184. container.innerHTML = "";
  4185. editor = new JSONEditor(container, options);
  4186. editor.set(ruleParser.customRules);
  4187. }
  4188.  
  4189. function checkGuidePage(href) {
  4190. if (guidePage.test(href)) {
  4191. if (typeof JSONEditor !== 'undefined') {
  4192. createEdit();
  4193. } else {
  4194. let checkEditorReady = setInterval(() => {
  4195. if (typeof JSONEditor !== 'undefined') {
  4196. createEdit();
  4197. clearInterval(checkEditorReady);
  4198. }
  4199. }, 100);
  4200. }
  4201. [].forEach.call(getBody(document).querySelectorAll('a'), ele => {
  4202. ele.target = "_blank";
  4203. });
  4204. return true;
  4205. }
  4206. return false;
  4207. }
  4208.  
  4209. function initConfig() {
  4210. listenUrl();
  4211. let href = location.href.slice(0, 100);
  4212. try {
  4213. if (_unsafeWindow.initedPagetual) {
  4214. if (ruleImportUrlReg.test(href)) {
  4215. showTips(i18n('duplicate'));
  4216. }
  4217. return true;
  4218. }
  4219. _unsafeWindow.initedPagetual = true;
  4220. } catch(e) {showTips(e)}
  4221. _GM_registerMenuCommand(i18n("update"), () => {
  4222. showTips(i18n("beginUpdate"), "", 60000);
  4223. updateRules(() => {
  4224. showTips(i18n("updateSucc"));
  4225. location.reload();
  4226. },(rule, err) => {
  4227. showTips(`Update ${rule.url} rules fail!`);
  4228. debug(err);
  4229. });
  4230. });
  4231. let isGuidePage = checkGuidePage(href);
  4232. if (!isGuidePage) {
  4233. if (href.indexOf("PagetualGuide") != -1) return true;
  4234. if (location.hostname === "pagetual.hoothin.com") return true;
  4235. }
  4236.  
  4237. var configCon, insertPos;
  4238. var noRules = !rulesData.urls || rulesData.urls.length === 0;
  4239.  
  4240. let inConfig = isGuidePage;
  4241. if (!inConfig) {
  4242. for (let i = 0; i < configPage.length; i++) {
  4243. if (configPage[i] == location.href) {
  4244. inConfig = true;
  4245. break;
  4246. }
  4247. }
  4248. }
  4249. if (ruleImportUrlReg.test(href) || inConfig) {
  4250. let importing = false;
  4251. if (noRules) {
  4252. setTimeout(() => {
  4253. if (!importing) showTips(i18n("firstAlert"));
  4254. }, 3000);
  4255. setTimeout(() => {
  4256. if (!importing) showTips(i18n("firstAlert"));
  4257. }, 6000);
  4258. showTips(i18n("firstAlert"));
  4259. }
  4260. let defaultOption = document.querySelector('#discussion_rating_4');
  4261. if (defaultOption) defaultOption.checked = true;
  4262. let createImportBtn = (pre) => {
  4263. let importBtn = document.createElement("button");
  4264. importBtn.id = "pagetualImport";
  4265. importBtn.innerText = i18n("import");
  4266. importBtn.style.marginTop = "100px";
  4267. importBtn.style.float = "right";
  4268. importBtn.style.position = "relative";
  4269. importBtn.style.display = "block";
  4270. importBtn.style.fontSize = "20px";
  4271. importBtn.addEventListener("click", e => {
  4272. let parentNode = importBtn.parentNode;
  4273. if (!parentNode) return;
  4274. parentNode.removeChild(importBtn);
  4275. try {
  4276. let rules = parentNode.innerText.trim();
  4277. let isContent = /['"]name['"]/i.test(rules);
  4278. if (isContent) {
  4279. let ruleList = JSON.parse(`[${rules}]`);
  4280. for (let i in ruleList) {
  4281. let hasRule = false;
  4282. let r = ruleList[i];
  4283. for (let j in ruleParser.customRules) {
  4284. if (ruleParser.customRules[j].name == r.name) {
  4285. ruleParser.customRules[j] = r;
  4286. hasRule = true;
  4287. break;
  4288. }
  4289. }
  4290. if (!hasRule) ruleParser.customRules.push(r);
  4291. ruleParser.hpRules.unshift(r);
  4292. }
  4293. storage.setItem("customRules", ruleParser.customRules);
  4294. storage.setItem("hpRules", ruleParser.hpRules);
  4295. storage.setItem("smartRules", []);
  4296. showTips(i18n("importSucc"));
  4297. } else {
  4298. rules = rules.split("\n");
  4299. let diff = false;
  4300. for (let c = 0; c < rules.length; c++) {
  4301. let urlArr = rules[c].split("|"), url, type = 1;
  4302. if (urlArr.length == 1) {
  4303. url = urlArr[0].trim();
  4304. if (!/^http/.test(url)) {
  4305. showTips(i18n("errorWrongUrl"));
  4306. return;
  4307. }
  4308. } else if (urlArr.length == 2) {
  4309. type = urlArr[0].trim();
  4310. url = urlArr[1].trim();
  4311. if (!/^http/.test(url)) {
  4312. showTips(i18n("errorWrongUrl"));
  4313. return;
  4314. }
  4315. } else {
  4316. break;
  4317. }
  4318. let maxId = 1, hasUrl = false;
  4319. if (!rulesData.urls) {
  4320. rulesData.urls = [];
  4321. maxId = 1;
  4322. } else {
  4323. rulesData.urls.forEach(u => {
  4324. if (maxId < u.id) {
  4325. maxId = u.id;
  4326. }
  4327. if (u.url == url) {
  4328. hasUrl = true;
  4329. }
  4330. });
  4331. if (hasUrl) break;
  4332. }
  4333. diff = true;
  4334. if (!rulesData.sort) rulesData.sort = [1];
  4335. rulesData.urls.push({id: maxId + 1, url: url, type: type});
  4336. rulesData.sort.unshift(maxId + 1);
  4337. }
  4338. if (!diff) {
  4339. showTips(i18n("errorAlreadyExists"));
  4340. return;
  4341. }
  4342. storage.setItem("rulesData", rulesData);
  4343.  
  4344. if (rulesData.urls) ruleUrls = ruleUrls.concat(rulesData.urls);
  4345. if (rulesData.sort) {
  4346. let urls = [];
  4347. rulesData.sort.forEach(id => {
  4348. for (let s = 0; s < ruleUrls.length; s++) {
  4349. if (id == ruleUrls[s].id) {
  4350. urls.push(ruleUrls[s]);
  4351. break;
  4352. }
  4353. }
  4354. });
  4355. ruleUrls = urls;
  4356. }
  4357. showTips(i18n("beginUpdate"), "", 30000);
  4358. updateRules(() => {
  4359. showTips(i18n("updateSucc"));
  4360. location.reload();
  4361. }, (rule, err) => {
  4362. showTips(`Update ${rule.url} rules fail!`);
  4363. debug(err);
  4364. });
  4365. importing = true;
  4366. }
  4367. } catch (e) {
  4368. _GM_notification(e.toString());
  4369. }
  4370. });
  4371. if (pre) {
  4372. let clientHeight = 35 - pre.clientHeight;
  4373. if (clientHeight > -20) clientHeight = -20;
  4374. importBtn.style.marginTop = `${clientHeight}px`;
  4375. pre.appendChild(importBtn);
  4376. }
  4377. return importBtn;
  4378. };
  4379. [].forEach.call(document.querySelectorAll('pre[name=pagetual],pre[name=user-content-pagetual]'), pre => {
  4380. let importBtn = createImportBtn(pre);
  4381. });
  4382. document.addEventListener("mouseover", e => {
  4383. if (/^PRE$/i.test(e.target.nodeName)) {
  4384. let nameAttr = e.target.getAttribute("name");
  4385. if (nameAttr == "pagetual" || nameAttr == "user-content-pagetual") {
  4386. if (e.target.querySelector('#pagetualImport')) return;
  4387. let importBtn = createImportBtn(e.target);
  4388. }
  4389. }
  4390. });
  4391.  
  4392. if (inConfig) {
  4393. if (_GM_info.script && _GM_info.script.version && _GM_info.script.version !== '1.0.0') {
  4394. let versionEle = document.querySelector('.markdown-body>h1[id],article>h1');
  4395. let latestVer = versionEle && versionEle.innerText.match(/\d[\d\.]+/)[0];
  4396. if (latestVer && latestVer != _GM_info.script.version) {
  4397. showTips(i18n('outOfDate'), "", 3000);
  4398. }
  4399. }
  4400. _GM_addStyle(`
  4401. p>span:nth-child(1),p>span:nth-child(2),p>span:nth-child(3){
  4402. cursor: pointer;
  4403. user-select: none;
  4404. display: inline-block;
  4405. margin-right: 5px;
  4406. -moz-transition:color 0.3s ease, transform 0.3s;
  4407. -webkit-transition:color 0.3s ease, transform 0.3s;
  4408. transition:color 0.3s ease, transform 0.3s;
  4409. }
  4410. p>span:nth-child(1):hover,p>span:nth-child(2):hover,p>span:nth-child(3):hover{
  4411. color:red;
  4412. transform: scale(1.5);
  4413. -webkit-transform: scale(1.5);
  4414. }
  4415. .updateDate{
  4416. cursor: pointer;
  4417. user-select: none;
  4418. -moz-transition:color 0.3s ease, transform 0.3s;
  4419. -webkit-transition:color 0.3s ease, transform 0.3s;
  4420. transition:color 0.3s ease, transform 0.3s;
  4421. transform-origin: left;
  4422. -webkit-transform-origin: left;
  4423. }
  4424. .updateDate:hover{
  4425. color:red;
  4426. transform: scale(1.1);
  4427. -webkit-transform: scale(1.1);
  4428. }
  4429. input[type=number]::-webkit-inner-spin-button,
  4430. input[type=number]::-webkit-outer-spin-button {
  4431. -webkit-appearance: none;
  4432. margin: 0;
  4433. }
  4434. input[type=number] {
  4435. -moz-appearance:textfield;
  4436. }
  4437. react-app>div>div>div>div>div>div>div[tabindex="0"]:not([data-selector]) {
  4438. display: none;
  4439. }
  4440. table td>h3 {
  4441. margin: 16px!important;
  4442. }
  4443. #saveBtn {
  4444. width: 100%;
  4445. position: fixed;
  4446. z-index: 999;
  4447. bottom: 0px;
  4448. left: 0px;
  4449. font-size: x-large;
  4450. opacity: 0.8;
  4451. cursor: pointer;
  4452. -moz-transition:opacity 0.3s ease;
  4453. -webkit-transition:opacity 0.3s ease;
  4454. transition:opacity 0.3s ease;
  4455. }
  4456. #saveBtn:hover {
  4457. opacity: 1;
  4458. }
  4459. `);
  4460. let click2import = document.querySelector("[name='user-content-click2import'],[name='click2import']");
  4461. if (click2import) click2import.innerText = i18n("click2ImportRule")
  4462. configCon = document.querySelector(".markdown-body,.theme-default-content");
  4463. insertPos = configCon.querySelector("hr,#jsoneditor");
  4464.  
  4465. if (!noRules) {
  4466. let importUrlPre = document.querySelector("pre[name='user-content-pagetual'],pre[name='pagetual']");
  4467. if (importUrlPre) importUrlPre.style.display = "none";
  4468. if (click2import) click2import.style.display = "none";
  4469. }
  4470. let otherconfig = document.querySelector("a[name='user-content-otherconfig'],a[name='otherconfig']");
  4471. if (otherconfig) otherconfig.parentNode.removeChild(otherconfig);
  4472. } else return true;
  4473. } else return false;
  4474. class Rulebar {
  4475. init(ruleUrl) {
  4476. this.ruleUrl = ruleUrl;
  4477. this.item = document.createElement("p");
  4478. this.item.dataset.id = this.ruleUrl.id;
  4479. let url = document.createElement("span");
  4480. url.innerHTML = ruleUrl.url;
  4481. let up = document.createElement("span");
  4482. up.innerHTML = "↑ ";
  4483. up.title = i18n("sortTitle");
  4484. let down = document.createElement("span");
  4485. down.innerHTML = "↓ ";
  4486. down.title = i18n("sortTitle");
  4487. let del = document.createElement("span");
  4488. del.innerHTML = "× ";
  4489. up.onclick = e => {
  4490. this.moveUp();
  4491. };
  4492. down.onclick = e => {
  4493. this.moveDown();
  4494. };
  4495. del.onclick = e => {
  4496. this.del();
  4497. };
  4498. this.item.appendChild(up);
  4499. this.item.appendChild(down);
  4500. this.item.appendChild(del);
  4501. this.item.appendChild(url);
  4502. configCon.insertBefore(this.item, insertPos);
  4503. }
  4504. saveSort() {
  4505. let sort = [];
  4506. [].forEach.call(this.item.parentNode.querySelectorAll("p[data-id]"), i => {
  4507. sort.push(i.dataset.id);
  4508. });
  4509. rulesData.sort = sort;
  4510. let urls = [];
  4511. sort.forEach(id => {
  4512. for (let s = 0; s < ruleUrls.length; s++) {
  4513. if (id == ruleUrls[s].id) {
  4514. urls.push(ruleUrls[s]);
  4515. break;
  4516. }
  4517. }
  4518. });
  4519. ruleUrls = urls;
  4520. storage.setItem("rulesData", rulesData);
  4521. }
  4522. moveUp() {
  4523. let preE = this.item.previousElementSibling;
  4524. if (/^P$/i.test(preE.nodeName) && preE.children.length > 1) {
  4525. this.item.parentNode.insertBefore(this.item, preE);
  4526. this.saveSort();
  4527. }
  4528. }
  4529. moveDown() {
  4530. let nextE = this.item.nextElementSibling;
  4531. if (/^P$/i.test(nextE.nodeName) && nextE.children.length > 1) {
  4532. this.item.parentNode.insertBefore(nextE, this.item);
  4533. this.saveSort();
  4534. }
  4535. }
  4536. del() {
  4537. if (this.ruleUrl.id < 2) {
  4538. showTips(i18n("cantDel"));
  4539. } else if (window.confirm(i18n("confirmDel"))) {
  4540. for (let u = 0; u < rulesData.urls.length; u++) {
  4541. if (this.ruleUrl.id == rulesData.urls[u].id) {
  4542. rulesData.urls.splice(u, 1);
  4543. break;
  4544. }
  4545. }
  4546. for (let u = 0; u < ruleUrls.length; u++) {
  4547. if (this.ruleUrl.id == ruleUrls[u].id) {
  4548. ruleUrls.splice(u, 1);
  4549. break;
  4550. }
  4551. }
  4552. for (let u = 0; u < rulesData.sort.length; u++) {
  4553. if (this.ruleUrl.id == rulesData.sort[u]) {
  4554. rulesData.sort.splice(u, 1);
  4555. break;
  4556. }
  4557. }
  4558. storage.setItem("rulesData", rulesData);
  4559. ruleParser.rules = ruleParser.rules.filter(item => {return item.from != this.ruleUrl.id});
  4560. storage.setItem("rules", ruleParser.rules);
  4561. this.item.parentNode.removeChild(this.item);
  4562. //location.reload();
  4563. }
  4564. }
  4565. }
  4566. let updateP = document.createElement("p"), i = 0;
  4567. let now = new Date().getTime(), inUpdate = false;
  4568.  
  4569.  
  4570. let pastDate = (new Date(updateDate)).toString(), passStr;
  4571. let passTime = (now - updateDate) / 1000;
  4572. if (isNaN(passTime)) {
  4573. passStr = i18n("firstUpdate");
  4574. } else {
  4575. if (passTime < 60) {
  4576. passStr = i18n("passSec", parseInt(passTime));
  4577. } else if (passTime < 60 * 60) {
  4578. passStr = i18n("passMin", parseInt(passTime / 60));
  4579. } else if (passTime < 60 * 60 * 24) {
  4580. passStr = i18n("passHour", parseInt(passTime / 3600));
  4581. } else {
  4582. passStr = i18n("passDay", parseInt(passTime / 86400));
  4583. }
  4584. passStr += " 👆 " + i18n("click2update");
  4585. }
  4586.  
  4587.  
  4588. updateP.className = "updateDate";
  4589. updateP.innerHTML = passStr;
  4590. updateP.title = i18n("update") + " - " + pastDate;
  4591. updateP.onclick = e => {
  4592. ruleParser.rules = [];
  4593. showTips(i18n("beginUpdate"), "", 30000);
  4594. updateRules(() => {
  4595. showTips(i18n("updateSucc"));
  4596. updateP.innerHTML = i18n("passSec", 0);
  4597. updateP.title = i18n("update");
  4598. }, (rule, err) => {
  4599. showTips(`Update ${rule.url} rules fail!`);
  4600. debug(err);
  4601. });
  4602. };
  4603. configCon.insertBefore(updateP, insertPos);
  4604. if (ruleUrls) {
  4605. ruleUrls.forEach(ruleUrl => {
  4606. var rulebar = new Rulebar();
  4607. rulebar.init(ruleUrl);
  4608. });
  4609. }
  4610. let customUrlsTitle = document.createElement("h2");
  4611. customUrlsTitle.innerHTML = i18n("customUrls");
  4612. configCon.insertBefore(customUrlsTitle, insertPos);
  4613. let customUrlsInput = document.createElement("textarea");
  4614. customUrlsInput.style.width = "100%";
  4615. customUrlsInput.placeholder = "http://wedata.net/databases/AutoPagerize/items_all.json \nhttps://hoothin.github.io/UserScripts/Pagetual/pagetualRules.json";
  4616. customUrlsInput.spellcheck = false;
  4617. configCon.insertBefore(customUrlsInput, insertPos);
  4618.  
  4619. let btns = document.createElement("div");
  4620. btns.style.display = "flex";
  4621. configCon.insertBefore(btns, insertPos);
  4622. let upBtnImg = document.createElement("div");
  4623. upBtnImg.style.width = "33%";
  4624. let upBtnImgTitle = document.createElement("h2");
  4625. upBtnImgTitle.style.whiteSpace = "nowrap";
  4626. upBtnImgTitle.style.overflow = "auto";
  4627. upBtnImgTitle.innerHTML = i18n("upBtnImg");
  4628. upBtnImg.appendChild(upBtnImgTitle);
  4629. let upBtnImgInput = document.createElement("input");
  4630. upBtnImgInput.style.width = "100%";
  4631. upBtnImgInput.placeholder = "data:image/png;base64,UpBtn";
  4632. upBtnImgInput.value = rulesData.upBtnImg || '';
  4633. upBtnImgInput.spellcheck = false;
  4634. upBtnImg.appendChild(upBtnImgInput);
  4635. btns.appendChild(upBtnImg);
  4636.  
  4637. let downBtnImg = document.createElement("div");
  4638. downBtnImg.style.width = "33%";
  4639. let downBtnImgTitle = document.createElement("h2");
  4640. downBtnImgTitle.style.whiteSpace = "nowrap";
  4641. downBtnImgTitle.style.overflow = "auto";
  4642. downBtnImgTitle.innerHTML = i18n("downBtnImg");
  4643. downBtnImg.appendChild(downBtnImgTitle);
  4644. let downBtnImgInput = document.createElement("input");
  4645. downBtnImgInput.style.width = "100%";
  4646. downBtnImgInput.placeholder = "data:image/png;base64,DownBtn";
  4647. downBtnImgInput.value = rulesData.downBtnImg || '';
  4648. downBtnImgInput.spellcheck = false;
  4649. downBtnImg.appendChild(downBtnImgInput);
  4650. btns.appendChild(downBtnImg);
  4651.  
  4652. let sideControllerIconDiv = document.createElement("div");
  4653. sideControllerIconDiv.style.width = "33%";
  4654. let sideControllerIconTitle = document.createElement("h2");
  4655. sideControllerIconTitle.style.whiteSpace = "nowrap";
  4656. sideControllerIconTitle.style.overflow = "auto";
  4657. sideControllerIconTitle.innerHTML = i18n("sideControllerIcon");
  4658. sideControllerIconDiv.appendChild(sideControllerIconTitle);
  4659. let sideControllerIconInput = document.createElement("input");
  4660. sideControllerIconInput.style.width = "100%";
  4661. sideControllerIconInput.placeholder = "🤍";
  4662. sideControllerIconInput.value = rulesData.sideControllerIcon || '';
  4663. sideControllerIconInput.spellcheck = false;
  4664. sideControllerIconDiv.appendChild(sideControllerIconInput);
  4665. btns.appendChild(sideControllerIconDiv);
  4666.  
  4667. let otherBtns = document.createElement("div");
  4668. otherBtns.style.display = "flex";
  4669. configCon.insertBefore(otherBtns, insertPos);
  4670. let loadingText = document.createElement("div");
  4671. loadingText.style.width = "100%";
  4672. let loadingTextTitle = document.createElement("h2");
  4673. loadingTextTitle.style.whiteSpace = "nowrap";
  4674. loadingTextTitle.style.overflow = "auto";
  4675. loadingTextTitle.innerHTML = i18n("loadingTextTitle");
  4676. loadingText.appendChild(loadingTextTitle);
  4677. let loadingTextInput = document.createElement("input");
  4678. loadingTextInput.value = rulesData.loadingText||'';
  4679. loadingTextInput.placeholder = i18n("loadingText");
  4680. loadingTextInput.style.width = "100%";
  4681. loadingTextInput.style.margin = "0";
  4682. loadingTextInput.spellcheck = false;
  4683. loadingText.appendChild(loadingTextInput);
  4684. otherBtns.appendChild(loadingText);
  4685.  
  4686. let opacity = document.createElement("div");
  4687. let opacityTitle = document.createElement("h2");
  4688. opacityTitle.style.whiteSpace = "nowrap";
  4689. opacityTitle.style.overflow = "visible";
  4690. opacityTitle.innerHTML = i18n("opacity");
  4691. opacity.appendChild(opacityTitle);
  4692. let opacityInput = document.createElement("input");
  4693. opacityInput.value = rulesData.opacity * 100;
  4694. opacityInput.type = "number";
  4695. opacityInput.min = 0;
  4696. opacityInput.max = 100;
  4697. opacityInput.style.width = "110px";
  4698. opacityInput.style.margin = "0";
  4699. opacityInput.placeholder = i18n("opacityPlaceholder");
  4700. opacityInput.spellcheck = false;
  4701. opacityInput.oninput = e => {
  4702. if (opacityInput.value > 100) opacityInput.value = 100;
  4703. else if (opacityInput.value < 0) opacityInput.value = 0;
  4704. };
  4705. opacity.appendChild(opacityInput);
  4706. otherBtns.appendChild(opacity);
  4707.  
  4708. let pageElementCss = document.createElement("div");
  4709. pageElementCss.style.marginBottom = "30px";
  4710. let pageElementCssTitle = document.createElement("h2");
  4711. pageElementCssTitle.innerHTML = i18n("pageElementCss");
  4712. pageElementCss.appendChild(pageElementCssTitle);
  4713. let pageElementCssInput = document.createElement("input");
  4714. pageElementCssInput.value = rulesData.pageElementCss || '';
  4715. pageElementCssInput.style.width = "100%";
  4716. pageElementCssInput.style.margin = "0";
  4717. pageElementCssInput.placeholder = "font-size: xx-large;";
  4718. pageElementCssInput.spellcheck = false;
  4719. pageElementCss.appendChild(pageElementCssInput);
  4720. configCon.insertBefore(pageElementCss, insertPos);
  4721.  
  4722. let customCss = document.createElement("div");
  4723. customCss.style.marginBottom = "50px";
  4724. let customCssTitle = document.createElement("h2");
  4725. customCssTitle.innerHTML = i18n("customCss");
  4726. customCss.appendChild(customCssTitle);
  4727. let customCssInput = document.createElement("textarea");
  4728. customCssInput.value = rulesData.customCss || '';
  4729. customCssInput.style.width = "100%";
  4730. customCssInput.style.margin = "0";
  4731. customCssInput.placeholder = ".pagetual{\n}";
  4732. customCssInput.spellcheck = false;
  4733. customCss.appendChild(customCssInput);
  4734. configCon.insertBefore(customCss, insertPos);
  4735.  
  4736. let configTable = document.createElement("table");
  4737. configTable.style.width = "100%";
  4738. let configTbody = document.createElement("tbody");
  4739. configTbody.style.width = "99%";
  4740. configTbody.style.display = "inline-table";
  4741. configTable.appendChild(configTbody);
  4742. configCon.insertBefore(configTable, insertPos);
  4743. function createCheckbox(innerText, val, tag, parentCheck, otherType) {
  4744. if (typeof val == 'undefined') val = "";
  4745. let title = document.createElement(tag || "h3");
  4746. title.innerHTML = innerText;
  4747. title.style.overflowWrap = "normal";
  4748. let input = document.createElement("input");
  4749. if (otherType === 'key') {
  4750. input.type = 'text';
  4751. input.setAttribute('readOnly', 'readonly');
  4752. input.addEventListener("keydown", e => {
  4753. if (e.key === 'Escape' || e.key === 'Backspace') input.value = '';
  4754. else input.value = e.key;
  4755. e.stopPropagation();
  4756. e.preventDefault();
  4757. });
  4758. } else {
  4759. input.type = otherType || "checkbox";
  4760. }
  4761. input.style.width = "30px";
  4762. input.style.height = "20px";
  4763. input.style.float = "left";
  4764. input.style.margin = "5px";
  4765. input.value = val;
  4766. input.checked = val;
  4767. let td = document.createElement("td");
  4768. td.appendChild(input);
  4769. if (parentCheck) {
  4770. title.style.margin = "0";
  4771. td.appendChild(title);
  4772. let parent = parentCheck.parentNode.nextElementSibling;
  4773. let tr = parent.querySelector("tr");
  4774. if (!tr) {
  4775. tr = document.createElement("tr");
  4776. parent.appendChild(tr);
  4777. }
  4778. tr.appendChild(td);
  4779. if (!parentCheck.checked) {
  4780. td.style.display = "none";
  4781. }
  4782. parentCheck.addEventListener("click", e => {
  4783. td.style.display = parentCheck.checked ? "" : "none";
  4784. });
  4785. } else {
  4786. let tr = document.createElement("tr");
  4787. tr.appendChild(td);
  4788. td = document.createElement("td");
  4789. td.appendChild(title);
  4790. tr.appendChild(td);
  4791. configTable.children[0].appendChild(tr);
  4792. }
  4793. let xNodePos = innerText.indexOf('【X】');
  4794. if (xNodePos !== -1) {
  4795. input.style.float = "";
  4796. let xNode = title.firstChild.splitText(xNodePos);
  4797. xNode.splitText(3);
  4798. xNode.parentNode.replaceChild(input, xNode);
  4799. }
  4800. return input;
  4801. }
  4802.  
  4803. let setConfigPageInput = createCheckbox(i18n("setConfigPage"), false);
  4804. let enableWhiteListInput = createCheckbox(i18n("autoRun"), rulesData.enableWhiteList != true);
  4805. let sideControllerInput = createCheckbox(i18n("sideController"), rulesData.sideController);
  4806. let enableDebugInput = createCheckbox(i18n("enableDebug"), rulesData.enableDebug != false);
  4807. let enableHistoryInput = createCheckbox(i18n("enableHistory"), rulesData.enableHistory === true);
  4808. let enableHistoryAfterInsertInput = createCheckbox(i18n("enableHistoryAfterInsert"), rulesData.enableHistoryAfterInsert === true);
  4809. let openInNewTabInput = createCheckbox(i18n("openInNewTab"), rulesData.openInNewTab != false);
  4810. let hidePageBarInput = createCheckbox(i18n("hideBarTips"), rulesData.opacity == 0);
  4811. let hidePageBarArrowInput = createCheckbox(i18n("hideBarArrow"), rulesData.hideBarArrow);
  4812. let hideLoadingIconInput = createCheckbox(i18n("hideLoadingIcon"), rulesData.hideLoadingIcon != false);
  4813. let initRunInput = createCheckbox(i18n("initRun"), rulesData.initRun != false);
  4814. let autoLoadNumInput = createCheckbox(i18n("autoLoadNum"), rulesData.autoLoadNum, "h4", initRunInput, "number");
  4815. let preloadInput = createCheckbox(i18n("preload"), rulesData.preload != false);
  4816. let rateInput = createCheckbox(i18n("turnRate"), rulesData.rate, "h4", preloadInput, "number");
  4817. let dbClick2StopInput = createCheckbox(i18n("dbClick2Stop"), rulesData.dbClick2Stop);
  4818. let manualModeInput = createCheckbox(i18n("manualMode"), rulesData.manualMode);
  4819. let clickModeInput = createCheckbox(i18n("clickMode"), rulesData.clickMode);
  4820. let pageBarMenuInput = createCheckbox(i18n("pageBarMenu"), rulesData.pageBarMenu != false);
  4821. let arrowToScrollInput = createCheckbox(i18n("arrowToScroll"), rulesData.arrowToScroll);
  4822. let contentVisibilityInput = createCheckbox(i18n("contentVisibility"), rulesData.contentVisibility);
  4823. let wedata2githubInput = createCheckbox(i18n("wedata2github"), rulesData.wedata2github);
  4824.  
  4825. let hideBarInput = createCheckbox(i18n("hideBar"), rulesData.hideBar && !rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  4826. hideBarInput.name = 'hideBar';
  4827. let hideBarButNoStopInput = createCheckbox(i18n("hideBarButNoStop"), rulesData.hideBarButNoStop, "h4", dbClick2StopInput, 'radio');
  4828. hideBarButNoStopInput.name = 'hideBar';
  4829. hideBarInput.addEventListener('mouseup', e => {
  4830. if (hideBarInput.checked) {
  4831. setTimeout(() => {hideBarInput.checked = false}, 0);
  4832. }
  4833. });
  4834. hideBarButNoStopInput.addEventListener('mouseup', e => {
  4835. if (hideBarButNoStopInput.checked) {
  4836. setTimeout(() => {hideBarButNoStopInput.checked = false}, 0);
  4837. }
  4838. });
  4839. hidePageBarInput.addEventListener('click', e => {
  4840. opacityInput.value = hidePageBarInput.checked ? 0 : 100;
  4841. });
  4842.  
  4843. let dbClick2StopCtrlInput = createCheckbox(i18n("dbClick2StopCtrl"), rulesData.dbClick2StopCtrl, "h4", dbClick2StopInput);
  4844. let dbClick2StopAltInput = createCheckbox(i18n("dbClick2StopAlt"), rulesData.dbClick2StopAlt, "h4", dbClick2StopInput);
  4845. let dbClick2StopShiftInput = createCheckbox(i18n("dbClick2StopShift"), rulesData.dbClick2StopShift, "h4", dbClick2StopInput);
  4846. let dbClick2StopMetaInput = createCheckbox(i18n("dbClick2StopMeta"), rulesData.dbClick2StopMeta, "h4", dbClick2StopInput);
  4847. let dbClick2StopKeyInput = createCheckbox(i18n("dbClick2StopKey"), rulesData.dbClick2StopKey, "h4", dbClick2StopInput, "key");
  4848.  
  4849. let otherConfigPage = rulesData.configPage ? rulesData.configPage != location.href : configPage[0] != location.href;
  4850. if (!otherConfigPage) {
  4851. setConfigPageInput.parentNode.parentNode.style.display = "none";
  4852. }
  4853. let customRulesTitle = document.createElement("h2");
  4854. 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');
  4855. configCon.insertBefore(customRulesTitle, insertPos);
  4856. let customRulesInput = document.createElement("textarea");
  4857. customRulesInput.spellcheck = false;
  4858. configCon.insertBefore(customRulesInput, insertPos);
  4859. if (rulesData.editTemp) {
  4860. if (!ruleParser.customRules) {
  4861. ruleParser.customRules = [];
  4862. }
  4863. for (let i in ruleParser.customRules) {
  4864. if (ruleParser.customRules[i].url == rulesData.editTemp.url) {
  4865. ruleParser.customRules.splice(i, 1);
  4866. break;
  4867. }
  4868. }
  4869. ruleParser.customRules.unshift(rulesData.editTemp);
  4870. rulesData.editTemp = null;
  4871. storage.setItem("rulesData", rulesData);
  4872. customRulesInput.previousElementSibling.scrollIntoView();
  4873. }
  4874. customRulesInput.style.width = "100%";
  4875. customRulesInput.style.height = "800px";
  4876. 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]`;
  4877. let preCustom = getFormatJSON(ruleParser.customRules);
  4878. customRulesInput.value = preCustom;
  4879. if (isGuidePage) customRulesInput.style.display = "none";
  4880. let blacklistInput = document.createElement("textarea");
  4881. blacklistInput.style.width = "100%";
  4882. blacklistInput.style.height = "500px";
  4883. blacklistInput.style.display = "none";
  4884. blacklistInput.spellcheck = false;
  4885. blacklistInput.placeholder = "http://*.xxx.com/*/y\n/^https?://.*\\.xxx\\.com/i";
  4886. blacklistInput.value = rulesData.blacklist ? rulesData.blacklist.join("\n") : "";
  4887. let blacklistBtn = document.createElement("button");
  4888. blacklistBtn.innerText = i18n("editBlacklist");
  4889. blacklistBtn.style.width = "100%";
  4890. blacklistBtn.onclick = e => {
  4891. blacklistInput.style.display = blacklistInput.style.display == "none" ? "" : "none";
  4892. };
  4893. configCon.insertBefore(blacklistBtn, insertPos);
  4894. configCon.insertBefore(blacklistInput, insertPos);
  4895. let saveBtn = document.createElement("button");
  4896. saveBtn.innerHTML = i18n("save");
  4897. saveBtn.id = "saveBtn";
  4898. configCon.insertBefore(saveBtn, insertPos);
  4899. saveBtn.onclick = e => {
  4900. try {
  4901. let customRules;
  4902. if (editor) {
  4903. if (editorChanged) {
  4904. editorChanged = false;
  4905. storage.setItem("hpRules", []);
  4906. storage.setItem("smartRules", []);
  4907. }
  4908. customRules = editor.get();
  4909. if (!customRules) {
  4910. customRules = "";
  4911. } else {
  4912. if (Array && Array.isArray && !Array.isArray(customRules)) {
  4913. showTips(i18n("errorRulesMustBeArray"));
  4914. return;
  4915. }
  4916. }
  4917. } else {
  4918. if (customRulesInput.value != preCustom) {
  4919. storage.setItem("hpRules", []);
  4920. storage.setItem("smartRules", []);
  4921. }
  4922. if (customRulesInput.value == "") {
  4923. customRules = "";
  4924. } else {
  4925. customRules = JSON.parse(customRulesInput.value);
  4926. if (Array && Array.isArray && !Array.isArray(customRules)) {
  4927. showTips(i18n("errorRulesMustBeArray"));
  4928. return;
  4929. }
  4930. customRulesInput.value = JSON.stringify(customRules, null, 4);
  4931. }
  4932. }
  4933. debug(customRules);
  4934. storage.setItem("customRules", customRules);
  4935. } catch(e) {
  4936. debug(e);
  4937. showTips(i18n("errorJson"));
  4938. return;
  4939. }
  4940. if (setConfigPageInput.checked) rulesData.configPage = location.href;
  4941. rulesData.wedata2github = wedata2githubInput.checked;
  4942. let opacity = parseInt(opacityInput.value) || 0;
  4943. if (opacity > 100) opacity = 100;
  4944. else if (opacity < 0) opacity = 0;
  4945. rulesData.opacity = opacity / 100;
  4946. rulesData.blacklist = blacklistInput.value ? blacklistInput.value.trim().split("\n") : "";
  4947. rulesData.hideBar = hideBarInput.checked;
  4948. rulesData.hideBarButNoStop = hideBarButNoStopInput.checked;
  4949. rulesData.dbClick2Stop = dbClick2StopInput.checked;
  4950. rulesData.enableWhiteList = !enableWhiteListInput.checked;
  4951. rulesData.enableDebug = enableDebugInput.checked;
  4952. rulesData.enableHistory = enableHistoryInput.checked;
  4953. rulesData.enableHistoryAfterInsert = enableHistoryAfterInsertInput.checked;
  4954. rulesData.openInNewTab = openInNewTabInput.checked;
  4955. rulesData.hideLoadingIcon = hideLoadingIconInput.checked;
  4956. rulesData.hideBarArrow = hidePageBarArrowInput.checked;
  4957. rulesData.initRun = initRunInput.checked;
  4958. rulesData.autoLoadNum = autoLoadNumInput.value !== "0" ? autoLoadNumInput.value : '';
  4959. rulesData.rate = parseInt(rateInput.value) || 1;
  4960. rulesData.preload = preloadInput.checked;
  4961. rulesData.manualMode = manualModeInput.checked;
  4962. rulesData.clickMode = clickModeInput.checked;
  4963. rulesData.pageBarMenu = pageBarMenuInput.checked;
  4964. rulesData.arrowToScroll = arrowToScrollInput.checked;
  4965. rulesData.contentVisibility = contentVisibilityInput.checked;
  4966. if (rulesData.sideController != sideControllerInput.checked) {
  4967. rulesData.sideControllerPos = false;
  4968. }
  4969. rulesData.sideController = sideControllerInput.checked;
  4970. rulesData.pageElementCss = pageElementCssInput.value;
  4971. rulesData.customCss = customCssInput.value;
  4972. rulesData.upBtnImg = upBtnImgInput.value;
  4973. rulesData.downBtnImg = downBtnImgInput.value;
  4974. rulesData.sideControllerIcon = sideControllerIconInput.value;
  4975. rulesData.loadingText = loadingTextInput.value;
  4976. rulesData.dbClick2StopCtrl = dbClick2StopCtrlInput.checked;
  4977. rulesData.dbClick2StopAlt = dbClick2StopAltInput.checked;
  4978. rulesData.dbClick2StopShift = dbClick2StopShiftInput.checked;
  4979. rulesData.dbClick2StopMeta = dbClick2StopMetaInput.checked;
  4980. rulesData.dbClick2StopKey = dbClick2StopKeyInput.value;
  4981. storage.setItem("rulesData", rulesData);
  4982. let customUrls = customUrlsInput.value.trim();
  4983. if (customUrls) {
  4984. customUrls = customUrls.split(/\n/);
  4985. for (let c = 0; c < customUrls.length; c++) {
  4986. let url;
  4987. if (/^0\s*\|/.test(customUrls[c])) {
  4988. url = customUrls[c].replace(/^0\s*\|\s*/, "").trim();
  4989. if (!/^http/.test(url)) {
  4990. showTips(i18n("errorWrongUrl"));
  4991. return;
  4992. }
  4993. } else {
  4994. url = customUrls[c].trim();
  4995. if (!/^http/.test(url)) {
  4996. showTips(i18n("errorWrongUrl"));
  4997. return;
  4998. }
  4999. }
  5000. let maxId = 1, hasUrl = false;
  5001. if (!rulesData.urls) {
  5002. rulesData.urls = [];
  5003. }
  5004. ruleUrls.forEach(u => {
  5005. if (maxId < u.id) {
  5006. maxId = u.id;
  5007. }
  5008. if (u.url == url) {
  5009. hasUrl = true;
  5010. }
  5011. });
  5012. if (hasUrl) break;
  5013. if (!rulesData.sort) rulesData.sort = [1];
  5014. rulesData.urls.push({id: maxId + 1, url: url});
  5015. rulesData.sort.push(maxId + 1);
  5016. storage.setItem("rulesData", rulesData);
  5017. }
  5018. }
  5019. showTips(i18n("settingsSaved"));
  5020. };
  5021. return true;
  5022. }
  5023.  
  5024. var inUpdate = false;
  5025. function updateRules (success, fail, keepCache) {
  5026. if (!storage.supportCrossSave()) {
  5027. fail({url:''}, "Not support cross storage");
  5028. showTips("Current platform do not support cross storage!");
  5029. return;
  5030. }
  5031. if (inUpdate) return;
  5032. inUpdate = true;
  5033. let ruleIndex = ruleUrls.length - 1;
  5034. if (!keepCache) {
  5035. storage.setItem("hpRules", []);
  5036. storage.setItem("smartRules", []);
  5037. }
  5038. function addNextRule() {
  5039. if (ruleIndex < 0) {
  5040. let now = new Date().getTime();
  5041. storage.setItem("ruleLastUpdate", now);
  5042. storage.setItem("rules", ruleParser.rules);
  5043. inUpdate = false;
  5044. success();
  5045. } else {
  5046. let rule = ruleUrls[ruleIndex--];
  5047. ruleParser.addRuleByUrl(rule.url, rule.id, (json, err) => {
  5048. if (!json) {
  5049. fail(rule, err);
  5050. }
  5051. addNextRule();
  5052. })
  5053. }
  5054. }
  5055. addNextRule();
  5056. }
  5057.  
  5058. function objIsArr(obj) {
  5059. return obj &&
  5060. typeof obj === 'object' &&
  5061. typeof obj.length === 'number' &&
  5062. !(obj.propertyIsEnumerable('length'));
  5063. }
  5064.  
  5065. function isVisible(el, win) {
  5066. if(!el || !el.offsetParent)return false;
  5067. var loopable = true,
  5068. visible = el.nodeName && win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  5069. while(loopable && visible) {
  5070. el = el.parentNode;
  5071.  
  5072. if(el && !/^BODY$/i.test(el.nodeName)) {
  5073. visible = win.getComputedStyle(el).display != 'none' && win.getComputedStyle(el).visibility != 'hidden';
  5074. }else {
  5075. loopable = false;
  5076. }
  5077. }
  5078. return visible;
  5079. }
  5080.  
  5081. function getElementTop(ele) {
  5082. if (!ele) return 0;
  5083. if (ele.getBoundingClientRect) {
  5084. return ele.getBoundingClientRect().top + document.documentElement.scrollTop;
  5085. }
  5086. var actualTop = ele.offsetTop;
  5087. var current = ele.offsetParent;
  5088. while (current) {
  5089. actualTop += current.offsetTop;
  5090. current = current.offsetParent;
  5091. }
  5092. return actualTop;
  5093. }
  5094.  
  5095. function getElementLeft(ele) {
  5096. if (!ele) return 0;
  5097. if (ele.getBoundingClientRect) {
  5098. return ele.getBoundingClientRect().left + document.documentElement.scrollLeft;
  5099. }
  5100. var actualLeft = ele.offsetLeft;
  5101. var current = ele.offsetParent;
  5102. while (current) {
  5103. actualLeft += current.offsetLeft;
  5104. current = current.offsetParent;
  5105. }
  5106. return actualLeft;
  5107. }
  5108.  
  5109. function getElementBottom(ele) {
  5110. return getElementTop(ele) + (ele.offsetHeight || ele.scrollHeight);
  5111. }
  5112.  
  5113. function getFormatJSON(obj){
  5114. if(!objIsArr(obj) || obj.length === 0)return "";
  5115. return JSON.stringify(obj, null, 4);
  5116. }
  5117.  
  5118. function globMatch(first, second) {
  5119. if (first === '*') {
  5120. return true;
  5121. }
  5122. if (first.length == 0 && second.length == 0){
  5123. return true;
  5124. }
  5125.  
  5126. if (first.length > 1 && first[0] == '*' &&
  5127. second.length == 0){
  5128. return false;
  5129. }
  5130.  
  5131. if ((first.length > 1 && first[0] == '?') ||
  5132. (first.length != 0 && second.length != 0 &&
  5133. first[0] == second[0])){
  5134. return globMatch(first.substring(1),
  5135. second.substring(1));
  5136. }
  5137.  
  5138. if (first.length > 0 && first[0] == '*'){
  5139. return globMatch(first.substring(1), second) ||
  5140. globMatch(first, second.substring(1));
  5141. }
  5142.  
  5143. return false;
  5144. }
  5145.  
  5146. let pageReady = false;
  5147. function initRules(callback) {
  5148. storage.getItem("rulesData", data => {
  5149. /*0 wedata格式,1 pagetual格式*/
  5150. ruleUrls = [{
  5151. id: 1,
  5152. url: data && data.wedata2github ? 'https://hoothin.github.io/UserScripts/Pagetual/items_all.json' : 'http://wedata.net/databases/AutoPagerize/items_all.json',
  5153. type: 0,
  5154. }];
  5155. if (data) {
  5156. rulesData = data;
  5157. if (data.urls) ruleUrls = ruleUrls.concat(data.urls);
  5158. if (data.sort) {
  5159. let urls = [];
  5160. data.sort.forEach(id => {
  5161. for (let s = 0; s < ruleUrls.length; s++) {
  5162. if (id == ruleUrls[s].id) {
  5163. urls.push(ruleUrls[s]);
  5164. break;
  5165. }
  5166. }
  5167. });
  5168. ruleUrls = urls;
  5169. }
  5170. }
  5171. if (rulesData.blacklist && rulesData.blacklist.length > 0) {
  5172. let href = location.href.slice(0, 500);
  5173. for (let i = 0; i < rulesData.blacklist.length; i++) {
  5174. let curGlob = rulesData.blacklist[i];
  5175. if (!curGlob) continue;
  5176. if (curGlob.indexOf("/") == 0) {
  5177. let regMatch = curGlob.match(/^\/(.*)\/(\w*)$/);
  5178. if (regMatch && new RegExp(regMatch[1], regMatch[2]).test(href)) {
  5179. forceState == 1;
  5180. return;
  5181. }
  5182. } else if (globMatch(curGlob, href)) {
  5183. forceState == 1;
  5184. return;
  5185. }
  5186. }
  5187. }
  5188. ruleParser.initSavedRules(() => {
  5189. let upBtnImg = rulesData.upBtnImg, downBtnImg = rulesData.downBtnImg, _sideControllerIcon = rulesData.sideControllerIcon;
  5190. if (upBtnImg && downBtnImg) {
  5191. downSvgCSS = downSvgCSS.replace("transform: rotate(180deg);", "");
  5192. } else if (upBtnImg && !downBtnImg) {
  5193. downBtnImg = upBtnImg;
  5194. } else if(downBtnImg && !upBtnImg) {
  5195. upBtnImg = downBtnImg;
  5196. }
  5197. if (upBtnImg) {
  5198. upSvg = /https?:|data/.test(upBtnImg) ? `<img class="pagetual" src="${upBtnImg}"/>` : `<span>${upBtnImg}</span>`;
  5199. }
  5200. if (downBtnImg) {
  5201. downSvg = /https?:|data/.test(downBtnImg) ? `<img class="pagetual" src="${downBtnImg}"/>` : `<span>${downBtnImg}</span>`;
  5202. }
  5203. if (_sideControllerIcon) {
  5204. sideControllerIcon = /https?:|data/.test(_sideControllerIcon) ? `<img class="pagetual" src="${_sideControllerIcon}"/>` : `<span>${_sideControllerIcon}</span>`;
  5205. }
  5206. setLoadingDiv(rulesData.loadingText || i18n("loadingText"));
  5207. if (typeof(rulesData.opacity) == "undefined") {
  5208. rulesData.opacity = 1;
  5209. }
  5210. if (typeof(rulesData.hideBar) == "undefined") {
  5211. rulesData.hideBar = false;
  5212. }
  5213. if (typeof(rulesData.dbClick2Stop) == "undefined") {
  5214. rulesData.dbClick2Stop = true;
  5215. }
  5216. if (typeof(rulesData.enableWhiteList) == "undefined") {
  5217. rulesData.enableWhiteList = false;
  5218. }
  5219. if (typeof(rulesData.enableHistory) == "undefined") {
  5220. rulesData.enableHistory = false;
  5221. }
  5222. if (typeof(rulesData.openInNewTab) == "undefined") {
  5223. rulesData.openInNewTab = false;
  5224. }
  5225. if (typeof(rulesData.enableDebug) == "undefined") {
  5226. rulesData.enableDebug = true;
  5227. }
  5228. if (typeof(rulesData.initRun) == "undefined") {
  5229. rulesData.initRun = true;
  5230. }
  5231. if (typeof(rulesData.preload) == "undefined") {
  5232. rulesData.preload = true;
  5233. }
  5234. if (typeof(rulesData.manualMode) == "undefined") {
  5235. rulesData.manualMode = false;
  5236. }
  5237. if (typeof(rulesData.clickMode) == "undefined") {
  5238. rulesData.clickMode = false;
  5239. }
  5240. if (typeof(rulesData.pageBarMenu) == "undefined") {
  5241. rulesData.pageBarMenu = true;
  5242. }
  5243. if (typeof(rulesData.arrowToScroll) == "undefined") {
  5244. rulesData.arrowToScroll = false;
  5245. }
  5246. if (typeof(rulesData.hideLoadingIcon) == "undefined") {
  5247. rulesData.hideLoadingIcon = false;
  5248. }
  5249. if (typeof(rulesData.hideBarArrow) == "undefined") {
  5250. rulesData.hideBarArrow = false;
  5251. }
  5252. if (rulesData.autoLoadNum && rulesData.initRun) {
  5253. autoLoadNum = parseInt(rulesData.autoLoadNum);
  5254. }
  5255. openInNewTab = rulesData.openInNewTab ? 1 : 0;
  5256. enableDebug = rulesData.enableDebug;
  5257. storage.getItem("nextSwitch_" + location.host, i => {
  5258. storage.getItem("forceState_" + location.host, v => {
  5259. storage.getItem("ruleLastUpdate", date => {
  5260. if (typeof(i) !== "undefined") {
  5261. nextIndex = i;
  5262. }
  5263. if (typeof(v) == "undefined") {
  5264. v = (rulesData.enableWhiteList ? 1 : 0);
  5265. }
  5266. forceState = v;
  5267. updateDate = date;
  5268. if (initConfig()) return;
  5269. pageReady = true;
  5270. if (forceState == 1) return;
  5271. let now = new Date().getTime();
  5272. if (!date || now - date > 2 * 24 * 60 * 60 * 1000) {
  5273. updateRules(() => {
  5274. }, (rule, err) => {}, true);
  5275. storage.setItem("ruleLastUpdate", now);
  5276. }
  5277. callback();
  5278. });
  5279. });
  5280. });
  5281. });
  5282. });
  5283. }
  5284.  
  5285. function requestDoc(url, callback){
  5286. let postParams = url.match(/#p{(.*)}$/);
  5287. if (postParams) {
  5288. postParams = postParams[1];
  5289. url = url.replace(/#p{.*/, "");
  5290. }
  5291. let ruleHeaders = ruleParser.curSiteRule.headers;
  5292. let headers = {
  5293. 'Referer': location.href,
  5294. 'User-Agent': navigator.userAgent,
  5295. 'accept': 'text/html,application/xhtml+xml,application/xml',
  5296. "Content-Type": (postParams ? "application/x-www-form-urlencoded" : "text/html") + ";charset=" + (document.characterSet || document.charset || document.inputEncoding),
  5297. };
  5298. if (ruleHeaders) {
  5299. if (ruleHeaders.referer) {
  5300. headers.referer = ruleHeaders.referer;
  5301. }
  5302. if (ruleHeaders.userAgent) {
  5303. headers.userAgent = ruleHeaders.userAgent;
  5304. }
  5305. if (ruleHeaders.accept) {
  5306. headers.accept = ruleHeaders.accept;
  5307. }
  5308. if (ruleHeaders.contentType) {
  5309. headers.contentType = ruleHeaders.contentType;
  5310. }
  5311. if (ruleHeaders.cookie) {
  5312. headers.cookie = ruleHeaders.cookie;
  5313. }
  5314. }
  5315. _GM_xmlhttpRequest({
  5316. url: url,
  5317. method: postParams ? 'POST' : 'GET',
  5318. data: postParams,
  5319. overrideMimeType: 'text/html;charset=' + (document.characterSet || document.charset || document.inputEncoding),
  5320. headers: headers,
  5321. timeout: 20000,
  5322. onload: async function(res) {
  5323. if (isPause) return callback(false);
  5324. var doc = null, response = res.response;
  5325. let preCode = ruleParser.curSiteRule.pageElementPre || ruleParser.curSiteRule.pagePre;
  5326. if (preCode) {
  5327. try {
  5328. if (typeof _unsafeWindow.pagetualPagePre != 'undefined') {
  5329. response = _unsafeWindow.pagetualPagePre(response);
  5330. } else if (preCode.length == 2) {
  5331. response = response.replace(new RegExp(preCode[0], "gi"), preCode[1]);
  5332. } else {
  5333. response = Function("response",'"use strict";' + preCode)(response);
  5334. }
  5335. } catch(e) {
  5336. debug(e);
  5337. }
  5338. }
  5339. try {
  5340. doc = document.implementation.createHTMLDocument('');
  5341. doc.documentElement.innerHTML = response;
  5342. let base = doc.querySelector("base");
  5343. ruleParser.basePath = base ? base.href : url;
  5344. }
  5345. catch (e) {
  5346. debug('parse error:' + e.toString());
  5347. }
  5348. let pageElement = ruleParser.getPageElement(doc);
  5349. if ((!pageElement || pageElement.length == 0) && res.status >= 400) {
  5350. debug(res.status, "Error status");
  5351. return callback(false);
  5352. }
  5353. if (inCors && (!pageElement || pageElement.length == 0) && ruleParser.curSiteRule.singleUrl) {
  5354. let article = doc.querySelectorAll(mainSel);
  5355. if (article && article.length == 1) {
  5356. article = article[0];
  5357. ruleParser.curSiteRule.pageElement = article.nodeName.toLowerCase() + (article.id ? "#" + article.id : "") + (article.className ? "." + article.className.replace(/ /g, ".") : "") + ">*";
  5358. pageElement = article.children;
  5359. } else {
  5360. ruleParser.curSiteRule.pageElement = allOfBody;
  5361. pageElement = ruleParser.getPageElement(doc);
  5362. }
  5363. ruleParser.getInsert(true);
  5364. }
  5365. //只有1的話怕不是圖片哦
  5366. if (pageElement && (pageElement.length > 1 || (pageElement.length == 1 && !/^IMG$/i.test(pageElement[0].nodeName)))) {
  5367. await ruleParser.insertPage(doc, pageElement, url, callback, false);
  5368. if (ruleParser.curSiteRule.action == 1) {
  5369. isLoading = true;
  5370. requestFromIframe(url, (doc, eles) => {
  5371. if (eles) {
  5372. ruleParser.insertPage(doc, eles, url, callback, true);
  5373. }
  5374. });
  5375. } else ruleParser.curSiteRule.action = 0;
  5376. } else if ((ruleParser.curSiteRule.singleUrl || curPage == 1) && !inCors) {
  5377. ruleParser.curSiteRule.action = 1;
  5378. requestFromIframe(url, (doc, eles) => {
  5379. if (eles) {
  5380. ruleParser.insertPage(doc, eles, url, callback, true);
  5381. }
  5382. });
  5383. } else {
  5384. debug("Stop as no page element");
  5385. showTips(i18n("noValidContent"), url);
  5386. isPause = true;
  5387. callback(false);
  5388. }
  5389. },
  5390. onerror: function(e) {
  5391. debug(e, "NetError");
  5392. callback(false);
  5393. },
  5394. ontimeout: function(e) {
  5395. debug(e, "NetTimeout");
  5396. callback(false);
  5397. }
  5398. });
  5399. }
  5400.  
  5401. function initPage() {
  5402. ruleParser.initPage(() => {
  5403. if (ruleParser.curSiteRule.autoLoadNum) {
  5404. autoLoadNum = ruleParser.curSiteRule.autoLoadNum;
  5405. }
  5406. if (ruleParser.curSiteRule.nextLink && Array && Array.isArray && Array.isArray(ruleParser.curSiteRule.nextLink)) {
  5407. _GM_registerMenuCommand(i18n("nextSwitch"), () => {
  5408. nextSwitch.start();
  5409. });
  5410. }
  5411. if (ruleParser.nextLinkHref) {
  5412. let isJs = /^(javascript|#)/.test(ruleParser.nextLinkHref.replace(location.href, ""));
  5413. if (!isJs) {
  5414. let inForce = (forceState == 2 || forceState == 3);
  5415. _GM_registerMenuCommand(i18n(inForce ? "cancelForceIframe" : "forceIframe"), () => {
  5416. if (inForce) {
  5417. storage.setItem("forceState_" + location.host, "");
  5418. } else {
  5419. let _state = ruleParser.curSiteRule.action > 0 || confirm(i18n("forceAllBody")) ? 2 : 3;
  5420. storage.setItem("forceState_" + location.host, _state);
  5421. }
  5422. location.reload();
  5423. });
  5424. }
  5425. _GM_registerMenuCommand(i18n("loadNow"), () => {
  5426. let loadNum = window.prompt(i18n("loadConfirm"), "1");
  5427. if (loadNum === "" || loadNum === null) return;
  5428. autoLoadNum = Math.abs(parseInt(loadNum));
  5429. nextPage();
  5430. });
  5431. }
  5432. _GM_registerMenuCommand(i18n(forceState == 1 ? "enable" : "disableSite"), () => {
  5433. forceState = (forceState == 1 ? 0 : 1);
  5434. storage.setItem("forceState_" + location.host, forceState);
  5435. showTips(i18n(forceState == 1 ? "disableSiteTips" : "enableSiteTips"));
  5436. if (!ruleParser.curSiteRule.url) location.reload();
  5437. });
  5438. initListener();
  5439. });
  5440. }
  5441.  
  5442. var pageBarStyle, mainStyleEle, mainStyleStyle;
  5443. function initView() {
  5444. if (!mainStyleStyle) {
  5445. mainStyleStyle = `
  5446. .pagetual_pageBar{
  5447. -moz-transition:all 0.3s ease-in-out 0s;
  5448. -webkit-transition:all 0.3s ease-in-out 0s;
  5449. transition:all 0.3s ease-in-out 0s;
  5450. font-family: Arial,sans-serif !important;
  5451. text-align: center !important;
  5452. }
  5453. .pagetual_pageBar.stop {
  5454. -webkit-filter: invert(100%);
  5455. filter: invert(100%);
  5456. opacity: 1!important;
  5457. }
  5458. .pagetual_pageBar.hide {
  5459. display: none!important;
  5460. }
  5461. .pagetual_pageBar:hover {
  5462. opacity: 1!important;
  5463. box-shadow: 0px 0px 10px 0px #000000aa;
  5464. border-radius: 20px;
  5465. background-color: rgb(240 240 240 / 80%);
  5466. border-color: transparent!important;
  5467. }
  5468. .pagetual_pageBar span {
  5469. vertical-align: super;
  5470. }
  5471. .pagetual_pageBar a::before,
  5472. .pagetual_pageBar a::after {
  5473. content: none;
  5474. }
  5475. .pagetual_pageBar a>span {
  5476. margin-top: 0!important;
  5477. pointer-events: none;
  5478. padding: unset;
  5479. opacity: 0;
  5480. -moz-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  5481. -webkit-transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  5482. transition:margin-top 0.3s ease-in-out 0s, opacity .3s;
  5483. transform: none;
  5484. left: 0;
  5485. margin-left: calc(50% - 20px);
  5486. }
  5487. .pagetual_pageBar a>span:hover {
  5488. color: red;
  5489. }
  5490. .pagetual_pageBar a:hover>span {
  5491. opacity: 1;
  5492. }
  5493. .pagetual_pageBar span.prevScreen,
  5494. .pagetual_pageBar span.nextScreen {
  5495. display: block!important;
  5496. }
  5497. .pagetual_pageBar a:hover>span.prevScreen {
  5498. margin-top: -${rulesData.opacity == 1 ? 31 : 30}px!important;
  5499. pointer-events: all;
  5500. }
  5501. .pagetual_pageBar a:hover>span.nextScreen {
  5502. margin-top: 30px!important;
  5503. pointer-events: all;
  5504. }
  5505. .pagetual_pageBar span>svg {
  5506. -moz-transition:transform 0.5s ease, opacity 0.3s ease;
  5507. -webkit-transition:transform 0.5s ease, opacity 0.3s ease;
  5508. transition:transform 0.5 ease, opacity 0.3s ease;
  5509. opacity: 0;
  5510. }
  5511. .pagetual_pageBar.stop span>svg{
  5512. opacity: 1;
  5513. }
  5514. .pagetual_pageBar.stop span>svg>path{
  5515. transform: scale(.8);
  5516. transform-origin: center;
  5517. -moz-transition:transform 0.3s ease;
  5518. -webkit-transition:transform 0.3s ease;
  5519. transition:transform 0.3 ease;
  5520. }
  5521. .pagetual_pageBar.stop:hover span>svg>path{
  5522. transform: unset;
  5523. }
  5524. .pagetual_pageBar:hover span>svg {
  5525. opacity: 1;
  5526. }
  5527. .pagetual_pageBar span>svg.upSvg:hover {
  5528. transform: rotate(360deg) scale3d(1.2, 1.2, 1.2);
  5529. }
  5530. .pagetual_pageBar span>svg.downSvg:hover {
  5531. transform: rotate(540deg) scale3d(1.2, 1.2, 1.2)!important;
  5532. }
  5533. .pagetual_pageBar .pagetual_pageNum{
  5534. color: #55555f;
  5535. }
  5536. .pagetual_pageBar .pagetual_pageNum:hover{
  5537. color: #ff6464;
  5538. }
  5539. .pagetual_tipsWords {
  5540. font-size: 50px;
  5541. font-weight: bold;
  5542. font-family: "黑体", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
  5543. "Oxygen", "Ubuntu", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
  5544. "Segoe UI Emoji", "Segoe UI Symbol";
  5545. color: #ffffff;
  5546. min-height: 70px;
  5547. max-width: 80%;
  5548. line-height: 70px;
  5549. position: fixed;
  5550. left: 50%;
  5551. top: 10%;
  5552. margin-left: -99999px;
  5553. padding: 0 15px;
  5554. z-index: 2147483647;
  5555. background-color: #000;
  5556. border: 1px solid #303030;
  5557. border-radius: 10px;
  5558. opacity: 0;
  5559. filter: alpha(opacity=65);
  5560. box-shadow: 5px 5px 20px 0px #000;
  5561. -moz-transition:opacity 0.3s ease-in-out 0s;
  5562. -webkit-transition:opacity 0.3s ease-in-out 0s;
  5563. transition:opacity 0.3s ease-in-out 0s;
  5564. pointer-events: none;
  5565. }
  5566. .pagetual_tipsWords>a {
  5567. color: #ffffff;
  5568. }
  5569. .pagetual_loading {
  5570. width: 50px;
  5571. height: 50px;
  5572. margin: 10px auto;
  5573. border-radius: 100%;
  5574. display: flex;
  5575. -webkit-animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  5576. animation: pagetual_loading_scaleout 1.0s infinite ease-in-out;
  5577. }
  5578. @-webkit-keyframes pagetual_loading_scaleout {
  5579. 0% { -webkit-transform: scale(0.0) }
  5580. 100% {
  5581. -webkit-transform: scale(1.0);
  5582. opacity: 0;
  5583. }
  5584. }
  5585. @keyframes pagetual_loading_scaleout {
  5586. 0% {
  5587. transform: scale(0.0);
  5588. -webkit-transform: scale(0.0);
  5589. } 100% {
  5590. transform: scale(1.0);
  5591. -webkit-transform: scale(1.0);
  5592. opacity: 0;
  5593. }
  5594. }
  5595. .pagetual_loading_text {
  5596. white-space: nowrap;
  5597. -webkit-animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  5598. animation: pagetual_loading_opacity 2.6s infinite ease-in-out;
  5599. }
  5600. @-webkit-keyframes pagetual_loading_opacity {
  5601. 0% { opacity: 1 }
  5602. 50% { opacity: 0.2 }
  5603. 100% { opacity: 1 }
  5604. }
  5605. @keyframes pagetual_loading_opacity {
  5606. 0% { opacity: 1 }
  5607. 50% { opacity: 0.2 }
  5608. 100% { opacity: 1 }
  5609. }
  5610. `;
  5611. let bodyColor
  5612. 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%);"}`;
  5613. }
  5614. if (!mainStyleEle || !mainStyleEle.parentNode) {
  5615. mainStyleEle = _GM_addStyle(mainStyleStyle);
  5616. }
  5617. }
  5618. var loadingDiv = document.createElement("div");
  5619. 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;";
  5620.  
  5621. 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;`;
  5622. function setLoadingDiv(loadingText) {
  5623. 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>`}`);
  5624. }
  5625.  
  5626. 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>`;
  5627. 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;`;
  5628. 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>`;
  5629. 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);`;
  5630.  
  5631. 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;`;
  5632. 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;`;
  5633. var sideControllerIcon = '';
  5634.  
  5635. var tipsWords = document.createElement("div");
  5636. tipsWords.className = "pagetual_tipsWords";
  5637.  
  5638. var isPause = false, isHideBar = false, isLoading = false, curPage = 1, forceState = 0, bottomGap = 1000, autoLoadNum = -1, nextIndex = 0, stopScroll = false, clickMode = false;
  5639. var openInNewTab = 0;
  5640.  
  5641. function changeStop(stop) {
  5642. isPause = stop;
  5643. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar,#pagetual-sideController"), bar => {
  5644. if (isPause) {
  5645. bar.classList.add("stop");
  5646. } else {
  5647. bar.classList.remove("stop");
  5648. }
  5649. });
  5650. }
  5651.  
  5652. function changeHideBar(hide) {
  5653. isHideBar = hide;
  5654. [].forEach.call(getBody(document).querySelectorAll(".pagetual_pageBar"), bar => {
  5655. if (isHideBar) {
  5656. bar.classList.add("hide");
  5657. } else {
  5658. bar.classList.remove("hide");
  5659. }
  5660. });
  5661. }
  5662.  
  5663. function isInViewPort(element) {
  5664. if (!getBody(document).contains(element)) return false;
  5665. if (_unsafeWindow.getComputedStyle(element).display == "none") return false;
  5666. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  5667. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  5668. const {
  5669. top,
  5670. right,
  5671. bottom,
  5672. left,
  5673. } = element.getBoundingClientRect();
  5674.  
  5675. return (
  5676. top >= 0 &&
  5677. left >= 0 &&
  5678. right <= viewWidth + 1 &&
  5679. top <= viewHeight * (ruleParser.curSiteRule.rate || rulesData.rate || 1)
  5680. );
  5681. }
  5682.  
  5683. function getPageBar() {
  5684. let preBar = null, nextBar = null;
  5685. let pageBars = [].slice.call(document.querySelectorAll(".pagetual_pageBar"));
  5686. for (let i = 0; i < pageBars.length; i++) {
  5687. let pageBar = pageBars[i];
  5688. if (!pageBar || !getBody(document).contains(pageBar)) continue;
  5689. let {
  5690. top,
  5691. right,
  5692. bottom,
  5693. left,
  5694. } = pageBar.getBoundingClientRect();
  5695. if (top > 500) {
  5696. nextBar = pageBar;
  5697. preBar = (i - 1 >= 0 ? pageBars[i - 1] : null);
  5698. if (pageBar && getBody(document).contains(pageBar)) {
  5699. let {
  5700. top,
  5701. right,
  5702. bottom,
  5703. left,
  5704. } = pageBar.getBoundingClientRect();
  5705. if (top < -500) {
  5706. preBar = pageBar;
  5707. } else preBar = (i - 2 >= 0 ? pageBars[i - 2] : null);
  5708. }
  5709. break;
  5710. }
  5711. }
  5712. if (!nextBar) preBar = pageBars[pageBars.length - 2];
  5713. return {preBar: preBar, nextBar: nextBar};
  5714. }
  5715.  
  5716. var urlChanged = false;
  5717. var urlchangeHandler = e => {
  5718. if (ruleParser && ruleParser.curSiteRule && ruleParser.curSiteRule.listenUrlChange == false) return;
  5719. isPause = true;
  5720. setTimeout(() => {
  5721. lastActiveUrl = location.href;
  5722. let href = location.href.slice(0, 60);
  5723. if (href == configPage[0]) {
  5724. location.reload();
  5725. } else {
  5726. setTimeout(() => {
  5727. if (guidePage.test(href)) {
  5728. location.reload();
  5729. } else {
  5730. urlChanged = true;
  5731. if (!ruleParser.nextLinkHref) {
  5732. isLoading = false;
  5733. }
  5734. //if (!pageReady && !ruleImportUrlReg.test(href)) location.reload();
  5735. }
  5736. }, 500);
  5737. }
  5738. }, 1);
  5739. };
  5740. window.addEventListener('pagetual_pushState', urlchangeHandler);
  5741. /*var _wr = function(type) {
  5742. var orig = history[type];
  5743. return function() {
  5744. var rv = orig.apply(this, arguments);
  5745. var e = new Event('pagetual_' + type);
  5746. e.arguments = arguments;
  5747. window.dispatchEvent(e);
  5748. return rv;
  5749. };
  5750. };
  5751. history.pushState = _wr('pushState');*/
  5752.  
  5753. function listenUrl() {
  5754. var prevState = window.location.pathname + window.location.search;
  5755. var checkUrlTime = 100;
  5756. var checkUrlTimer;
  5757. var checkFunc = () => {
  5758. if (forceState == 1) return;
  5759. if (checkUrlTime < 5000) {
  5760. checkUrlTime += checkUrlTime>>1;
  5761. }
  5762. clearTimeout(checkUrlTimer);
  5763. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  5764. if (document.hidden) return;
  5765. let url = window.location.pathname + window.location.search;
  5766. if (prevState !== url && window.location.href != ruleParser.historyUrl) {
  5767. checkUrlTime = 2000;
  5768. prevState = url;
  5769. var e = new Event('pagetual_pushState');
  5770. e.arguments = arguments;
  5771. window.dispatchEvent(e);
  5772. }
  5773. };
  5774. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  5775.  
  5776. document.addEventListener("click", e => {
  5777. checkUrlTime = 100;
  5778. clearTimeout(checkUrlTimer);
  5779. checkUrlTimer = setTimeout(checkFunc, checkUrlTime);
  5780. });
  5781. }
  5782.  
  5783. function distToBottom () {
  5784. let scrolly = window.scrollY;
  5785. let windowHeight = window.innerHeight || document.documentElement.clientHeight;
  5786. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  5787. return scrollH - scrolly - windowHeight;
  5788. }
  5789.  
  5790. let checkLoadMore, scrollHandler, clickToResetHandler, dblclickHandler, keydownHandler, hashchangeHandler, manualModeKeyHandler, pagetualNextHandler, keyupHandler;
  5791. function initListener () {
  5792. clearInterval(checkLoadMore);
  5793. document.removeEventListener('scroll', scrollHandler, true);
  5794. document.removeEventListener('wheel', scrollHandler, true);
  5795. document.removeEventListener('dblclick', dblclickHandler);
  5796. document.removeEventListener('keydown', keydownHandler);
  5797. window.removeEventListener('hashchange', hashchangeHandler, false);
  5798. document.removeEventListener('keydown', manualModeKeyHandler);
  5799. document.removeEventListener('pagetual.next', pagetualNextHandler, false);
  5800. document.removeEventListener('keyup', keyupHandler);
  5801. let loadmoreBtn, loadingMore = true, lastScroll = 0, checkLoadMoreTimes = 0;
  5802. if (!ruleParser.curSiteRule.singleUrl) {
  5803. if (ruleParser.curSiteRule.loadMore) {
  5804. loadingMore = false;
  5805. }
  5806. } else {
  5807. checkLoadMore = setInterval(() => {
  5808. loadmoreBtn = getLoadMore(document);
  5809. if (loadmoreBtn && isVisible(loadmoreBtn, _unsafeWindow)) {
  5810. loadingMore = false;
  5811. if (isInViewPort(loadmoreBtn)) {
  5812. emuClick(loadmoreBtn);
  5813. loadingMore = true;
  5814. setTimeout(() => {loadingMore = false}, 200);
  5815. }
  5816. clearInterval(checkLoadMore);
  5817. } else if (checkLoadMoreTimes++ > 10) {
  5818. clearInterval(checkLoadMore);
  5819. }
  5820. }, 1000);
  5821. }
  5822. clickMode = typeof ruleParser.curSiteRule.clickMode == 'undefined' ? rulesData.clickMode : ruleParser.curSiteRule.clickMode;
  5823. let clickNext = async () => {
  5824. let nextLink = ruleParser.nextLinkHref;
  5825. if (!nextLink) return;
  5826. let isJs = /^(javascript|#)/.test(nextLink.replace(location.href, ""));
  5827. if (isJs) {
  5828. let nextBtn = ruleParser.nextLinkEle;
  5829. if (!nextBtn || !nextBtn.offsetParent) nextBtn = await ruleParser.getNextLink(document);
  5830. if (nextBtn) emuClick(nextBtn);
  5831. } else {
  5832. window.location.href = nextLink;
  5833. }
  5834. };
  5835. let checkScrollReach = () => {
  5836. let dist = distToBottom();
  5837. if (clickMode) {
  5838. if (dist < 10) {
  5839. clickNext();
  5840. }
  5841. } else if (dist < bottomGap) {
  5842. nextPage();
  5843. }
  5844. };
  5845. scrollHandler = e => {
  5846. if (urlChanged && !isLoading) {
  5847. ruleParser.initPage(() => {});
  5848. urlChanged = false;
  5849. }
  5850. if (isPause) return;
  5851. if (!loadingMore) {
  5852. loadmoreBtn = getLoadMore(document, loadmoreBtn);
  5853. if (loadmoreBtn) {
  5854. if (isInViewPort(loadmoreBtn)) {
  5855. emuClick(loadmoreBtn);
  5856. loadingMore = true;
  5857. setTimeout(() => {loadingMore = false}, 200);
  5858. }
  5859. } else {
  5860. loadingMore = true;
  5861. setTimeout(() => {loadingMore = false}, 200);
  5862. }
  5863. }
  5864. if (!isLoading && !stopScroll) {
  5865. checkScrollReach();
  5866. }
  5867. ruleParser.changeVisibility();
  5868. if (ruleParser.curSiteRule.lockScroll) {
  5869. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  5870. if (isLoading && Math.abs(lastScroll - curScroll) > 350) {
  5871. getBody(document).scrollTop = lastScroll;
  5872. document.documentElement.scrollTop = lastScroll;
  5873. } else {
  5874. lastScroll = curScroll;
  5875. }
  5876. }
  5877. };
  5878. dblclickHandler = e => {
  5879. if (forceState == 1 || /^(INPUT|TEXTAREA|SELECT)$/i.test(e.target.nodeName)) return;
  5880. if (!rulesData.dbClick2StopKey) {
  5881. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  5882. (rulesData.dbClick2StopAlt && !e.altKey) ||
  5883. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  5884. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  5885. return;
  5886. }
  5887. }
  5888. if (!/^BODY$/i.test(e.target.nodeName) && e.target.className !== 'pagetual_pageBar') {
  5889. let selStr = document.getSelection().toString();
  5890. if (selStr && selStr.trim()) {
  5891. return;
  5892. }
  5893. }
  5894. if (rulesData.dbClick2Stop && (ruleParser.nextLinkHref || loadmoreBtn)) {
  5895. setTimeout(() => {
  5896. if (rulesData.hideBarButNoStop || rulesData.hideBar) {
  5897. changeHideBar(!isHideBar);
  5898. }
  5899. if (!rulesData.hideBarButNoStop) {
  5900. changeStop(!isPause);
  5901. showTips(i18n(isPause ? "disable" : "enable"));
  5902. }
  5903. if (!isPause) {
  5904. checkScrollReach();
  5905. }
  5906. }, 10);
  5907. }
  5908. };
  5909. document.addEventListener('dblclick', dblclickHandler);
  5910. clickToResetHandler = e => {
  5911. if (!ruleParser.nextLinkHref) isLoading = false;
  5912. };
  5913. document.addEventListener('click', clickToResetHandler);
  5914. if (rulesData.dbClick2StopKey) {
  5915. keydownHandler = e => {
  5916. if ((rulesData.dbClick2StopCtrl && !e.ctrlKey) ||
  5917. (rulesData.dbClick2StopAlt && !e.altKey) ||
  5918. (rulesData.dbClick2StopShift && !e.shiftKey) ||
  5919. (rulesData.dbClick2StopMeta && !e.metaKey)) {
  5920. return;
  5921. }
  5922. if (document.activeElement &&
  5923. (/^(INPUT|TEXTAREA)$/i.test(document.activeElement.nodeName) ||
  5924. document.activeElement.contentEditable == 'true')) {
  5925. return;
  5926. }
  5927. var key = e.key.toLowerCase();
  5928. if (rulesData.dbClick2StopKey.toLowerCase() == key) {
  5929. forceState = (forceState == 1 ? 0 : 1);
  5930. showTips(i18n(forceState == 1 ? "disableSiteTips" : "enableSiteTips"));
  5931. if (!ruleParser.curSiteRule.url) {
  5932. storage.setItem("forceState_" + location.host, forceState);
  5933. location.reload();
  5934. }
  5935. }
  5936. };
  5937. document.addEventListener('keydown', keydownHandler);
  5938. }
  5939. if (ruleParser.curSiteRule.listenHashChange) {
  5940. hashchangeHandler = () => {
  5941. isPause = true;
  5942. urlChanged = true;
  5943. if (!ruleParser.nextLinkHref) isLoading = false;
  5944. };
  5945. window.addEventListener('hashchange', hashchangeHandler, false);
  5946. }
  5947. let manualMode = typeof ruleParser.curSiteRule.manualMode == 'undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode;
  5948. if (manualMode) {
  5949. manualModeKeyHandler = e => {
  5950. if (document.activeElement &&
  5951. (/^(INPUT|TEXTAREA)$/i.test(document.activeElement.nodeName) ||
  5952. document.activeElement.contentEditable == 'true')) {
  5953. return;
  5954. }
  5955. if (e.keyCode == 39) {
  5956. clickNext();
  5957. } else if (e.keyCode == 37) {
  5958. history.back();
  5959. }
  5960. };
  5961. document.addEventListener('keydown', manualModeKeyHandler);
  5962. pagetualNextHandler = () => {
  5963. clickNext();
  5964. };
  5965. document.addEventListener('pagetual.next', pagetualNextHandler, false);
  5966. return;
  5967. }
  5968. if (rulesData.arrowToScroll) {
  5969. keyupHandler = e => {
  5970. if (document.activeElement &&
  5971. (/^(INPUT|TEXTAREA)$/i.test(document.activeElement.nodeName) ||
  5972. document.activeElement.contentEditable == 'true')) {
  5973. return;
  5974. }
  5975. if (e.keyCode == 39) {
  5976. let nextPageBar=getPageBar().nextBar;
  5977. if (nextPageBar) {
  5978. scrollToPageBar(nextPageBar);
  5979. } else {
  5980. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  5981. window.scrollTo({ top: scrollTop + (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  5982. }
  5983. } else if (e.keyCode == 37) {
  5984. let prePageBar = getPageBar().preBar;
  5985. if (prePageBar) {
  5986. scrollToPageBar(prePageBar);
  5987. } else {
  5988. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  5989. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  5990. }
  5991. }
  5992. };
  5993. document.addEventListener('keyup', keyupHandler);
  5994. }
  5995. if (!ruleParser.curSiteRule.wheel) {
  5996. document.addEventListener('scroll', scrollHandler, true);
  5997. }
  5998. document.addEventListener('wheel', scrollHandler, true);
  5999. }
  6000.  
  6001. let hideTipsTimeout;
  6002. function showTips(content, href, time, wordColor, backColor) {
  6003. initView();
  6004. getBody(document).appendChild(tipsWords);
  6005. tipsWords.style.color = wordColor || 0xFFFFFF;
  6006. tipsWords.style.backgroundColor = backColor || 0x000;
  6007. let _time = 1500;
  6008. if (href) {
  6009. _time = 3500;
  6010. tipsWords.innerHTML = createHTML(`<a href='${href}'>${content}</a>`);
  6011. tipsWords.style.pointerEvents = 'all';
  6012. } else {
  6013. tipsWords.innerHTML = createHTML(content);
  6014. }
  6015. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  6016. setTimeout(() => {
  6017. tipsWords.style.marginLeft = -tipsWords.offsetWidth / 2 + "px";
  6018. }, 0);
  6019. setTimeout(() => {
  6020. tipsWords.style.opacity = 0.8;
  6021. clearTimeout(hideTipsTimeout);
  6022. hideTipsTimeout = setTimeout(() => {
  6023. tipsWords.style.opacity = 0;
  6024. tipsWords.style.pointerEvents = '';
  6025. }, time || _time);
  6026. }, 1);
  6027. }
  6028.  
  6029. const loadmoreReg = /^\s*((点击)?加载更多|(點擊)?加載更多|load\s*more|もっと読み込む)[.…]*\s*$/i;
  6030. const defaultLoadmoreSel = ".loadMore,.LoadMore,.load-more,.button-show-more,button[data-testid='more-results-button'],#btn_preview_remain";
  6031. function getLoadMore(doc, loadmoreBtn) {
  6032. if (!loadmoreBtn || !getBody(doc).contains(loadmoreBtn) || /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  6033. if (!ruleParser.curSiteRule.singleUrl && !ruleParser.curSiteRule.loadMore) return null;
  6034. if (loadmoreBtn) return loadmoreBtn;
  6035. let btnSel = ruleParser.curSiteRule.loadMore || defaultLoadmoreSel;
  6036. if (btnSel) {
  6037. loadmoreBtn = getElement(btnSel, doc);
  6038. }
  6039. if (!loadmoreBtn) {
  6040. let buttons = doc.querySelectorAll("input,button,a,div[onclick]");
  6041. for (let i = 0; i < buttons.length; i++) {
  6042. let button = buttons[i];
  6043. if (!button.innerText || button.innerText.length > 20) continue;
  6044. if (button && loadmoreReg.test(button.innerText)) {
  6045. loadmoreBtn = button;
  6046. break;
  6047. }
  6048. }
  6049. }
  6050. if (loadmoreBtn && !ruleParser.curSiteRule.loadMore && loadmoreBtn.dataset.ajax !== "true") {
  6051. let href = loadmoreBtn.getAttribute("href");
  6052. if (href && href != "/" && !/^(javascript|#)/.test(href.replace(location.href, ""))) {
  6053. loadmoreBtn = null;
  6054. }
  6055. }
  6056. if (loadmoreBtn && /less/.test(loadmoreBtn.innerText)) loadmoreBtn = null;
  6057. return loadmoreBtn;
  6058. }
  6059.  
  6060. function scrollToPageBar(bar){
  6061. let yOffset = -20;
  6062. if (typeof ruleParser.curSiteRule.pageBarTop !== 'undefined') {
  6063. yOffset = -ruleParser.curSiteRule.pageBarTop;
  6064. }
  6065. const y = bar.getBoundingClientRect().top + window.pageYOffset + yOffset;
  6066. window.scrollTo({ top: y, behavior: 'smooth'});
  6067. }
  6068.  
  6069. const pageNumReg=/[&\/\?](p=|page[=\/_-]?)\d+|[_-]\d+\./;
  6070. function createPageBar(url) {
  6071. curPage++;
  6072. sideController.setup();
  6073. let posEle = null;
  6074. let scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  6075. let insert = ruleParser.getInsert();
  6076. if (!insert || !insert.parentNode) return;
  6077. if (forceState == 2) {
  6078. posEle = getBody(document);
  6079. posEle = posEle.children[posEle.children.length - 1];
  6080. } else {
  6081. posEle = insert;
  6082. }
  6083. while (posEle && !posEle.offsetParent) {
  6084. posEle = posEle.previousElementSibling || posEle.parentNode;
  6085. }
  6086. if (posEle) {
  6087. let actualBottom = getElementBottom(posEle);
  6088. bottomGap = scrollH - actualBottom + (window.innerHeight || document.documentElement.clientHeight) * (ruleParser.curSiteRule.rate || rulesData.rate || 1);
  6089. if (bottomGap < 100) bottomGap = 100;
  6090. } else {
  6091. bottomGap = 1000;
  6092. }
  6093. if (rulesData.opacity == 0 || ruleParser.curSiteRule.pageBar === 0) return null;
  6094. url = url.replace(/#p{.*/, "");
  6095. let example = ruleParser.curSiteRule.insertPos == 2 ? insert.children[0] : (insert.parentNode.children[0] || insert);
  6096. while (example && (/^(SCRIPT|STYLE)$/i.test(example.nodeName) || example.className == "pagetual_pageBar")) {
  6097. example = example.nextElementSibling;
  6098. }
  6099. if (!example || !example.parentNode) example = insert;
  6100. if (example.nodeType != 1) {
  6101. example = example.previousElementSibling || example.parentNode;
  6102. if (!example || example.nodeType != 1) return;
  6103. }
  6104. let exampleStyle = _unsafeWindow.getComputedStyle(example);
  6105. let inTable, inLi;
  6106. if (forceState == 2) {
  6107. inTable = inLi = false;
  6108. } else {
  6109. inTable = /^(TABLE|TBODY)$/i.test(example.parentNode.nodeName) ||
  6110. /^(TR|TBODY)$/i.test(example.nodeName) ||
  6111. exampleStyle.display == "table-row" ||
  6112. (example.nextElementSibling && /^(TR|TBODY)$/i.test(example.nextElementSibling.nodeName));
  6113. inLi = /^LI$/i.test(example.nodeName) || (example.nextElementSibling && /^LI$/i.test(example.nextElementSibling.nodeName));
  6114. }
  6115. let pageBar = document.createElement(inTable ? "tr" : (inLi ? "li" : "div"));
  6116. let upSpan = document.createElement("span");
  6117. let downSpan = document.createElement("span");
  6118. let pageText = document.createElement("a");
  6119. let pageNum;
  6120. pageBar.className = isHideBar ? "pagetual_pageBar hide" : "pagetual_pageBar";
  6121. pageBar.id = "pagetual_pageBar" + curPage;
  6122. pageBar.setAttribute("translate", "no");
  6123. if (isPause) {
  6124. pageBar.classList.add("stop");
  6125. }
  6126. pageBar.style.cssText = pageBarStyle;
  6127. pageBar.title = i18n(isPause ? "enable" : "disable");
  6128. upSpan.innerHTML = upSvg;
  6129. upSpan.children[0].style.cssText = upSvgCSS;
  6130. upSpan.title = i18n("toTop");
  6131. downSpan.innerHTML = downSvg;
  6132. downSpan.children[0].style.cssText = downSvgCSS;
  6133. downSpan.title = i18n("toBottom");
  6134. upSpan.style.cssText = initStyle;
  6135. downSpan.style.cssText = initStyle;
  6136. pageText.href = url;
  6137. pageText.style.cssText = pageTextStyle;
  6138. pageText.title = i18n("current");
  6139. if (openInNewTab == 1) pageText.target = "_blank";
  6140. pageBar.appendChild(upSpan);
  6141. pageBar.appendChild(pageText);
  6142. if (rulesData.pageBarMenu) {
  6143. pageText.addEventListener("click", e => {
  6144. e.stopPropagation();
  6145. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
  6146. e.preventDefault();
  6147. picker.start();
  6148. });
  6149. }
  6150. let touched = false;
  6151. let touchBodyHandler = e => {
  6152. touched = false;
  6153. getBody(document).removeEventListener('touchstart', touchBodyHandler, { passive: false, capture: false });
  6154. };
  6155. pageText.addEventListener("touchstart", e => {
  6156. if (touched) return;
  6157. touched = true;
  6158. pageText.style.pointerEvents = 'none';
  6159. setTimeout(() => {
  6160. pageText.style.pointerEvents = 'all';
  6161. }, 250);
  6162. getBody(document).addEventListener("touchstart", touchBodyHandler, { passive: false, capture: false });
  6163. }, { passive: false, capture: false });
  6164. if (ruleParser.nextTitle) {
  6165. pageText.innerHTML = ruleParser.nextTitle + " ";
  6166. pageText.title = ruleParser.nextTitle;
  6167. }
  6168. if (ruleParser.curSiteRule.pageNum || pageNumReg.test(url)) {
  6169. pageText.innerHTML += i18n("page");
  6170. pageNum = document.createElement("span");
  6171. let num = ruleParser.getPageNumFromUrl(url);
  6172. pageNum.innerHTML = num;
  6173. pageNum.className = "pagetual_pageNum";
  6174. pageNum.title = i18n("inputPageNum");
  6175. pageNum.style.cssText = pageTextStyle;
  6176. pageNum.style.cursor = "pointer";
  6177. pageNum.style.color = "";
  6178. pageNum.style.marginLeft = "5px";
  6179. pageNum.addEventListener("click", e => {
  6180. let pageInput = prompt(i18n("inputPageNum"), num || "1");
  6181. if (pageInput) {
  6182. let localPageBar = document.querySelector("#pagetual_pageBar" + pageInput);
  6183. if (localPageBar) {
  6184. scrollToPageBar(localPageBar);
  6185. } else {
  6186. let pageLink = ruleParser.getLinkByPage(url, pageInput);
  6187. if (pageLink) {
  6188. _GM_openInTab(pageLink, {active:true});
  6189. }
  6190. }
  6191. }
  6192. e.preventDefault();
  6193. e.stopPropagation();
  6194. });
  6195. pageBar.appendChild(pageNum);
  6196. } else {
  6197. pageText.innerHTML += i18n("page") + curPage;
  6198. }
  6199. let preBtn = document.createElement("span");
  6200. preBtn.innerHTML = "∧";
  6201. preBtn.title = i18n("prevPage");
  6202. preBtn.className = "prevScreen";
  6203. 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; ";
  6204. let nextBtn = document.createElement("span");
  6205. nextBtn.innerHTML = "∨";
  6206. nextBtn.title = i18n("nextPage");
  6207. nextBtn.className = "nextScreen";
  6208. 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; ";
  6209. let localPage = curPage;
  6210. preBtn.addEventListener("click", e => {
  6211. e.stopPropagation();
  6212. e.preventDefault();
  6213. let prePageBar = document.querySelector("#pagetual_pageBar" + (localPage - 1));
  6214. if (prePageBar) {
  6215. scrollToPageBar(prePageBar);
  6216. } else {
  6217. let scrollTop = getBody(document).scrollTop || document.documentElement.scrollTop;
  6218. window.scrollTo({ top: scrollTop - (window.innerHeight || document.documentElement.clientHeight), behavior: 'smooth'});
  6219. }
  6220. });
  6221. nextBtn.addEventListener("click", e => {
  6222. e.stopPropagation();
  6223. e.preventDefault();
  6224. let nextPageBar = document.querySelector("#pagetual_pageBar" + (localPage + 1));
  6225. if (nextPageBar) {
  6226. scrollToPageBar(nextPageBar);
  6227. } else {
  6228. scrollH = Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  6229. window.scrollTo({ top: scrollH || 9999999, behavior: 'smooth'});
  6230. }
  6231. });
  6232. if (!rulesData.hideBarArrow) {
  6233. pageText.insertBefore(preBtn, pageText.firstChild);
  6234. pageText.insertBefore(nextBtn, pageText.firstChild);
  6235. }
  6236. pageBar.appendChild(downSpan);
  6237. if (forceState == 2) {
  6238. pageBar.style.width = "99%";
  6239. } else {
  6240. let parentStyle = _unsafeWindow.getComputedStyle(example.parentNode);
  6241. let parentWidth = example.parentNode.offsetWidth || parseInt(parentStyle.width);
  6242. pageBar.style.width = parentWidth - parseInt(parentStyle.paddingLeft) - parseInt(parentStyle.paddingRight) - 10 + "px";
  6243. pageBar.style.margin = '10px 5px';
  6244. if (parentStyle.display == "grid" || parentStyle.display == "inline-grid") {
  6245. pageBar.style.gridColumn = "1/-1";
  6246. }
  6247. if (inTable) {
  6248. example = (/^(TR|TBODY)$/i.test(example.nodeName)) ? example : example.nextElementSibling || example;
  6249. if (/^TBODY$/i.test(example.nodeName)) example = example.querySelector("tr");
  6250. let nextTr = example;
  6251. while (nextTr && nextTr.children.length == 0) nextTr = nextTr.nextElementSibling;
  6252. if (nextTr) example = nextTr;
  6253. let tdNum = 0;
  6254. if (exampleStyle.display == "table-row") {
  6255. [].forEach.call(example.children, el => {
  6256. tdNum += el.colSpan || 1;
  6257. });
  6258. } else {
  6259. [].forEach.call(example.children, el => {
  6260. if (/^(TD|TH)$/i.test(el.nodeName)) {
  6261. tdNum += el.colSpan || 1;
  6262. }
  6263. });
  6264. }
  6265. pageBar.style.cssText = "";
  6266. pageBar.style.display = "table-row";
  6267. pageBar.style.backgroundColor = "unset";
  6268. pageBar.style.lineHeight = "20px";
  6269. pageBar.style.boxShadow = "";
  6270. let td = document.createElement("td");
  6271. td.colSpan = tdNum || 1;
  6272. let inTd = document.createElement("div");
  6273. inTd.style.cssText = pageBarStyle;
  6274. inTd.style.display = "";
  6275. inTd.className = pageBar.className;
  6276. pageBar.className = "";
  6277. inTd.appendChild(upSpan);
  6278. inTd.appendChild(pageText);
  6279. if (pageNum) inTd.appendChild(pageNum);
  6280. inTd.appendChild(downSpan);
  6281. td.appendChild(inTd);
  6282. pageBar.appendChild(td);
  6283. } else if (inLi) {
  6284. example = /^LI$/i.test(example.nodeName) ? example : example.nextElementSibling || example;
  6285. pageBar.style.opacity = 1;
  6286. pageBar.style.display = getComputedStyle(example).display;
  6287. pageBar.style.backgroundColor = "unset";
  6288. pageBar.style.lineHeight = "20px";
  6289. pageBar.style.boxShadow = "";
  6290. pageBar.style.border = "";
  6291. pageBar.style.maxWidth = "unset";
  6292. pageBar.style.flex = "auto";
  6293. let inTd = document.createElement("div");
  6294. inTd.style.cssText = pageBarStyle;
  6295. inTd.style.display = "";
  6296. inTd.style.margin = "0"
  6297. inTd.style.padding = "0 0";
  6298. inTd.style.textAlign = "center";
  6299. inTd.style.minWidth = "150px";
  6300. inTd.style.width = 'calc(100% - 20px)';
  6301. inTd.className = pageBar.className;
  6302. pageBar.className = "";
  6303. inTd.appendChild(upSpan);
  6304. inTd.appendChild(pageText);
  6305. if (pageNum) inTd.appendChild(pageNum);
  6306. inTd.appendChild(downSpan);
  6307. if (pageBar.style.display === 'table-row') {
  6308. let td = document.createElement("td");
  6309. td.colSpan = example.children.length;
  6310. td.style.width = '100%';
  6311. td.appendChild(inTd);
  6312. pageBar.appendChild(td);
  6313. } else {
  6314. inTd.style.width = '100%';
  6315. pageBar.appendChild(inTd);
  6316. }
  6317. }
  6318. }
  6319.  
  6320. upSpan.addEventListener("click", e => {
  6321. getBody(document).scrollTop = 0;
  6322. document.documentElement.scrollTop = 0;
  6323. e.preventDefault();
  6324. e.stopPropagation();
  6325. });
  6326. downSpan.addEventListener("click", e => {
  6327. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  6328. changeStop(true);
  6329. }
  6330. pageBar.title = i18n(isPause ? "enable" : "disable");
  6331. scrollH=Math.max(document.documentElement.scrollHeight, getBody(document).scrollHeight);
  6332. getBody(document).scrollTop = scrollH || 9999999;
  6333. document.documentElement.scrollTop = scrollH || 9999999;
  6334. e.preventDefault();
  6335. e.stopPropagation();
  6336. });
  6337. pageBar.addEventListener("click", e => {
  6338. changeStop(!isPause);
  6339. pageBar.title = i18n(isPause ? "enable" : "disable");
  6340. });
  6341. ruleParser.insertElement(pageBar);
  6342. if (ruleParser.curSiteRule.pageBar && ruleParser.curSiteRule.pageBar !== 0) {
  6343. try {
  6344. ((typeof _unsafeWindow.pagetualPageBar == 'undefined') ? Function("pageBar",'"use strict";' + ruleParser.curSiteRule.pageBar) : _unsafeWindow.pagetualPageBar)(pageBar);
  6345. } catch(e) {
  6346. debug(e);
  6347. }
  6348. }
  6349.  
  6350. return pageBar;
  6351. }
  6352.  
  6353. function emuClick(btn) {
  6354. let orgHref = btn.getAttribute('href');
  6355. if (orgHref && orgHref != "#") {
  6356. btn.setAttribute('href', orgHref.replace(/#$/,""));
  6357. }
  6358. if (!PointerEvent) return btn.click();
  6359. let eventParam = {
  6360. isTrusted: true,
  6361. altKey: false,
  6362. azimuthAngle: 0,
  6363. bubbles: true,
  6364. button: 0,
  6365. buttons: 0,
  6366. clientX: 1,
  6367. clientY: 1,
  6368. cancelBubble: false,
  6369. cancelable: true,
  6370. composed: true,
  6371. ctrlKey: false,
  6372. defaultPrevented: false,
  6373. detail: 1,
  6374. eventPhase: 2,
  6375. fromElement: null,
  6376. height: 1,
  6377. isPrimary: false,
  6378. metaKey: false,
  6379. pointerId: 1,
  6380. pointerType: "mouse",
  6381. pressure: 0,
  6382. relatedTarget: null,
  6383. returnValue: true,
  6384. shiftKey: false,
  6385. toElement: null,
  6386. twist: 0,
  6387. which: 1
  6388. };
  6389. let mouseEvent = new PointerEvent("mousedown", eventParam);
  6390. btn.dispatchEvent(mouseEvent);
  6391. mouseEvent = new PointerEvent("mouseup", eventParam);
  6392. btn.dispatchEvent(mouseEvent);
  6393. let dispatchTouchEvent = (ele, type) => {
  6394. let touchEvent;
  6395. try {
  6396. touchEvent = document.createEvent('TouchEvent')
  6397. touchEvent.initTouchEvent(type, true, true)
  6398. } catch (err) {
  6399. try {
  6400. touchEvent = document.createEvent('UIEvent')
  6401. touchEvent.initUIEvent(type, true, true)
  6402. } catch (err) {
  6403. touchEvent = document.createEvent('Event')
  6404. touchEvent.initEvent(type, true, true)
  6405. }
  6406. }
  6407. if (touchEvent) {
  6408. try {
  6409. touchEvent.targetTouches = [{
  6410. pageX: 1,
  6411. pageY: 1,
  6412. clientX: 1,
  6413. clientY: 1,
  6414. target: btn
  6415. }];
  6416. touchEvent.touches = [{
  6417. pageX: 1,
  6418. pageY: 1,
  6419. clientX: 1,
  6420. clientY: 1,
  6421. target: btn
  6422. }];
  6423. touchEvent.changedTouches = [{
  6424. pageX: 1,
  6425. pageY: 1,
  6426. clientX: 1,
  6427. clientY: 1,
  6428. target: btn
  6429. }];
  6430. } catch (err) {}
  6431. ele.dispatchEvent(touchEvent);
  6432. }
  6433. }
  6434. dispatchTouchEvent(btn, "touchstart");
  6435. dispatchTouchEvent(btn, "touchend");
  6436.  
  6437. btn.click();
  6438. if (orgHref && orgHref != "#") {
  6439. setTimeout(() => btn.setAttribute('href', orgHref), 0);
  6440. }
  6441. }
  6442.  
  6443. var failFromIframe = 0;
  6444. var inCors = false;
  6445. var checkRemoveIntv;
  6446. function requestFromIframe(url, callback){
  6447. if (location.protocol === 'https:' && !/^https:/.test(url)) {
  6448. showTips(i18n("noValidContent"), url);
  6449. }
  6450. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  6451. let iframe = document.createElement('iframe');
  6452. iframe.name = 'pagetual-iframe';
  6453. iframe.width = '100%';
  6454. iframe.height = '1000';
  6455. iframe.frameBorder = '0';
  6456. if (ruleParser.curSiteRule.sandbox != false) {
  6457. iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  6458. }
  6459. 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;';
  6460. let waitTime = 100, checkEval;
  6461. if (ruleParser.curSiteRule.waitElement) {
  6462. checkEval = doc => {
  6463. return ruleParser.waitElement(doc);
  6464. };
  6465. } else if (ruleParser.curSiteRule.wait) {
  6466. if (isNaN(ruleParser.curSiteRule.wait)) {
  6467. try {
  6468. checkEval = (typeof _unsafeWindow.pagetualWait == 'undefined') ? Function("doc",'"use strict";' + ruleParser.curSiteRule.wait) : _unsafeWindow.pagetualWait;
  6469. } catch(e) {
  6470. debug(e);
  6471. }
  6472. } else {
  6473. waitTime = ruleParser.curSiteRule.wait;
  6474. }
  6475. }
  6476. if (checkRemoveIntv) clearInterval(checkRemoveIntv);
  6477. checkRemoveIntv = setInterval(() => {
  6478. if (!iframe || !getBody(document).contains(iframe)) {
  6479. clearInterval(checkRemoveIntv);
  6480. loadPageOver();
  6481. }
  6482. }, 500);
  6483. let loadedHandler = e => {
  6484. if (e.data != 'pagetual-iframe:DOMLoaded' && e.type != 'load') return;
  6485. clearInterval(checkRemoveIntv);
  6486. window.removeEventListener('message', loadedHandler, false);
  6487. iframe.removeEventListener('load', loadedHandler, false);
  6488. let tryTimes = 0;
  6489. function checkIframe() {
  6490. if (urlChanged || isPause) {
  6491. return callback(false, false);
  6492. }
  6493. try {
  6494. let doc = iframe.contentDocument || iframe.contentWindow.document;
  6495. let base = doc.querySelector("base");
  6496. ruleParser.basePath = base ? base.href : url;
  6497. let eles = ruleParser.getPageElement(doc, iframe.contentWindow);
  6498. if (checkEval && !checkEval(doc)) {
  6499. setTimeout(() => {
  6500. checkIframe();
  6501. }, waitTime);
  6502. return;
  6503. } else if (eles && eles.length > 0) {
  6504. callback(doc, eles);
  6505. } else if (tryTimes++ < 100) {
  6506. setTimeout(() => {
  6507. checkIframe();
  6508. }, waitTime);
  6509. return;
  6510. } else {
  6511. if (failFromIframe++ > 2) {
  6512. failFromIframe = 0;
  6513. debug("Stop as failFromIframe");
  6514. isPause = true;
  6515. callback(false, false);
  6516. } else {
  6517. showTips(i18n("noValidContent"), url);
  6518. callback(false, false);
  6519. }
  6520. }
  6521. } catch(e) {
  6522. inCors = true;
  6523. if (forceState === 3) {
  6524. debug("Stop as cors");
  6525. isPause = true;
  6526. }
  6527. if (!ruleParser.curSiteRule.pageElement) {
  6528. ruleParser.curSiteRule.pageElement = allOfBody;
  6529. ruleParser.getInsert(true);
  6530. }
  6531. ruleParser.curSiteRule.action = 0;
  6532. ruleParser.nextLinkHref = url;
  6533. callback(false, false);
  6534. nextPage();
  6535. }
  6536. if (iframe && iframe.parentNode) iframe.parentNode.removeChild(iframe);
  6537. }
  6538. setTimeout(() => {
  6539. checkIframe();
  6540. }, waitTime);
  6541. };
  6542. window.addEventListener('message', loadedHandler, false);
  6543. iframe.addEventListener('load', loadedHandler, false);
  6544. iframe.src = url;
  6545. try {
  6546. getBody(document).appendChild(iframe);
  6547. } catch (e) {
  6548. return callback(false, false);
  6549. }
  6550. }
  6551.  
  6552. var emuIframe, lastActiveUrl, orgContent, meetCors = false;
  6553. function emuPage(callback) {
  6554. let orgPage = null, preContent = null, iframeDoc, checkTimes = 0, loadmoreBtn, pageEle, nextLink, loadmoreEnd = false, waitTimes = 80, changed = false;
  6555. function returnFalse(log) {
  6556. debug(log);
  6557. isPause = true;
  6558. callback(false, false);
  6559. if (emuIframe && emuIframe.parentNode) {
  6560. emuIframe.parentNode.removeChild(emuIframe);
  6561. sideController.remove();
  6562. emuIframe = null;
  6563. }
  6564. }
  6565. async function checkPage() {
  6566. if (isPause) return loadPageOver();
  6567. try {
  6568. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  6569. } catch(e) {
  6570. returnFalse("Stop as cors");
  6571. return;
  6572. }
  6573.  
  6574. let waitTime = 200, checkEval;
  6575. if (ruleParser.curSiteRule.waitElement) {
  6576. checkEval = doc => {
  6577. return ruleParser.waitElement(doc);
  6578. };
  6579. } else if(ruleParser.curSiteRule.wait) {
  6580. if (isNaN(ruleParser.curSiteRule.wait)) {
  6581. try {
  6582. checkEval = (typeof _unsafeWindow.pagetualWait == 'undefined') ? Function("doc", '"use strict";' + ruleParser.curSiteRule.wait) : _unsafeWindow.pagetualWait;
  6583. } catch(e) {
  6584. debug(e);
  6585. }
  6586. } else {
  6587. waitTime = ruleParser.curSiteRule.wait;
  6588. }
  6589. }
  6590.  
  6591. if (!orgPage) {
  6592. if (!loadmoreEnd) {
  6593. loadmoreBtn = getLoadMore(iframeDoc);
  6594. if (loadmoreBtn && isVisible(loadmoreBtn, iframeDoc.defaultView)) {
  6595. emuClick(loadmoreBtn);
  6596. let intv = setInterval(() => {
  6597. loadmoreBtn = getLoadMore(iframeDoc);
  6598. if (!loadmoreBtn || !getBody(document).contains(loadmoreBtn) || !isVisible(loadmoreBtn, iframeDoc.defaultView)) {
  6599. clearInterval(intv);
  6600. loadmoreEnd = true;
  6601. setTimeout(() => {
  6602. checkPage();
  6603. }, 500);
  6604. } else if (isInViewPort(loadmoreBtn)) {
  6605. emuClick(loadmoreBtn);
  6606. }
  6607. }, 200);
  6608. return;
  6609. } else {
  6610. loadmoreEnd = true;
  6611. }
  6612. }
  6613. if (checkEval && !checkEval(iframeDoc)) {
  6614. waitTimes = 50;
  6615. setTimeout(() => {
  6616. checkPage();
  6617. }, waitTime);
  6618. return;
  6619. } else {
  6620. if (!nextLink || !nextLink.offsetParent) nextLink = await ruleParser.getNextLink(iframeDoc);
  6621. if (nextLink) pageEle = ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true);
  6622. if (!pageEle || pageEle.length == 0 || !nextLink) {
  6623. if (waitTimes-- > 0) {
  6624. setTimeout(() => {
  6625. checkPage();
  6626. }, waitTime);
  6627. return;
  6628. }
  6629. }
  6630. }
  6631. if (!pageEle || pageEle.length == 0) {
  6632. returnFalse("Stop as no page when emu");
  6633. return;
  6634. }
  6635. if (/^UL$/i.test(pageEle[0].nodeName)) pageEle = pageEle[0].children;
  6636. pageEle = pageEle[parseInt((pageEle.length - 1) / 2)];
  6637. while(pageEle && ((pageEle.scrollHeight && pageEle.scrollHeight < 50) || !pageEle.offsetParent || (!/^IMG$/i.test(pageEle.nodeName) && !pageEle.innerHTML.trim()))) {
  6638. if (pageEle.nextElementSibling) pageEle = pageEle.nextElementSibling;
  6639. else break;
  6640. }
  6641. if (ruleParser.curSiteRule.singleUrl && orgContent != pageEle.innerHTML) {
  6642. orgContent = pageEle.innerHTML;
  6643. if (waitTimes-- > 0) {
  6644. setTimeout(() => {
  6645. checkPage();
  6646. }, waitTime);
  6647. return;
  6648. }
  6649. }
  6650. orgPage = pageEle;
  6651. if (nextLink) {
  6652. if (/^IMG$/i.test(orgPage.nodeName)) {
  6653. if (!ruleParser.curSiteRule.lazyImgSrc) ruleParser.curSiteRule.lazyImgSrc = "0";
  6654. if (orgPage.src) {
  6655. orgContent = orgPage.src;
  6656. } else {
  6657. setTimeout(() => {
  6658. checkPage();
  6659. }, 500);
  6660. return;
  6661. }
  6662. } else {
  6663. orgContent = orgPage.innerHTML;
  6664. }
  6665. preContent = orgContent;
  6666. if (!isVisible(nextLink, iframeDoc.defaultView)) {
  6667. returnFalse("Stop as next hide when emu");
  6668. } else {
  6669. emuClick(nextLink);
  6670. setTimeout(() => {
  6671. checkPage();
  6672. }, 500);
  6673. }
  6674. } else {
  6675. returnFalse("Stop as no next when emu");
  6676. }
  6677. return;
  6678. }
  6679. if (!ruleParser.checkStopSign(nextLink, iframeDoc)) return returnFalse("Stop as stopSign");;
  6680. if (checkTimes++ > 200) {
  6681. returnFalse("Stop as timeout when emu");
  6682. return;
  6683. }
  6684. let eles = ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView, true), checkItem;
  6685. if (eles && eles.length > 0) {
  6686. checkItem = eles;
  6687. if (/^UL$/i.test(eles[0].nodeName)) checkItem = eles[0].children;
  6688. checkItem = checkItem[parseInt((checkItem.length - 1) / 2)];
  6689. while(checkItem && ((checkItem.scrollHeight && checkItem.scrollHeight < 50) || !checkItem.offsetParent || (!/^IMG$/i.test(checkItem.nodeName) && !checkItem.innerHTML.trim()))) {
  6690. if (checkItem.nextElementSibling) checkItem = checkItem.nextElementSibling;
  6691. else break;
  6692. }
  6693. }
  6694. if (!checkItem || (checkEval && !checkEval(iframeDoc))) {
  6695. if (checkEval) checkTimes = 0;
  6696. setTimeout(() => {
  6697. checkPage();
  6698. }, waitTime);
  6699. } else {
  6700. let checkInner;
  6701. if (/^IMG$/i.test(checkItem.nodeName)) {
  6702. if (checkItem.src) {
  6703. checkInner = checkItem.src;
  6704. } else {
  6705. setTimeout(() => {
  6706. checkPage();
  6707. }, waitTime);
  6708. return;
  6709. }
  6710. } else {
  6711. checkInner = checkItem.innerHTML;
  6712. }
  6713. if (orgPage != checkItem || checkInner != preContent) {
  6714. changed = true;
  6715. orgPage = checkItem;
  6716. preContent = checkInner;
  6717. setTimeout(() => {
  6718. checkPage();
  6719. }, waitTime);
  6720. } else if (changed) {
  6721. checkTimes = 0;
  6722. if (orgContent == preContent && (ruleParser.curSiteRule.singleUrl || ruleParser.curSiteRule.stopSame)) {
  6723. returnFalse("Stop as same content");
  6724. } else {
  6725. orgContent = preContent;
  6726. callback(iframeDoc, eles);
  6727. }
  6728. } else {
  6729. if (checkTimes % 10 === 1) {
  6730. if (!nextLink || !nextLink.offsetParent) {
  6731. nextLink = await ruleParser.getNextLink(iframeDoc);
  6732. }
  6733. if (nextLink) {
  6734. emuClick(nextLink);
  6735. }
  6736. }
  6737. setTimeout(() => {
  6738. checkPage();
  6739. }, waitTime);
  6740. }
  6741. }
  6742. }
  6743. if (!emuIframe) {
  6744. let loaded = false;
  6745. emuIframe = document.createElement('iframe');
  6746. emuIframe.name = 'pagetual-iframe';
  6747. let notSetSandbox = typeof ruleParser.curSiteRule.sandbox == 'undefined';
  6748. if (notSetSandbox || ruleParser.curSiteRule.sandbox == true) {
  6749. emuIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  6750. } else if (ruleParser.curSiteRule.sandbox) {
  6751. emuIframe.sandbox = ruleParser.curSiteRule.sandbox;
  6752. }
  6753. emuIframe.width = '100%';
  6754. emuIframe.height = '100%';
  6755. emuIframe.frameBorder = '0';
  6756. 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;';
  6757. emuIframe.addEventListener("load", e => {
  6758. setTimeout(() => {
  6759. try {
  6760. iframeDoc = emuIframe.contentDocument || emuIframe.contentWindow.document;
  6761. } catch(e) {
  6762. if (e.message && e.message.indexOf("cross-origin") != -1 && notSetSandbox && emuIframe.hasAttribute("sandbox")) {
  6763. emuIframe.removeAttribute("sandbox");
  6764. meetCors = true;
  6765. callback(false, false);
  6766. } else {
  6767. returnFalse("Stop as cors");
  6768. }
  6769. return;
  6770. }
  6771. meetCors = false;
  6772. let code = ruleParser.curSiteRule.init;
  6773. if (code) {
  6774. try {
  6775. Function('doc','win','iframe','"use strict";' + code)(iframeDoc, iframeDoc.defaultView, emuIframe);
  6776. } catch(e) {
  6777. debug(e);
  6778. }
  6779. }
  6780. if (loaded) return;
  6781. loaded = true;
  6782. checkPage();
  6783. }, 500);
  6784. });
  6785. if (!lastActiveUrl) lastActiveUrl = location.href;
  6786. emuIframe.src = lastActiveUrl;
  6787. getBody(document).appendChild(emuIframe);
  6788. } else {
  6789. if (emuIframe.src != lastActiveUrl || meetCors) {
  6790. emuIframe.src = lastActiveUrl;
  6791. return;
  6792. }
  6793. checkPage();
  6794. }
  6795. }
  6796.  
  6797. var scrollToResizeInited = false;
  6798. var resizePool = [];
  6799. var scrollingToResize = false;
  6800.  
  6801. function isTouchViewPort(element) {
  6802. const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  6803. const viewHeight = window.innerHeight || document.documentElement.clientHeight;
  6804. const {
  6805. top,
  6806. right,
  6807. bottom,
  6808. left,
  6809. } = element.getBoundingClientRect();
  6810.  
  6811. return (
  6812. top < viewHeight &&
  6813. left < viewWidth &&
  6814. right > 0 &&
  6815. bottom > 0
  6816. );
  6817. }
  6818.  
  6819. function resizeIframe(iframe, frameDoc, pageEle) {
  6820. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  6821. if (ruleParser.curSiteRule.singleUrl || forceState === 2) {
  6822. iframe.style.height = (getBody(frameDoc).scrollHeight || getBody(frameDoc).offsetHeight || 500) + "px";
  6823. iframe.style.minHeight = iframe.style.height;
  6824. iframe.style.width = "100%";
  6825. frameDoc.documentElement.scrollTop = 0;
  6826. frameDoc.documentElement.scrollLeft = 0;
  6827. } else {
  6828. if (pageEle) {
  6829. let fitWidth = ruleParser.curSiteRule.fitWidth !== false;
  6830. let targetElement = pageEle[0];
  6831. if (!targetElement) return;
  6832. if (pageEle.length > 1) {
  6833. targetElement = targetElement.parentNode;
  6834. }
  6835. let scrollHeight = targetElement.scrollHeight || targetElement.offsetHeight || 500;
  6836. iframe.style.height = scrollHeight + "px";
  6837. let scrollTop = 0, scrollLeft = 0;
  6838. getBody(frameDoc).scrollTop = 0;
  6839. getBody(frameDoc).scrollLeft = 0;
  6840. while (targetElement && targetElement.offsetParent) {
  6841. targetElement.offsetParent.scrollTop = targetElement.offsetTop;
  6842. if (targetElement.offsetParent.scrollTop == 0) {
  6843. scrollTop += targetElement.offsetTop;
  6844. }
  6845. if (fitWidth) {
  6846. targetElement.offsetParent.scrollLeft = targetElement.offsetLeft;
  6847. if (targetElement.offsetParent.scrollLeft == 0) {
  6848. scrollLeft += targetElement.offsetLeft;
  6849. }
  6850. }
  6851. targetElement = targetElement.offsetParent;
  6852. }
  6853. frameDoc.documentElement.scrollTop = scrollTop;
  6854. frameDoc.documentElement.scrollLeft = scrollLeft;
  6855. if (frameDoc.documentElement.scrollTop == 0 && frameDoc.documentElement.scrollLeft == 0) {
  6856. getBody(frameDoc).scrollTop += scrollTop;
  6857. getBody(frameDoc).scrollLeft += scrollLeft;
  6858. }
  6859. if (!fitWidth && iframe.style.marginLeft == '0px') {
  6860. iframe.style.width = "100vw";
  6861. var cWidth = document.body.clientWidth || document.documentElement.clientWidth;
  6862. var iWidth = window.innerWidth;
  6863. iframe.style.marginLeft = -iframe.getBoundingClientRect().left - (iWidth - cWidth) / 2 + "px";
  6864. }
  6865. }
  6866. }
  6867. getBody(document).scrollTop = curScroll;
  6868. document.documentElement.scrollTop = curScroll;
  6869. }
  6870.  
  6871. function scrollToResize(e) {
  6872. if (scrollingToResize) return;
  6873. else {
  6874. scrollingToResize = true;
  6875. let resizeHandler = () => {
  6876. let touched = 0;
  6877. for (let i in resizePool) {
  6878. let resizeArr = resizePool[i];
  6879. let iframe = resizeArr[1]();
  6880. if (isTouchViewPort(iframe)) {
  6881. touched++;
  6882. let pageEle = resizeArr[0]();
  6883. let frameDoc = resizeArr[2]();
  6884. resizeIframe(iframe, frameDoc, pageEle);
  6885. } else if (touched) {
  6886. if (touched == 1) {
  6887. let pageEle = resizeArr[0]();
  6888. let frameDoc = resizeArr[2]();
  6889. resizeIframe(iframe, frameDoc, pageEle);
  6890. }
  6891. break;
  6892. } else if (!iframe.parentNode) {
  6893. resizePool.splice(i, 1);
  6894. break;
  6895. }
  6896. }
  6897. };
  6898. setTimeout(() => {
  6899. scrollingToResize = false;
  6900. }, 300);
  6901. resizeHandler();
  6902. }
  6903. }
  6904.  
  6905. function forceIframe(url, callback) {
  6906. url = url.indexOf('=') == -1 ? url.replace(/#[^#]*/,"") : url;
  6907. let curIframe = document.createElement('iframe'), iframeDoc, pageElement = null, isloaded = false, inAction = true;
  6908. let loadedHandler = () => {
  6909. let getPageEle = () => {
  6910. if (ruleParser.curSiteRule.singleUrl) {
  6911. return null;
  6912. } else {
  6913. if (!pageElement || pageElement.length === 0 || !pageElement[0].offsetParent) {
  6914. pageElement = ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView);
  6915. }
  6916. return pageElement;
  6917. }
  6918. };
  6919. resizeIframe(curIframe, iframeDoc, getPageEle());
  6920. if (isloaded) return;
  6921. isloaded = true;
  6922. let getIframe = () => {
  6923. return curIframe;
  6924. };
  6925. let getFrameDoc = () => {
  6926. return iframeDoc;
  6927. };
  6928. ruleParser.insertPage(iframeDoc, [], url, ele => {
  6929. callback(curIframe);
  6930. inAction = false;
  6931. }, true);
  6932. resizePool.push([getPageEle, getIframe, getFrameDoc]);
  6933. };
  6934. let checkIframeTimer = setInterval(() => {
  6935. if (!curIframe.parentNode) {
  6936. clearInterval(checkIframeTimer);
  6937. return isloaded || callback(false);
  6938. }
  6939. }, 500);
  6940. curIframe.name = 'pagetual-iframe';
  6941. curIframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
  6942. curIframe.frameBorder = '0';
  6943. curIframe.scrolling = "no";
  6944. 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;';
  6945. curIframe.addEventListener("load", e => {
  6946. clearInterval(checkIframeTimer);
  6947. if (isPause) return callback(false);
  6948. try {
  6949. iframeDoc = curIframe.contentDocument || curIframe.contentWindow.document;
  6950. } catch(e) {
  6951. debug("Stop as cors");
  6952. isPause = true;
  6953. callback(false);
  6954. return;
  6955. }
  6956. let css = ruleParser.curSiteRule.css || rulesData.customCss;
  6957. if (css) {
  6958. let cssArr = css.split("inIframe:");
  6959. if (cssArr && cssArr.length > 1) {
  6960. let styleEle = iframeDoc.createElement("style");
  6961. styleEle.innerHTML = cssArr[1];
  6962. iframeDoc.head.appendChild(styleEle);
  6963. }
  6964. }
  6965. loadedHandler();
  6966. let code = ruleParser.curSiteRule.init;
  6967. if (code) {
  6968. try {
  6969. Function('doc','win','iframe','"use strict";' + code)(iframeDoc,iframeDoc.defaultView,curIframe);
  6970. } catch(e) {
  6971. debug(e);
  6972. }
  6973. }
  6974. });
  6975. let checkTimes = 0, findPageEle = false;
  6976. let forceRefresh = e => {
  6977. if (inAction || !iframeDoc) return;
  6978. inAction = true;
  6979. let foundNext = () => {
  6980. document.removeEventListener("scroll", forceRefresh);
  6981. }
  6982. setTimeout(async () => {
  6983. inAction = false;
  6984. if (!ruleParser.nextLinkHref && !isPause) {
  6985. checkTimes++;
  6986. await ruleParser.getNextLink(iframeDoc);
  6987. if (ruleParser.nextLinkHref) {
  6988. foundNext();
  6989. if (isLoading) isLoading = false;
  6990. } else if (checkTimes >= 10) {
  6991. foundNext();
  6992. } else if (checkTimes >= 3 && !findPageEle) {
  6993. if (!pageElement) pageElement = ruleParser.getPageElement(iframeDoc, iframeDoc.defaultView);
  6994. if (!pageElement) {
  6995. inAction = true;
  6996. curIframe.contentWindow.location.reload();
  6997. } else {
  6998. findPageEle = true;
  6999. }
  7000. }
  7001. } else {
  7002. foundNext();
  7003. }
  7004. }, 100);
  7005. };
  7006. document.addEventListener("scroll", forceRefresh);
  7007. curIframe.src = url;
  7008. let insert = ruleParser.getInsert();
  7009. let curScroll = getBody(document).scrollTop || document.documentElement.scrollTop;
  7010. if (forceState == 2) {
  7011. getBody(document).appendChild(loadingDiv);
  7012. getBody(document).appendChild(curIframe);
  7013. } else {
  7014. ruleParser.insertElement(curIframe);
  7015. }
  7016. getBody(document).scrollTop = curScroll;
  7017. document.documentElement.scrollTop = curScroll;
  7018.  
  7019. if (!scrollToResizeInited) {
  7020. scrollToResizeInited = true;
  7021. document.addEventListener("scroll", scrollToResize);
  7022. }
  7023. return curIframe;
  7024. }
  7025.  
  7026. let lastScrollTop;
  7027. function loadPageOver() {
  7028. isLoading = false;
  7029. stopScroll = true;
  7030. let dist = distToBottom();
  7031. setTimeout(() => {stopScroll = false}, 300);
  7032. if (loadingDiv.parentNode) {
  7033. loadingDiv.parentNode.removeChild(loadingDiv);
  7034. }
  7035. let rate = (ruleParser.curSiteRule.rate || rulesData.rate || 1);
  7036. if (rate != 1 && !clickMode) {
  7037. setTimeout(() => {
  7038. if (dist < bottomGap) {
  7039. nextPage();
  7040. }
  7041. }, 1);
  7042. }
  7043. }
  7044.  
  7045. function checkAutoLoadNum() {
  7046. if (autoLoadNum >= 0) {
  7047. if (autoLoadNum != 0 && --autoLoadNum == 0) {
  7048. autoLoadNum = -1;
  7049. } else {
  7050. setTimeout(() => nextPage(), 1);
  7051. }
  7052. }
  7053. }
  7054.  
  7055. var tryTimes = 0;
  7056. async function nextPage() {
  7057. if (typeof ruleParser.curSiteRule.manualMode == 'undefined' ? rulesData.manualMode : ruleParser.curSiteRule.manualMode) return;
  7058. if (clickMode) return;
  7059. if (isPause || isLoading || forceState == 1) return;
  7060. if (ruleParser.curSiteRule.delay) {
  7061. try {
  7062. let checkDelay = ((typeof _unsafeWindow.pagetualDelay=='undefined') ? Function('"use strict";' + ruleParser.curSiteRule.delay) : _unsafeWindow.pagetualDelay)();
  7063. if (!checkDelay) return;
  7064. } catch(e) {
  7065. debug(e);
  7066. }
  7067. }
  7068. let nextLink = ruleParser.nextLinkHref;
  7069. if (!nextLink) {
  7070. isLoading = true;
  7071. if (curPage == 1) {
  7072. await ruleParser.getNextLink(document);
  7073. nextLink = ruleParser.nextLinkHref;
  7074. }
  7075. if (!nextLink) {
  7076. if (curPage == 1 && (ruleParser.curSiteRule.pinUrl || tryTimes++ <= 5)) {
  7077. setTimeout(() => {isLoading = false}, 500);
  7078. }
  7079. return;
  7080. }
  7081. isLoading = false;
  7082. }
  7083. let pvGallery = document.querySelector("span.pv-gallery-container");
  7084. if (pvGallery && pvGallery.style.display != "none") return;
  7085. let insert = ruleParser.getInsert();
  7086. if (insert) {
  7087. if (curPage == 1) initView();
  7088. sideController.setup();
  7089. /*if (curPage == 1) {
  7090. window.postMessage({
  7091. insert: geneSelector(ruleParser.curSiteRule.insertPos == 2 ? insert : insert.parentNode, true),
  7092. command: 'pagetual.insert'
  7093. }, '*');
  7094. }*/
  7095. let isJs = ruleParser.curSiteRule.action == 3 || /^(javascript|#)/.test(nextLink.replace(location.href, ""));
  7096. if (!isJs) {
  7097. emuIframe = null;
  7098. lastActiveUrl = nextLink;
  7099. if (location.protocol == "https:" && /^http:/.test(nextLink)) {
  7100. nextLink = nextLink.replace(/^http/, "https");
  7101. }
  7102. }
  7103. isLoading = true;
  7104. if (curPage != 1 || !isJs || !ruleParser.curSiteRule.singleUrl) {
  7105. ruleParser.beginLoading(loadingDiv);
  7106. }
  7107. let sleep = ruleParser.curSiteRule.sleep || 0;
  7108. setTimeout(() => {
  7109. if (ruleParser.curSiteRule.pageElementByJs) {
  7110. var over = eles => {
  7111. if (urlChanged || isPause) {
  7112. loadPageOver();
  7113. return;
  7114. }
  7115. if (eles) {
  7116. ruleParser.insertPage(document, eles, nextLink, () => {
  7117. createPageBar(nextLink);
  7118. checkAutoLoadNum();
  7119. }, true);
  7120. } else {
  7121. debug("Stop as no page when get by js");
  7122. isPause = true;
  7123. loadPageOver();
  7124. }
  7125. };
  7126. try {
  7127. ((typeof _unsafeWindow.pagetualPageElementByJs == 'undefined') ? Function("over", "pageNum",'"use strict";' + ruleParser.curSiteRule.pageElementByJs) : _unsafeWindow.pagetualPageElementByJs)(over, curPage);
  7128. } catch(e) {
  7129. debug(e);
  7130. }
  7131. } else if ((forceState == 2 || ruleParser.curSiteRule.action == 2) && !isJs) {
  7132. forceIframe(nextLink, (iframe) => {
  7133. if (urlChanged || isPause) {
  7134. loadPageOver();
  7135. return;
  7136. }
  7137. let pageBar = createPageBar(nextLink);
  7138. if (pageBar && iframe && iframe.parentNode) iframe.parentNode.insertBefore(pageBar, iframe);
  7139. loadPageOver();
  7140. checkAutoLoadNum();
  7141. });
  7142. } else if ((forceState == 3 || ruleParser.curSiteRule.action == 1) && !isJs) {
  7143. requestFromIframe(nextLink, (doc, eles) => {
  7144. if (urlChanged || isPause) {
  7145. loadPageOver();
  7146. return;
  7147. }
  7148. if (eles) {
  7149. ruleParser.insertPage(doc, eles, nextLink, () => {
  7150. createPageBar(nextLink);
  7151. checkAutoLoadNum();
  7152. }, true);
  7153. } else loadPageOver();
  7154. });
  7155. } else {
  7156. if (!isJs) {
  7157. requestDoc(nextLink, (eles) => {
  7158. if (urlChanged || isPause) {
  7159. loadPageOver();
  7160. return;
  7161. }
  7162. if (eles) {
  7163. createPageBar(nextLink);
  7164. checkAutoLoadNum();
  7165. } else loadPageOver();
  7166. });
  7167. } else {
  7168. emuPage((doc, eles) => {
  7169. if (urlChanged || isPause) {
  7170. loadPageOver();
  7171. return;
  7172. }
  7173. if (eles) {
  7174. ruleParser.insertPage(doc, eles, "", () => {
  7175. createPageBar(nextLink);
  7176. checkAutoLoadNum();
  7177. }, true);
  7178. } else loadPageOver();
  7179. });
  7180. }
  7181. }
  7182. }, sleep);
  7183. }
  7184. }
  7185.  
  7186. function init() {
  7187. if (document.readyState == 'loading' || document.readyState == 'uninitialized') {
  7188. let domReady = e => {
  7189. initRules(() => {
  7190. initPage();
  7191. });
  7192. document.removeEventListener("DOMContentLoaded", domReady, false);
  7193. }
  7194. document.addEventListener("DOMContentLoaded", domReady, false);
  7195. } else {
  7196. initRules(() => {
  7197. initPage();
  7198. });
  7199. }
  7200. }
  7201.  
  7202. function visibilitychangeHandler() {
  7203. document.removeEventListener('visibilitychange', visibilitychangeHandler);
  7204. init();
  7205. }
  7206.  
  7207. setTimeout(() => {
  7208. if (document.hidden) {
  7209. document.addEventListener('visibilitychange', visibilitychangeHandler);
  7210. } else {
  7211. init();
  7212. }
  7213. }, 300);
  7214. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址