东方永页机

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

当前为 2023-03-31 提交的版本,查看 最新版本

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

QingJ © 2025

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