东方永页机

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

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