東方永頁機

終極自動翻頁 - 加載並拼接下一分頁內容至當前頁尾,智能適配任意網頁

目前為 2023-06-25 提交的版本,檢視 最新版本

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