NodeSeek X

【原NodeSeek增强】自动签到、无缝翻页帖子评论、快捷回复、代码高亮、屏蔽用户、屏蔽帖子、楼主低等级提醒

安装此脚本?
作者推荐脚本

您可能也喜欢NSnapshot

安装此脚本
  1. // ==UserScript==
  2. // @name NodeSeek X
  3. // @namespace http://www.nodeseek.com/
  4. // @version 0.3-beta.12
  5. // @description 【原NodeSeek增强】自动签到、无缝翻页帖子评论、快捷回复、代码高亮、屏蔽用户、屏蔽帖子、楼主低等级提醒
  6. // @author dabao
  7. // @match *://www.nodeseek.com/*
  8. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAQAAADZc7J/AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAACz0lEQVR4Ae3B32tVdQAA8M85u7aVHObmzJVD0+ssiphstLEM62CBlCBEIAYhUoGGD/kiRUo+9CIEElFZgZJFSApBVhCUX2WFrVQKf5Qy26SgdK4pN7eZu+cbtyfJ/gLx83HD9SAhlEyXupiPhUSTeonRfNw1ws2aRJeN5jHcolFhJJ9M8Zj99piDTnv12SjzfzIb9dmrC7Pttt8ykjDVLsu8ZZ1GH1oqeDofJLtJh4fMEw3Y72jlCuEO2+W+sNJFr3vOZ1YIi8NIGA29hDWhGgZDJ2Rt2ZvZSBazmMUsZsPZ1qwVQmcYDNWwhtAbRsNIWJx6WLPDfgxNVkm9nR8hm+XduLba7F9RtcXztmUzyY/YJrUqNPvBYc0eSS3CwXxMl4WG7CarsyEuvU2HOkRNujSw3PosxR6DFurKxx3E/akFohPo0aDfEO61os5LdrtLVWG1TzxokifdiSH9GnTjuGhBqsWE39GOo3kVi8wsmeVW00SJ200zA9r0kFcdQzv+MKElVW/S+L5EE86pmUth3BV/SzCOCUjMVXMWzfsSYybVl1SlSlESkagpuOI1nzshFX1gyAF1UKhJEKOkJFVNXVBv+pJoBK1qBkh86z1/SaR+9o5zEgoDaloxsiSart6F1Bkl83ESHWEKvvEbqZJETaokgSH9hCk6cBLtSs6kDqEb/cZ0K+MnO0X/VdhRGUBZjzH9uA+HUl+a0BvmO+J7bVZSKWz1kehqhfe9oWalNoccDmW9JnyV+toxsy3PK3aY9Gx4gMp567ziV4WawpCXra+MEhZ5xqTtecVycxzXlxA22OK4ZYbt9LjvrM5PkNUp6zVPdNpBv1QKwt126Paxp8zwqXu8kG8pYZdHlT2Rvxo2aVG2ObyYn65UnXLKVULZZrP02ZRfCms1OmAXCSHRYqrLzuZFaDFV6s/8omuERs0Kl/LzITVTvTHDeXTD9eAftAsSYhXYOWUAAAAASUVORK5CYII=
  9. // @require https://s4.zstatic.net/ajax/libs/layui/2.9.9/layui.min.js
  10. // @resource highlightStyle https://s4.zstatic.net/ajax/libs/highlight.js/11.9.0/styles/atom-one-light.min.css
  11. // @resource highlightStyle_dark https://s4.zstatic.net/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css
  12. // @grant GM_xmlhttpRequest
  13. // @grant GM_getValue
  14. // @grant GM_setValue
  15. // @grant GM_deleteValue
  16. // @grant GM_notification
  17. // @grant GM_registerMenuCommand
  18. // @grant GM_unregisterMenuCommand
  19. // @grant GM_getResourceURL
  20. // @grant GM_addElement
  21. // @grant GM_addStyle
  22. // @grant GM_openInTab
  23. // @grant unsafeWindow
  24. // @run-at document-end
  25. // @license GPL-3.0 License
  26. // @supportURL https://www.nodeseek.com/post-36263-1
  27. // @homepageURL https://www.nodeseek.com/post-36263-1
  28. // ==/UserScript==
  29.  
  30. (function () {
  31. 'use strict';
  32.  
  33. const { version, author, name, icon } = GM_info.script;
  34.  
  35. const BASE_URL = "https://www.nodeseek.com";
  36.  
  37. const util = {
  38. clog:(c) => {
  39. console.group(`%c %c [${name}]-v${version} by ${author}`, `background:url(${icon}) center/12px no-repeat;padding:3px`, "");
  40. console.log(c);
  41. console.groupEnd();
  42. },
  43. getValue: (name, defaultValue) => GM_getValue(name, defaultValue),
  44. setValue: (name, value) => GM_setValue(name, value),
  45. sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
  46. addStyle(id, tag, css) {
  47. tag = tag || 'style';
  48. let doc = document, styleDom = doc.head.querySelector(`#${id}`);
  49. if (styleDom) return;
  50. let style = doc.createElement(tag);
  51. style.rel = 'stylesheet';
  52. style.id = id;
  53. tag === 'style' ? style.innerHTML = css : style.href = css;
  54. doc.head.appendChild(style);
  55. },
  56. removeStyle(id,tag){
  57. tag = tag || 'style';
  58. let doc = document, styleDom = doc.head.querySelector(`#${id}`);
  59. if (styleDom) { doc.head.removeChild(styleDom) };
  60. },
  61. getAttrsByPrefix(element, prefix) {
  62. return Array.from(element.attributes).reduce((acc, { name, value }) => {
  63. if (name.startsWith(prefix)) acc[name] = value;
  64. return acc;
  65. }, {});
  66. },
  67. data(element, key, value) {
  68. if (arguments.length < 2) return undefined;
  69. if (value !== undefined) element.dataset[key] = value;
  70. return element.dataset[key];
  71. },
  72. async post(url, data, headers, responseType = 'json') {
  73. return this.fetchData(url, 'POST', data, headers, responseType);
  74. },
  75. async get(url, headers, responseType = 'json') {
  76. return this.fetchData(url, 'GET', null, headers, responseType);
  77. },
  78. async fetchData(url, method='GET', data=null, headers={}, responseType='json') {
  79. const options = {
  80. method,
  81. headers: { 'Content-Type':'application/json',...headers},
  82. body: data ? JSON.stringify(data) : undefined
  83. };
  84. const response = await fetch(url.startsWith("http") ? url : BASE_URL + url, options);
  85. const result = await response[responseType]().catch(() => null);
  86. return response.ok ? result : Promise.reject(result);
  87. },
  88. getCurrentDate() {
  89. const localTimezoneOffset = (new Date()).getTimezoneOffset();
  90. const beijingOffset = 8 * 60;
  91. const beijingTime = new Date(Date.now() + (localTimezoneOffset + beijingOffset) * 60 * 1000);
  92. const timeNow = `${beijingTime.getFullYear()}/${(beijingTime.getMonth() + 1)}/${beijingTime.getDate()}`;
  93. return timeNow;
  94. },
  95. createElement(tagName, options = {}, childrens = [], doc = document, namespace = null) {
  96. if (Array.isArray(options)) {
  97. if (childrens.length !== 0) {
  98. throw new Error("If options is an array, childrens should not be provided.");
  99. }
  100. childrens = options;
  101. options = {};
  102. }
  103.  
  104. const { staticClass = '', dynamicClass = '', attrs = {}, on = {} } = options;
  105.  
  106. const ele = namespace ? doc.createElementNS(namespace, tagName) : doc.createElement(tagName);
  107.  
  108. if (staticClass) {
  109. staticClass.split(' ').forEach(cls => ele.classList.add(cls.trim()));
  110. }
  111. if (dynamicClass) {
  112. dynamicClass.split(' ').forEach(cls => ele.classList.add(cls.trim()));
  113. }
  114.  
  115. Object.entries(attrs).forEach(([key, value]) => {
  116. if (key === 'style' && typeof value === 'object') {
  117. Object.entries(value).forEach(([styleKey, styleValue]) => {
  118. ele.style[styleKey] = styleValue;
  119. });
  120. } else {
  121. if (value !== undefined) ele.setAttribute(key, value);
  122. }
  123. });
  124.  
  125. Object.entries(on).forEach(([event, handler]) => {
  126. ele.addEventListener(event, handler);
  127. });
  128.  
  129. childrens.forEach(child => {
  130. if (typeof child === 'string') {
  131. child = doc.createTextNode(child);
  132. }
  133. ele.appendChild(child);
  134. });
  135.  
  136. return ele;
  137. },
  138. b64DecodeUnicode(str) {
  139. // Going backwards: from bytestream, to percent-encoding, to original string.
  140. return decodeURIComponent(atob(str).split('').map(function (c) {
  141. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  142. }).join(''));
  143. }
  144. };
  145.  
  146. const opts = {
  147. post: {
  148. pathPattern: /^\/(categories\/|page|award|search|$)/,
  149. scrollThreshold: 200,
  150. nextPagerSelector: '.nsk-pager a.pager-next',
  151. postListSelector: 'ul.post-list:not(.topic-carousel-panel)',
  152. topPagerSelector: 'div.nsk-pager.pager-top',
  153. bottomPagerSelector: 'div.nsk-pager.pager-bottom',
  154. },
  155. comment: {
  156. pathPattern: /^\/post-/,
  157. scrollThreshold: 690,
  158. nextPagerSelector: '.nsk-pager a.pager-next',
  159. postListSelector: 'ul.comments',
  160. topPagerSelector: 'div.nsk-pager.post-top-pager',
  161. bottomPagerSelector: 'div.nsk-pager.post-bottom-pager',
  162. },
  163. setting: {
  164. SETTING_SIGN_IN_STATUS: 'setting_sign_in_status',
  165. SETTING_SIGN_IN_LAST_DATE: 'setting_sign_in_last_date',
  166. SETTING_SIGN_IN_IGNORE_DATE: 'setting_sign_in_ignore_date',
  167. SETTING_AUTO_LOADING_STATUS: 'setting_auto_loading_status'
  168. },
  169. settings:{
  170. "version": version,
  171. "sign_in": { "enabled": true, "method": 0, "last_date": "", "ignore_date": "" },
  172. "signin_tips": { "enabled": true },
  173. "re_signin": { "enabled": true },
  174. "auto_jump_external_links": { "enabled": true },
  175. "loading_post": { "enabled": true },
  176. "loading_comment": { "enabled": true },
  177. "quick_comment": { "enabled": true },
  178. "open_post_in_new_tab": { "enabled": false },
  179. "block_members": { "enabled": true },
  180. "block_posts": { "enabled": true,"keywords":[] },
  181. "level_tag": { "enabled": true, "low_lv_alarm":false, "low_lv_max_days":30 },
  182. "code_highlight": { "enabled": true },
  183. "image_slide":{ "enabled":true },
  184. "visited_links":{ "enabled": true, "link_color":"","visited_color":"","dark_link_color":"","dark_visited_color":"" },
  185. "user_card_ext": { "enabled":true }
  186. }
  187. };
  188. layui.use(function () {
  189. const layer = layui.layer;
  190. const dropdown = layui.dropdown;
  191. const message = {
  192. info: (text) => message.__msg(text, { "background-color": "#4D82D6" }),
  193. success: (text) => message.__msg(text, { "background-color": "#57BF57" }),
  194. warning: (text) => message.__msg(text, { "background-color": "#D6A14D" }),
  195. error: (text) => message.__msg(text, { "background-color": "#E1715B" }),
  196. __msg: (text, style) => { let index = layer.msg(text, { offset: 't', area: ['100%', 'auto'], anim: 'slideDown' }); layer.style(index, Object.assign({ opacity: 0.9 }, style)); }
  197. };
  198.  
  199. const Config = {
  200. // 初始化配置数据
  201. initValue() {
  202. const value = [
  203. { name: opts.setting.SETTING_SIGN_IN_STATUS, defaultValue: 0 },
  204. { name: opts.setting.SETTING_SIGN_IN_LAST_DATE, defaultValue: '1753/1/1' },
  205. { name: opts.setting.SETTING_SIGN_IN_IGNORE_DATE, defaultValue: '1753/1/1' },
  206. { name: opts.setting.SETTING_AUTO_LOADING_STATUS, defaultValue: 1 }
  207. ];
  208. this.upgradeConfig();
  209. value.forEach((v) => util.getValue(v.name) === undefined && util.setValue(v.name, v.defaultValue));
  210. },
  211. // 升级配置项
  212. upgradeConfig() {
  213. const upgradeConfItem = (oldConfKey, newConfKey) => {
  214. if (util.getValue(oldConfKey) && util.getValue(newConfKey) === undefined) {
  215. util.clog(`升级配置项 ${oldConfKey} ${newConfKey}`);
  216. util.setValue(newConfKey, util.getValue(oldConfKey));
  217. GM_deleteValue(oldConfKey);
  218. }
  219. };
  220. upgradeConfItem('menu_signInTime', opts.setting.SETTING_SIGN_IN_LAST_DATE);
  221. },
  222. initializeConfig() {
  223. const defaultConfig = opts.settings;
  224. if (!util.getValue('settings')) {
  225. util.setValue('settings', defaultConfig);
  226. return;
  227. }
  228. if(this.getConfig('version')===version) return;
  229. // 从存储中获取当前配置
  230. let storedConfig = util.getValue('settings');
  231.  
  232. // 递归地删除不在默认配置中的项
  233. const cleanDefaults = (stored, defaults) => {
  234. Object.keys(stored).forEach(key => {
  235. if (defaults[key] === undefined) {
  236. delete stored[key]; // 如果默认配置中没有这个键,删除它
  237. } else if (typeof stored[key] === 'object' && stored[key] !== null && !(stored[key] instanceof Array)) {
  238. cleanDefaults(stored[key], defaults[key]); // 递归检查
  239. }
  240. });
  241. };
  242.  
  243. // 递归地将默认配置中的新项合并到存储的配置中
  244. const mergeDefaults = (stored, defaults) => {
  245. Object.keys(defaults).forEach(key => {
  246. if (typeof defaults[key] === 'object' && defaults[key] !== null && !(defaults[key] instanceof Array)) {
  247. if (!stored[key]) stored[key] = {};
  248. mergeDefaults(stored[key], defaults[key]);
  249. } else {
  250. if (stored[key] === undefined) {
  251. stored[key] = defaults[key];
  252. }
  253. }
  254. });
  255. };
  256.  
  257. mergeDefaults(storedConfig, defaultConfig);
  258. //...这里将旧设置项的值迁移到新设置项
  259. cleanDefaults(storedConfig, defaultConfig);
  260. storedConfig.version = version;
  261. util.setValue('settings',storedConfig);
  262. },updateConfig(path, value) {
  263. let config = util.getValue('settings');
  264. let keys = path.split('.');
  265. let lastKey = keys.pop();
  266. let lastObj = keys.reduce((obj, key) => obj[key], config);
  267. lastObj[lastKey] = value;
  268. util.setValue('settings', config);
  269. },getConfig(path) {
  270. let config = GM_getValue('settings');
  271. let keys = path.split('.');
  272. return keys.reduce((obj, key) => obj[key], config);
  273. }
  274. };
  275.  
  276. const FeatureFlags={
  277. isEnabled(featureName) {
  278. if (Config.getConfig(featureName)) {
  279. return Config.getConfig(`${featureName}.enabled`);
  280. } else {
  281. console.error(`Feature '${featureName}' does not exist.`);
  282. return false;
  283. }
  284. }
  285. };
  286.  
  287. const main = {
  288. loginStatus: false,
  289. //检查是否登陆
  290. checkLogin() {
  291. if (unsafeWindow.__config__ && unsafeWindow.__config__.user) {
  292. this.loginStatus = true;
  293. util.clog(`当前登录用户 ${unsafeWindow.__config__.user.member_name} (ID ${unsafeWindow.__config__.user.member_id})`);
  294. }
  295. },
  296. // 自动签到
  297. autoSignIn(rand) {
  298. if(!FeatureFlags.isEnabled('sign_in')) return;
  299.  
  300. if (!this.loginStatus) return
  301. if (util.getValue(opts.setting.SETTING_SIGN_IN_STATUS) === 0) return;
  302.  
  303. rand = rand || (util.getValue(opts.setting.SETTING_SIGN_IN_STATUS) === 1);
  304.  
  305. let timeNow = util.getCurrentDate(),
  306. timeOld = util.getValue(opts.setting.SETTING_SIGN_IN_LAST_DATE);
  307. if (!timeOld || timeOld != timeNow) { // 是新的一天
  308. util.setValue(opts.setting.SETTING_SIGN_IN_LAST_DATE, timeNow); // 写入签到时间以供后续比较
  309. this.signInRequest(rand);
  310. }
  311. },
  312. // 重新签到
  313. reSignIn() {
  314. if (!this.loginStatus) return;
  315. if (util.getValue(opts.setting.SETTING_SIGN_IN_STATUS) === 0) {
  316. unsafeWindow.mscAlert('提示', this.getMenuStateText(this._menus[0], 0) + ' 状态时不支持重新签到!');
  317. return;
  318. }
  319.  
  320. util.setValue(opts.setting.SETTING_SIGN_IN_LAST_DATE, '1753/1/1');
  321. location.reload();
  322. },
  323. addSignTips() {
  324. if(!FeatureFlags.isEnabled('signin_tips')) return;
  325.  
  326. if (!this.loginStatus) return
  327. if (util.getValue(opts.setting.SETTING_SIGN_IN_STATUS) !== 0) return;
  328.  
  329. const timeNow = util.getCurrentDate();
  330. const { SETTING_SIGN_IN_IGNORE_DATE, SETTING_SIGN_IN_LAST_DATE } = opts.setting;
  331. const timeIgnore = util.getValue(SETTING_SIGN_IN_IGNORE_DATE);
  332. const timeOld = util.getValue(SETTING_SIGN_IN_LAST_DATE);
  333.  
  334. if (timeNow === timeIgnore || timeNow === timeOld) return;
  335.  
  336. const _this = this;
  337. let tip = util.createElement("div", { staticClass: 'nsplus-tip' });
  338. let tip_p = util.createElement('p');
  339. tip_p.innerHTML = '今天你还没有签到哦!&emsp;【<a class="sign_in_btn" data-rand="true" href="javascript:;">随机抽个鸡腿</a>】&emsp;【<a class="sign_in_btn" data-rand="false" href="javascript:;">只要5个鸡腿</a>】&emsp;【<a id="sign_in_ignore" href="javascript:;">今天不再提示</a>】';
  340. tip.appendChild(tip_p);
  341. tip.querySelectorAll('.sign_in_btn').forEach(function (item) {
  342. item.addEventListener("click", function (e) {
  343. const rand = util.data(this, 'rand');
  344. _this.signInRequest(rand);
  345. tip.remove();
  346. util.setValue(SETTING_SIGN_IN_LAST_DATE, timeNow); // 写入签到时间以供后续比较
  347. })
  348. });
  349. tip.querySelector('#sign_in_ignore').addEventListener("click", function (e) {
  350. tip.remove();
  351. util.setValue(SETTING_SIGN_IN_IGNORE_DATE, timeNow);
  352. });
  353.  
  354. document.querySelector('#nsk-frame').before(tip);
  355. },
  356. async signInRequest(rand) {
  357. await util.post('/api/attendance?random=' + (rand || false), {}, { "Content-Type": "application/json" }).then(json => {
  358. if (json.success) {
  359. message.success(`签到成功!今天午饭+${json.gain}个鸡腿; 积攒了${json.current}个鸡腿了`);
  360. }
  361. else {
  362. message.info(json.message);
  363. }
  364. }).catch(error => {
  365. message.info(error.message || "发生未知错误");
  366. util.clog(error);
  367. });
  368. util.clog(`[${name}] 签到完成`);
  369. },
  370. is_show_quick_comment: false,
  371. quickComment() {
  372. if (!this.loginStatus || !opts.comment.pathPattern.test(location.pathname)) return;
  373. if (util.getValue(opts.setting.SETTING_AUTO_LOADING_STATUS) === 0) return;
  374.  
  375. const _this = this;
  376.  
  377.  
  378. const onClick = (e) => {
  379. if (_this.is_show_quick_comment) {
  380. return;
  381. }
  382. e.preventDefault();
  383.  
  384. const mdEditor = document.querySelector('.md-editor');
  385. const clientHeight = document.documentElement.clientHeight, clientWidth = document.documentElement.clientWidth;
  386. const mdHeight = mdEditor.clientHeight, mdWidth = mdEditor.clientWidth;
  387. const top = (clientHeight / 2) - (mdHeight / 2), left = (clientWidth / 2) - (mdWidth / 2);
  388. mdEditor.style.cssText = `position: fixed; top: ${top}px; left: ${left}px; margin: 30px 0px; width: 100%; max-width: ${mdWidth}px; z-index: 999;`;
  389. const moveEl = mdEditor.querySelector('.tab-select.window_header');
  390. moveEl.style.cursor = "move";
  391. moveEl.addEventListener('mousedown', startDrag);
  392. addEditorCloseButton();
  393. _this.is_show_quick_comment = true;
  394. };
  395. const commentDiv = document.querySelector('#fast-nav-button-group #back-to-parent').cloneNode(true);
  396. commentDiv.id = 'back-to-comment';
  397. commentDiv.innerHTML = '<svg class="iconpark-icon" style="width: 24px; height: 24px;"><use href="#comments"></use></svg>';
  398. commentDiv.addEventListener("click", onClick);
  399. document.querySelector('#back-to-parent').before(commentDiv);
  400. document.querySelectorAll('.nsk-post .comment-menu,.comment-container .comments').forEach(x=>x.addEventListener("click",(event) =>{ if(!["引用", "回复", "编辑"].includes(event.target.textContent)) return; onClick(event);},true));//使用冒泡法给按钮引用、回复添加事件
  401.  
  402. function addEditorCloseButton() {
  403. const fullScreenToolbar = document.querySelector('#editor-body .window_header > :last-child');
  404. const cloneToolbar = fullScreenToolbar.cloneNode(true);
  405. cloneToolbar.setAttribute('title', '关闭');
  406. cloneToolbar.querySelector('span').classList.replace('i-icon-full-screen-one', 'i-icon-close');
  407. cloneToolbar.querySelector('span').innerHTML = '<svg width="16" height="16" viewBox="0 0 48 48" fill="none"><path d="M8 8L40 40" stroke="currentColor" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"></path><path d="M8 40L40 8" stroke="currentColor" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"></path></svg>';
  408. cloneToolbar.addEventListener("click", function (e) {
  409. const mdEditor = document.querySelector('.md-editor');
  410. mdEditor.style = "";
  411. const moveEl = mdEditor.querySelector('.tab-select.window_header');
  412. moveEl.style.cursor = "";
  413. moveEl.removeEventListener('mousedown', startDrag);
  414.  
  415. this.remove();
  416. _this.is_show_quick_comment = false;
  417. });
  418. fullScreenToolbar.after(cloneToolbar);
  419. }
  420. function startDrag(event) {
  421. if (event.button !== 0) return;
  422.  
  423. const draggableElement = document.querySelector('.md-editor');
  424. const parentMarginTop = parseInt(window.getComputedStyle(draggableElement).marginTop);
  425. const initialX = event.clientX - draggableElement.offsetLeft;
  426. const initialY = event.clientY - draggableElement.offsetTop + parentMarginTop;
  427. document.onmousemove = function (event) {
  428. const newX = event.clientX - initialX;
  429. const newY = event.clientY - initialY;
  430. draggableElement.style.left = newX + 'px';
  431. draggableElement.style.top = newY + 'px';
  432. };
  433. document.onmouseup = function () {
  434. document.onmousemove = null;
  435. document.onmouseup = null;
  436. };
  437. }
  438. },
  439. //自动点击跳转页链接
  440. autoJump() {
  441. document.querySelectorAll('a[href*="/jump?to="]').forEach(link => {
  442. try {
  443. const urlObj = new URL(link.href);
  444. const encodedUrl = urlObj.searchParams.get('to');
  445. if (encodedUrl) {
  446. const decodedUrl = decodeURIComponent(encodedUrl);
  447. link.href = decodedUrl;
  448. }
  449. } catch (e) {
  450. console.error('处理链接时出错:', e);
  451. }
  452. });
  453. if (!/^\/jump/.test(location.pathname)) return;
  454. document.querySelector('.btn').click();
  455. },
  456. blockPost(ele) {
  457. ele = ele || document;
  458. ele.querySelectorAll('.post-title>a[href]').forEach(function (item) {
  459. if (item.textContent.toLowerCase().includes("__keys__")) {
  460. item.closest(".post-list-item").classList.add('blocked-post')
  461. }
  462. });
  463. },
  464. //屏蔽用户
  465. blockMemberDOMInsert() {
  466. if (!this.loginStatus) return;
  467.  
  468. const _this = this;
  469. Array.from(document.querySelectorAll(".post-list .post-list-item,.content-item")).forEach((function (t, n) {
  470. var r = t.querySelector('.avatar-normal');
  471. r.addEventListener("click", (function (n) {
  472. n.preventDefault();
  473. let intervalId = setInterval(async () => {
  474. const userCard = document.querySelector('div.user-card.hover-user-card');
  475. const pmButton = document.querySelector('div.user-card.hover-user-card a.btn');
  476. if (userCard && pmButton) {
  477. clearInterval(intervalId);
  478. const dataVAttrs = util.getAttrsByPrefix(userCard, 'data-v');
  479. const userName = userCard.querySelector('a.Username').textContent;
  480. dataVAttrs.style = "float:left; background-color:rgba(0,0,0,.3)";
  481. const blockBtn = util.createElement("a", {
  482. staticClass: "btn", attrs: dataVAttrs, on: {
  483. click: function (e) {
  484. e.preventDefault();
  485. unsafeWindow.mscConfirm(`确定要屏蔽“${userName}”吗?`, '你可以在本站的 设置=>屏蔽用户 中解除屏蔽', function () { blockMember(userName); })
  486. }
  487. }
  488. }, ["屏蔽"]);
  489. pmButton.after(blockBtn);
  490. }
  491. }, 50);
  492. }))
  493. }))
  494. function blockMember(userName) {
  495. util.post("/api/block-list/add", { "block_member_name": userName }, { "Content-Type": "application/json" }).then(function (data) {
  496. if (data.success) {
  497. let msg = '屏蔽用户【' + userName + '】成功!';
  498. unsafeWindow.mscAlert(msg);
  499. util.clog(msg);
  500. } else {
  501. let msg = '屏蔽用户【' + userName + '】失败!' + data.message;
  502. unsafeWindow.mscAlert(msg);
  503. util.clog(msg);
  504. }
  505. }).catch(function (err) {
  506. util.clog(err);
  507. });
  508. }
  509. },
  510. addImageSlide() {
  511. if (!opts.comment.pathPattern.test(location.pathname)) return;
  512.  
  513. const posts = document.querySelectorAll('article.post-content');
  514. posts.forEach(function (post, i) {
  515. const images = post.querySelectorAll('img:not(.sticker)');
  516. if (images.length === 0) return;
  517.  
  518. images.forEach(function (image, i) {
  519. const newImg = image.cloneNode(true);
  520. image.parentNode.replaceChild(newImg, image);
  521. newImg.addEventListener('click', function (e) {
  522. e.preventDefault();
  523. const imgArr = Array.from(post.querySelectorAll('img:not(.sticker)'));
  524. const clickedIndex = imgArr.indexOf(this);
  525. const photoData = imgArr.map((img, i) => ({ alt: img.alt, pid: i + 1, src: img.src }));
  526. layer.photos({ photos: { "title": "图片预览", "start": clickedIndex, "data": photoData } });
  527. }, true);
  528. });
  529. });
  530. },
  531. addLevelTag() {//添加等级标签
  532. if (!this.loginStatus) return;
  533. if (!opts.comment.pathPattern.test(location.pathname)) return;
  534.  
  535. this.getUserInfo(unsafeWindow.__config__.postData.op.uid).then((user) => {
  536. let warningInfo = '';
  537. const daysDiff = Math.floor((new Date() - new Date(user.created_at)) / (1000 * 60 * 60 * 24));
  538. if (daysDiff < 30) {
  539. warningInfo = `⚠️`;
  540. }
  541. console.log(user);
  542. const span = util.createElement("span", { staticClass: `nsk-badge role-tag user-level user-lv${user.rank}`, on: { mouseenter: function (e) { layer.tips(`注册 <span class="layui-badge">${daysDiff}</span> 天;帖子 ${user.nPost};评论 ${user.nComment}`, this, { tips: 3, time: 0 }); }, mouseleave: function (e) { layer.closeAll(); } } }, [util.createElement("span", [`${warningInfo}Lv ${user.rank}`])]);
  543.  
  544. const authorLink = document.querySelector('#nsk-body .nsk-post .nsk-content-meta-info .author-info>a');
  545. if (authorLink != null) {
  546. authorLink.after(span);
  547. }
  548. });
  549. },
  550. getUserInfo(uid) {
  551. return new Promise((resolve, reject) => {
  552. util.get(`/api/account/getInfo/${uid}`, {}, 'json').then((data) => {
  553. if (!data.success) {
  554. util.clog(data);
  555. return;
  556. }
  557. resolve(data.detail);
  558. }).catch((err) => reject(err));
  559. })
  560. },
  561. userCardEx() {
  562. if (!this.loginStatus) return;
  563. if (!(opts.post.pathPattern.test(location.pathname)|| opts.comment.pathPattern.test(location.pathname))) return;
  564.  
  565. const updateNotificationElement = (element, href, iconHref, text, count) => {
  566. element.querySelector("a").setAttribute("href", `${href}`);
  567. element.querySelector("a > svg > use").setAttribute("href", `${iconHref}`)
  568. element.querySelector("a > :nth-child(2)").textContent = `${text} `;
  569. element.querySelector("a > :last-child").textContent = count;
  570. if (count > 0) {
  571. element.querySelector("a > :last-child").classList.add("notify-count");
  572. }
  573. return element;
  574. };
  575.  
  576. const userCard = document.querySelector(".user-card .user-stat");
  577. const lastElement = userCard.querySelector(".stat-block:first-child > :last-child");
  578. const unViewedCount = unsafeWindow.__config__.user.unViewedCount;
  579.  
  580. if (lastElement.querySelector("a > .notify-count:last-child")) {
  581. lastElement.querySelector("a > .notify-count:last-child").classList.remove("notify-count");
  582. }
  583.  
  584. const atMeElement = lastElement.cloneNode(true);
  585. updateNotificationElement(atMeElement, "/notification#/atMe", "#at-sign", "我", unViewedCount.atMe);
  586. lastElement.after(atMeElement);
  587.  
  588. const msgElement = lastElement.cloneNode(true);
  589. updateNotificationElement(msgElement, "/notification#/message?mode=list", "#envelope-one", "私信", unViewedCount.message);
  590. userCard.querySelector(".stat-block:last-child").append(msgElement);
  591.  
  592. updateNotificationElement(lastElement, "/notification#/reply", "#remind-6nce9p47", "回复", unViewedCount.reply);
  593. },
  594. // 自动翻页
  595. autoLoading() {
  596. if (util.getValue(opts.setting.SETTING_AUTO_LOADING_STATUS) === 0) return;
  597. let opt = {};
  598. if (opts.post.pathPattern.test(location.pathname)) { opt = opts.post; }
  599. else if (opts.comment.pathPattern.test(location.pathname)) { opt = opts.comment; }
  600. else { return; }
  601. let is_requesting = false;
  602. let _this = this;
  603. this.windowScroll(function (direction, e) {
  604. if (direction === 'down') { // 下滑才准备翻页
  605. let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
  606. if (document.documentElement.scrollHeight <= document.documentElement.clientHeight + scrollTop + opt.scrollThreshold && !is_requesting) {
  607. if (!document.querySelector(opt.nextPagerSelector)) return;
  608. let nextUrl = document.querySelector(opt.nextPagerSelector).attributes.href.value;
  609. is_requesting = true;
  610. util.get(nextUrl, {}, 'text').then(function (data) {
  611. let doc = new DOMParser().parseFromString(data, "text/html");
  612. _this.blockPost(doc);//过滤帖子
  613. if (opts.comment.pathPattern.test(location.pathname)){
  614. // 取加载页的评论数据追加到原评论数据
  615. let el = doc.getElementById('temp-script')
  616. let jsonText = el.textContent;
  617. if (jsonText) {
  618. let conf = JSON.parse(util.b64DecodeUnicode(jsonText))
  619. unsafeWindow.__config__.postData.comments.push(...conf.postData.comments);
  620. }
  621. }
  622. document.querySelector(opt.postListSelector).append(...doc.querySelector(opt.postListSelector).childNodes);
  623. document.querySelector(opt.topPagerSelector).innerHTML = doc.querySelector(opt.topPagerSelector).innerHTML;
  624. document.querySelector(opt.bottomPagerSelector).innerHTML = doc.querySelector(opt.bottomPagerSelector).innerHTML;
  625. history.pushState(null, null, nextUrl);
  626. // 评论菜单条
  627. if (opts.comment.pathPattern.test(location.pathname)){
  628. const vue = document.querySelector('.comment-menu').__vue__;
  629. Array.from(document.querySelectorAll(".content-item")).forEach(function (t,e) {
  630. var n = t.querySelector(".comment-menu-mount");
  631. if(!n) return;
  632. let o = new vue.$root.constructor(vue.$options);
  633. o.setIndex(e);
  634. o.$mount(n);
  635. });
  636. }
  637. is_requesting = false;
  638. }).catch(function (err) {
  639. is_requesting = false;
  640. util.clog(err);
  641. });
  642. }
  643. }
  644. });
  645. },
  646. // 滚动条事件
  647. windowScroll(fn1) {
  648. let beforeScrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop,
  649. fn = fn1 || function () { };
  650. setTimeout(function () { // 延时执行,避免刚载入到页面就触发翻页事件
  651. window.addEventListener('scroll', function (e) {
  652. const afterScrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop,
  653. delta = afterScrollTop - beforeScrollTop;
  654. if (delta == 0) return false;
  655. fn(delta > 0 ? 'down' : 'up', e);
  656. beforeScrollTop = afterScrollTop;
  657. }, false);
  658. }, 1000)
  659. },
  660. async switchOpenPostInNewTab(){
  661. try {
  662. const db = await unsafeWindow.IdbManager.get('nodeseekIDB');
  663. const store = db.transaction(['Preference'], 'readwrite').objectStore('Preference');
  664. const result = await new Promise((resolve, reject) => {
  665. const request = store.get('configuration');
  666. request.onsuccess = () => resolve(request.result);
  667. request.onerror = () => reject("查询失败");
  668. });
  669.  
  670. result.openPostInNewPage = !result.openPostInNewPage;
  671.  
  672. await new Promise((resolve, reject) => {
  673. const request = store.put(result);
  674. request.onsuccess = resolve;
  675. request.onerror = () => reject("保存失败");
  676. }).then(()=>{ unsafeWindow.mscAlert(`已${result.openPostInNewPage?'开启':'关闭'}新标签页打开链接`)});
  677.  
  678. console.log(result);
  679. } catch (error) {
  680. console.error(error);
  681. }
  682. },
  683. history: ()=>{
  684. const STORAGE_KEY = 'nsx_browsing_history';
  685. const PAGE_SIZE = 10;
  686. let saveLimit = 'all';
  687.  
  688. const POST_URL_PATTERN = /^https:\/\/www\.nodeseek\.com\/post-(\d+)-\d+.*$/;
  689. const getCurrentTime = () => layui.util.toDateString(new Date(),"yyyy-MM-ddTHH:mm:ss.SSS");
  690.  
  691. const getBrowsingHistory = () => {
  692. return JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
  693. };
  694.  
  695. const saveBrowsingHistory = (history) => {
  696. if (saveLimit !== 'all') {
  697. history = history.slice(-saveLimit);
  698. }
  699. localStorage.setItem(STORAGE_KEY, JSON.stringify(history));
  700. };
  701.  
  702. const addOrUpdateHistory = (url, title) => {
  703. const match = url.match(POST_URL_PATTERN);
  704. if (!match) return; // 只保存匹配的帖子记录
  705.  
  706. const normalizedUrl = `https://www.nodeseek.com/post-${match[1]}-1`; // 只判断第1页,即不区分页码
  707. const history = getBrowsingHistory();
  708. const index = history.findIndex(item => item.url === normalizedUrl);
  709. const entry = { url: normalizedUrl, title, time: getCurrentTime() };
  710. if (index > -1) {
  711. history[index] = entry;
  712. }
  713. else {
  714. history.push(entry);
  715. }
  716. saveBrowsingHistory(history);
  717. };
  718.  
  719. const getHistory = (page = 1) => {
  720. const history = getBrowsingHistory();
  721. const totalPages = Math.ceil(history.length / PAGE_SIZE);
  722. const sortedData = history.sort((a, b) => new Date(b.time) - new Date(a.time));
  723. if(page===0) return sortedData;
  724. return sortedData.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);
  725. };
  726.  
  727. const showHistory = (page = 1) => {
  728. const history = getBrowsingHistory();
  729. const totalPages = Math.ceil(history.length / PAGE_SIZE);
  730. const pageHistory = history.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);
  731. console.clear();
  732. console.log(`浏览历史 - ${page} 页,共 ${totalPages} 页`);
  733. pageHistory.forEach((item, i) => {
  734. console.log(`${(page - 1) * PAGE_SIZE + i + 1}. [${item.time}] ${item.title} - ${item.url}`);
  735. });
  736. if (page < totalPages) {
  737. console.log(`输入 showHistory(${page + 1}) 查看下一页`);
  738. }
  739. };
  740.  
  741. const setSaveLimit = (limit) => {
  742. if (typeof limit === 'number' && limit > 0 || limit === 'all') {
  743. saveLimit = limit;
  744. console.log(`保存限制已设置为:${limit === 'all' ? '全部' : `最近 ${limit} 条`}`);
  745. }
  746. else {
  747. console.error('无效的保存限制。请输入正整数或 "all"');
  748. }
  749. };
  750.  
  751. const injectDom=()=>{
  752. const svg = util.createElement("svg", { staticClass: "iconpark-icon", attrs: { "style": "width: 17px;height: 17px;" }},[ util.createElement("use",{ attrs: { "href": "#history"} }, [], document, "http://www.w3.org/2000/svg") ], document, "http://www.w3.org/2000/svg");
  753. const originalSwitcher = document.querySelector('#nsk-head .color-theme-switcher');
  754. if (originalSwitcher) {
  755. const svgWrap = originalSwitcher.cloneNode();
  756. svgWrap.classList.replace('color-theme-switcher', 'history-dropdown-on');
  757. svgWrap.setAttribute('lay-options', '{trigger:"hover"}');
  758.  
  759. // 判断是否为移动端(li 元素)并移除 SVG 的 style 属性
  760. if (originalSwitcher.tagName.toLowerCase() === 'li') {
  761. svg.removeAttribute('style');
  762. }
  763.  
  764. svgWrap.appendChild(svg);
  765. originalSwitcher.insertAdjacentElement('beforebegin', svgWrap);
  766. }
  767.  
  768. const history=getHistory(0);
  769. const maxLength=20;
  770. // 按天分组
  771. const grouped = history.reduce((result, item, i) => {
  772. const date = item.time.split("T")[0];
  773. if (!result[date]) {
  774. result[date] = [];
  775. }
  776. const truncatedTitle = item.title.length > maxLength
  777. ? item.title.slice(0, maxLength) + "..."
  778. : item.title;
  779. result[date].push({
  780. id: 1000+i+1,
  781. title: `${truncatedTitle}(${layui.util.toDateString(item.time,'HH:mm')})`,
  782. href: item.url,
  783. time: item.time
  784. });
  785. return result;
  786. }, {});
  787.  
  788. // 转换为目标结构
  789. const result = Object.entries(grouped).map(([day, items], index) => ({
  790. id: index + 1,
  791. title: day,
  792. type: "group",
  793. child: items // 将子项包裹在数组中
  794. }));
  795.  
  796. console.log(result);
  797.  
  798. dropdown.render({
  799. elem: '.history-dropdown-on',
  800. // trigger: 'click' // trigger 已配置在元素 `lay-options` 属性上
  801. data: result,
  802. style: 'width: 370px; height: 200px;'
  803. });
  804. };
  805.  
  806. addOrUpdateHistory(window.location.href, document.title);
  807. injectDom();
  808. },
  809. initInstantPage:() => {
  810. const prefetchedUrls = new Set(); // 用于存储已经尝试预加载的 URL
  811. let prefetcher = document.createElement('link');
  812. prefetcher.rel = 'prefetch';
  813.  
  814. document.body.addEventListener('mouseover', (event) => {
  815. const target = event.target.closest('a');
  816.  
  817. if (!target || !target.href || target.hasAttribute('data-no-instant')) {
  818. return;
  819. }
  820.  
  821. const href = target.href;
  822.  
  823. if (!href.startsWith('https://www.nodeseek.com/post-')) {
  824. return;
  825. }
  826.  
  827. if (prefetchedUrls.has(href)) {
  828. console.log('跳过已预加载链接:', href);
  829. return;
  830. }
  831.  
  832. setTimeout(() => {
  833. if (target.matches(':hover')) {
  834. prefetcher.href = href;
  835. document.head.appendChild(prefetcher);
  836. prefetchedUrls.add(href);
  837. console.log('预加载链接已启动:', href);
  838. }
  839. }, 65); // 65毫秒延迟
  840. });
  841. },
  842. switchMultiState(stateName, states) {//多态顺序切换
  843. let currState = util.getValue(stateName);
  844. currState = (currState + 1) % states.length;
  845. util.setValue(stateName, currState);
  846. this.registerMenus();
  847. },
  848. getMenuStateText(menu, stateVal) {
  849. return `${menu.states[stateVal].s1} ${menu.text}(${menu.states[stateVal].s2})`;
  850. },
  851. _menus: [
  852. { name: opts.setting.SETTING_SIGN_IN_STATUS, callback: (name, states) => main.switchMultiState(name, states), accessKey: '', text: '自动签到', states: [{ s1: '❌', s2: '关闭' }, { s1: '🎲', s2: '随机🍗' }, { s1: '📌', s2: '5个🍗' }] },
  853. { name: 're_sign_in', callback: (name, states) => main.reSignIn(), accessKey: '', text: '🔂 重新签到', states: [] },
  854. { name: opts.setting.SETTING_AUTO_LOADING_STATUS, callback: (name, states) => main.switchMultiState(name, states), accessKey: '', text: '无缝加载', states: [{ s1: '❌', s2: '关闭' }, { s1: '✅', s2: '开启' }] },
  855. { name: 'open_post_in_new_tab', callback: (name, states) => main.switchOpenPostInNewTab(), accessKey: '', text: '切换新标签页打开链接', states: []},
  856. { name: 'advanced_settings', callback: (name, states) => main.advancedSettings(), accessKey: '', text: '⚙️ 高级设置', states: [] },
  857. { name: 'feedback', callback: (name, states) => GM_openInTab('https://greasyfork.org/zh-CN/scripts/479426/feedback', { active: true, insert: true, setParent: true }), accessKey: '', text: '💬 反馈 & 建议', states: [] }
  858. ],
  859. _menuIds: [],
  860. registerMenus() {
  861. this._menuIds.forEach(function (id) {
  862. GM_unregisterMenuCommand(id);
  863. });
  864. this._menuIds = [];
  865.  
  866. const _this = this;
  867. this._menus.forEach(function (menu) {
  868. let k = menu.text;
  869. if (menu.states.length > 0) {
  870. k = _this.getMenuStateText(menu, util.getValue(menu.name));
  871. }
  872. let autoClose = menu.hasOwnProperty('autoClose') ? menu.autoClose : true;
  873. let menuId = GM_registerMenuCommand(k, function () { menu.callback(menu.name, menu.states) }, { autoClose: autoClose });
  874. menuId = menuId || k;
  875. _this._menuIds.push(menuId);
  876. });
  877. },
  878. advancedSettings() {
  879. let layerWidth = layui.device().mobile ? '100%' : '620px';
  880. layer.open({
  881. type: 1,
  882. offset: 'r',
  883. anim: 'slideLeft', // 从右往左
  884. area: [layerWidth, '100%'],
  885. scrollbar: false,
  886. shade: 0.1,
  887. shadeClose: false,
  888. btn: ["保存设置"],
  889. btnAlign: 'r',
  890. title: 'NodeSeek X 设置',
  891. id: 'setting-layer-direction-r',
  892. content: `<div class="layui-row" style="display:flex;height:100%">
  893. <div class="layui-panel layui-col-xs3 layui-col-sm3 layui-col-md3" id="demo-menu">
  894. <ul class="layui-menu" lay-filter="demo"></ul>
  895. </div>
  896. <div class="layui-col-xs9 layui-col-sm9 layui-col-md9" style="overflow-y: auto; padding-left: 10px" id="demo-content">
  897. <fieldset id="group1" class="layui-elem-field layui-field-title">
  898. <legend>基本设置</legend>
  899. </fieldset>
  900. <div style="height: 500px;">Content for Group 1</div>
  901. <fieldset id="group2" class="layui-elem-field layui-field-title">
  902. <legend>扩展设置</legend>
  903. </fieldset>
  904. <div style="height: 500px;">Content for Group 2</div>
  905. <fieldset id="group3" class="layui-elem-field layui-field-title">
  906. <legend>实验设置</legend>
  907. </fieldset>
  908. <div style="height: 500px;">Content for Group 3</div>
  909. </div>
  910. </div>
  911. <script>
  912. document.querySelectorAll('#demo-content > fieldset').forEach(function (el, i) {
  913. let li = document.createElement('li');
  914. if (i === 0) li.classList = 'layui-menu-item-checked';
  915. let div = document.createElement('div');
  916. div.classList = 'layui-menu-body-title';
  917. let a = document.createElement('a');
  918. a.href = '#' + el.id;
  919. a.textContent = el.textContent;
  920. a.addEventListener('click', aClick);
  921. li.append(div);
  922. div.append(a);
  923. document.querySelector('#demo-menu>ul').append(li);
  924. });
  925. const docContent = document.querySelector('#demo-content');
  926. docContent.addEventListener('scroll', function (e) {
  927. var scrollPos = docContent.scrollTop;
  928. console.log(scrollPos);
  929. docContent.querySelectorAll('fieldset').forEach(function (el) {
  930. var topPos = el.offsetTop - 10;
  931. if (scrollPos >= topPos) {
  932. var id = el.getAttribute('id');
  933. document.querySelectorAll('.layui-menu > li.layui-menu-item-checked').forEach(function (navItem) {
  934. navItem.classList.remove('layui-menu-item-checked');
  935. });
  936. var navItem = document.querySelector('.layui-menu > li a[href="#' + id + '"]').closest('li');
  937. navItem.classList.add('layui-menu-item-checked');
  938. }
  939. });
  940. });
  941. function aClick(e) {
  942. e.preventDefault();
  943. var id = this.getAttribute('href');
  944. var target = document.querySelector(id);
  945. docContent.scrollTo({
  946. top: target.offsetTop - 10,
  947. // behavior: 'smooth'
  948. });
  949. }
  950. <\/script>`,
  951. yes: function(index, layero, that){
  952. layer.msg('111');
  953. layer.close(index); // 关闭弹层
  954. }
  955. });
  956. },
  957. addCodeHighlight() {
  958. const codes = document.querySelectorAll(".post-content pre code");
  959. if (codes) {
  960. codes.forEach(function (code) {
  961. const copyBtn = util.createElement("span", { staticClass: "copy-code", attrs: { title: "复制代码" }, on: { click: copyCode } }, [util.createElement("svg", { staticClass: 'iconpark-icon' }, [util.createElement("use", { attrs: { href: "#copy" } }, [], document, "http://www.w3.org/2000/svg")], document, "http://www.w3.org/2000/svg")]);
  962. code.after(copyBtn);
  963. });
  964. }
  965. function copyCode(e) {
  966. const pre = this.closest('pre');
  967. const selection = window.getSelection();
  968. const range = document.createRange();
  969. range.selectNodeContents(pre.querySelector("code"));
  970. selection.removeAllRanges();
  971. selection.addRange(range);
  972. document.execCommand('copy');
  973. selection.removeAllRanges();
  974. updateCopyButton(this);
  975. layer.tips(`复制成功`, this, { tips: 4, time: 1000 })
  976. }
  977. function updateCopyButton(ele) {
  978. ele.querySelector("use").setAttribute("href", "#check");
  979. util.sleep(1000).then(() => ele.querySelector("use").setAttribute("href", "#copy"));
  980. }
  981. },
  982. addRunCode(){
  983. // 首先添加弹出层样式到页面头部
  984. const modalStyle = document.createElement('style');
  985. modalStyle.textContent = `
  986. .html-preview-modal {
  987. display: none;
  988. position: fixed;
  989. z-index: 1000;
  990. left: 0;
  991. top: 0;
  992. width: 100%;
  993. height: 100%;
  994. overflow: auto;
  995. background-color: rgba(0, 0, 0, 0.5);
  996. }
  997.  
  998. .html-preview-modal-content {
  999. position: relative;
  1000. background-color: #fefefe;
  1001. margin: 5% auto;
  1002. padding: 20px;
  1003. border: 1px solid #888;
  1004. width: 80%;
  1005. max-width: 900px;
  1006. border-radius: 5px;
  1007. box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  1008. }
  1009.  
  1010. .html-preview-close {
  1011. color: #aaa;
  1012. float: right;
  1013. font-size: 28px;
  1014. font-weight: bold;
  1015. cursor: pointer;
  1016. margin-top: -5px;
  1017. }
  1018.  
  1019. .html-preview-close:hover,
  1020. .html-preview-close:focus {
  1021. color: black;
  1022. text-decoration: none;
  1023. }
  1024.  
  1025. .html-preview-iframe {
  1026. width: 100%;
  1027. min-height: 600px;
  1028. border: 1px solid #ddd;
  1029. margin-top: 15px;
  1030. background-color: white;
  1031. }
  1032.  
  1033. .run-html-btn {
  1034. position: absolute;
  1035. right: .5em;
  1036. bottom: 1.5em;
  1037. margin-top: 10px;
  1038. padding: 8px 12px;
  1039. background-color: #4CAF50;
  1040. color: white;
  1041. border: none;
  1042. border-radius: 4px;
  1043. cursor: pointer;
  1044. }
  1045.  
  1046. .run-html-btn:hover {
  1047. background-color: #45a049;
  1048. }
  1049. `;
  1050. document.head.appendChild(modalStyle);
  1051.  
  1052. // 创建全局模态框元素
  1053. const modal = document.createElement('div');
  1054. modal.className = 'html-preview-modal';
  1055. modal.innerHTML = `
  1056. <div class="html-preview-modal-content">
  1057. <span class="html-preview-close">&times;</span>
  1058. <h3>HTML 预览</h3>
  1059. <div id="iframe-container"></div>
  1060. </div>
  1061. `;
  1062. document.body.appendChild(modal);
  1063.  
  1064. // 获取模态框元素
  1065. const previewModal = document.querySelector('.html-preview-modal');
  1066. const closeBtn = document.querySelector('.html-preview-close');
  1067. const iframeContainer = document.querySelector('#iframe-container');
  1068.  
  1069. // 关闭并销毁预览内容的函数
  1070. function closeAndDestroyPreview() {
  1071. // 隐藏模态框
  1072. previewModal.style.display = "none";
  1073.  
  1074. // 销毁iframe内容
  1075. iframeContainer.innerHTML = '';
  1076. }
  1077.  
  1078. // 关闭按钮事件
  1079. closeBtn.onclick = closeAndDestroyPreview;
  1080.  
  1081. // 点击模态框外部关闭
  1082. window.onclick = function(event) {
  1083. if (event.target == previewModal) {
  1084. closeAndDestroyPreview();
  1085. }
  1086. };
  1087.  
  1088. // 预览HTML内容的函数
  1089. function previewHtmlContent(content) {
  1090. // 清空容器(销毁之前的内容)
  1091. iframeContainer.innerHTML = '';
  1092.  
  1093. // 创建一个新的iframe
  1094. const iframe = document.createElement('iframe');
  1095. iframe.className = 'html-preview-iframe';
  1096. iframe.sandbox = 'allow-scripts allow-same-origin allow-popups';
  1097. iframeContainer.appendChild(iframe);
  1098.  
  1099. // 显示模态框
  1100. previewModal.style.display = "block";
  1101.  
  1102. // 使用srcdoc属性设置内容
  1103. iframe.srcdoc = content;
  1104.  
  1105. // 调整iframe高度
  1106. iframe.onload = function() {
  1107. try {
  1108. const height = iframe.contentDocument.body.scrollHeight;
  1109. iframe.style.height = (height + 30) + 'px';
  1110.  
  1111. // 添加事件监听,允许iframe内容动态改变高度
  1112. const resizeObserver = new ResizeObserver(() => {
  1113. try {
  1114. const newHeight = iframe.contentDocument.body.scrollHeight;
  1115. iframe.style.height = (newHeight + 30) + 'px';
  1116. } catch (e) {
  1117. console.log("无法访问iframe内容高度");
  1118. }
  1119. });
  1120.  
  1121. try {
  1122. resizeObserver.observe(iframe.contentDocument.body);
  1123. } catch (e) {
  1124. console.log("无法观察iframe内容变化");
  1125. }
  1126. } catch (e) {
  1127. console.log("无法访问iframe内容");
  1128. iframe.style.height = '400px'; // 默认高度
  1129. }
  1130. };
  1131. }
  1132.  
  1133. // 查找所有HTML代码块并添加运行按钮
  1134. document.querySelectorAll('pre code.language-html').forEach((codeBlock) => {
  1135. const pre = codeBlock.parentNode;
  1136.  
  1137. // 创建运行按钮
  1138. const runButton = document.createElement('button');
  1139. runButton.textContent = '运行代码';
  1140. runButton.className = 'run-html-btn';
  1141.  
  1142. // 运行按钮点击事件
  1143. runButton.onclick = function() {
  1144. // 获取当前代码块的内容
  1145. const codeContent = codeBlock.textContent;
  1146.  
  1147. // 预览该内容
  1148. previewHtmlContent(codeContent);
  1149. };
  1150.  
  1151. // 将按钮添加到代码块后面
  1152. pre.appendChild(runButton);
  1153. });
  1154.  
  1155. // 添加键盘事件监听器 - 按ESC键关闭模态框
  1156. document.addEventListener('keydown', function(event) {
  1157. if (event.key === 'Escape' && previewModal.style.display === 'block') {
  1158. closeAndDestroyPreview();
  1159. }
  1160. });
  1161. },
  1162. addPluginStyle() {
  1163. let style = `
  1164. .nsplus-tip { background-color: rgba(255, 217, 0, 0.8); border: 0px solid black; padding: 10px; text-align: center;animation: blink 5s cubic-bezier(.68,.05,.46,.96) infinite;}
  1165. /* @keyframes blink{ 0%{background-color: red;} 25%{background-color: yellow;} 50%{background-color: blue;} 75%{background-color: green;} 100%{background-color: red;} } */
  1166. .nsplus-tip p,.nsplus-tip p a { color: #f00 }
  1167. .nsplus-tip p a:hover {color: #0ff}
  1168. #back-to-comment{display:flex;}
  1169. #fast-nav-button-group .nav-item-btn:nth-last-child(4){bottom:120px;}
  1170.  
  1171. header div.history-dropdown-on { color: var(--link-hover-color); cursor: pointer; padding: 0 5px; position: absolute; right: 50px}
  1172.  
  1173. body.light-layout .post-list .post-title a:visited{color:#681da8}
  1174. body.dark-layout .post-list .post-title a:visited {color:#999}
  1175. .role-tag.user-level.user-lv0 {background-color: rgb(199 194 194); border: 1px solid rgb(199 194 194); color: #fafafa;}
  1176. .role-tag.user-level.user-lv1 {background-color: #ff9400; border: 1px solid #ff9400; color: #fafafa;}
  1177. .role-tag.user-level.user-lv2 {background-color: #ff9400; border: 1px solid #ff9400; color: #fafafa;}
  1178. .role-tag.user-level.user-lv3 {background-color: #ff3a55; border: 1px solid #ff3a55; color: #fafafa;}
  1179. .role-tag.user-level.user-lv4 {background-color: #ff3a55; border: 1px solid #ff3a55; color: #fafafa;}
  1180. .role-tag.user-level.user-lv5 {background-color: #de00ff; border: 1px solid #de00ff; color: #fafafa;}
  1181. .role-tag.user-level.user-lv6 {background-color: #de00ff; border: 1px solid #de00ff; color: #fafafa;}
  1182. .role-tag.user-level.user-lv7 {background-color: #ff0000; border: 1px solid #ff0000; color: #fafafa;}
  1183. .role-tag.user-level.user-lv8 {background-color: #3478f7; border: 1px solid #3478f7; color: #fafafa;}
  1184.  
  1185. .post-content pre { position: relative; }
  1186. .post-content pre span.copy-code { position: absolute; right: .5em; top: .5em; cursor: pointer;color: #c1c7cd; }
  1187. .post-content pre .iconpark-icon {width:16px;height:16px;margin:3px;}
  1188. .post-content pre .iconpark-icon:hover {color:var(--link-hover-color)}
  1189. .dark-layout .post-content pre code.hljs { padding: 1em !important; }
  1190. `;
  1191. if (document.head) {
  1192. util.addStyle('nsplus-style', 'style', style);
  1193. util.addStyle('layui-style', 'link', 'https://s.cfn.pp.ua/layui/2.9.9/css/layui.css');
  1194. util.addStyle('hightlight-style', 'link', GM_getResourceURL("highlightStyle"));
  1195. }
  1196. },
  1197. addPluginScript() {
  1198. GM_addElement(document.body, 'script', {
  1199. src: 'https://s4.zstatic.net/ajax/libs/highlight.js/11.9.0/highlight.min.js'
  1200. });
  1201. GM_addElement(document.body, 'script', {
  1202. textContent: 'window.onload = function(){hljs.highlightAll();}'
  1203. });
  1204. GM_addElement(document.body, "script", { textContent: `!function(e){var t,n,d,o,i,a,r='<svg><symbol id="envelope-one" viewBox="0 0 48 48" fill="none"><path stroke-linejoin="round" stroke-linecap="round" stroke-width="4" stroke="currentColor" d="M36 16V8H4v24h8" data-follow-stroke="currentColor"/><path stroke-linejoin="round" stroke-width="4" stroke="currentColor" d="M12 40h32V16H12v24Z" data-follow-stroke="currentColor"/><path stroke-linejoin="round" stroke-linecap="round" stroke-width="4" stroke="currentColor" d="m12 16 16 12 16-12" data-follow-stroke="currentColor"/><path stroke-linejoin="round" stroke-linecap="round" stroke-width="4" stroke="currentColor" d="M32 16H12v15" data-follow-stroke="currentColor"/><path stroke-linejoin="round" stroke-linecap="round" stroke-width="4" stroke="currentColor" d="M44 31V16H24" data-follow-stroke="currentColor"/></symbol><symbol id="at-sign" viewBox="0 0 48 48" fill="none"><path stroke-linejoin="round" stroke-linecap="round" stroke-width="4" stroke="currentColor" d="M44 24c0-11.046-8.954-20-20-20S4 12.954 4 24s8.954 20 20 20v0c4.989 0 9.55-1.827 13.054-4.847" data-follow-stroke="currentColor"/><path stroke-linejoin="round" stroke-width="4" stroke="currentColor" d="M24 32a8 8 0 1 0 0-16 8 8 0 0 0 0 16Z" data-follow-stroke="currentColor"/><path stroke-linejoin="round" stroke-linecap="round" stroke-width="4" stroke="currentColor" d="M32 24a6 6 0 0 0 6 6v0a6 6 0 0 0 6-6m-12 1v-9" data-follow-stroke="currentColor"/></symbol><symbol id="copy" viewBox="0 0 48 48" fill="none"><path stroke-linejoin="round" stroke-linecap="round" stroke-width="4" stroke="currentColor" d="M13 12.432v-4.62A2.813 2.813 0 0 1 15.813 5h24.374A2.813 2.813 0 0 1 43 7.813v24.375A2.813 2.813 0 0 1 40.187 35h-4.67" data-follow-stroke="currentColor"/><path stroke-linejoin="round" stroke-width="4" stroke="currentColor" d="M32.188 13H7.811A2.813 2.813 0 0 0 5 15.813v24.374A2.813 2.813 0 0 0 7.813 43h24.375A2.813 2.813 0 0 0 35 40.187V15.814A2.813 2.813 0 0 0 32.187 13Z" data-follow-stroke="currentColor"/></symbol><symbol id="history" viewBox="0 0 48 48" fill="none"><path stroke-linejoin="round" stroke-linecap="round" stroke-width="4" stroke="currentColor" d="M5.818 6.727V14h7.273" data-follow-stroke="currentColor"/><path stroke-linejoin="round" stroke-linecap="round" stroke-width="4" stroke="currentColor" d="M4 24c0 11.046 8.954 20 20 20v0c11.046 0 20-8.954 20-20S35.046 4 24 4c-7.402 0-13.865 4.021-17.323 9.998" data-follow-stroke="currentColor"/><path stroke-linejoin="round" stroke-linecap="round" stroke-width="4" stroke="currentColor" d="m24.005 12-.001 12.009 8.48 8.48" data-follow-stroke="currentColor"/></symbol></svg>';function c(){i||(i=!0,d())}t=function(){var e,t,n;(n=document.createElement("div")).innerHTML=r,r=null,(t=n.getElementsByTagName("svg")[0])&&(t.setAttribute("aria-hidden","true"),t.style.position="absolute",t.style.width=0,t.style.height=0,t.style.overflow="hidden",e=t,(n=document.body).firstChild?(t=n.firstChild).parentNode.insertBefore(e,t):n.appendChild(e))},document.addEventListener?["complete","loaded","interactive"].indexOf(document.readyState)>-1?setTimeout(t,0):(n=function(){document.removeEventListener("DOMContentLoaded",n,!1),t()},document.addEventListener("DOMContentLoaded",n,!1)):document.attachEvent&&(d=t,o=e.document,i=!1,(a=function(){try{o.documentElement.doScroll("left")}catch(e){return void setTimeout(a,50)}c()})(),o.onreadystatechange=function(){"complete"==o.readyState&&(o.onreadystatechange=null,c())})}(window);` });
  1205. },
  1206. darkMode(){
  1207. // 选择要监视的目标元素(body元素)
  1208. const targetNode = document.querySelector('body');
  1209. // 进入页面时判断是否是深色模式
  1210. if(targetNode.classList.contains('dark-layout')){
  1211. util.addStyle('layuicss-theme-dark','link','https://s.cfn.pp.ua/layui/theme-dark/2.9.7/css/layui-theme-dark.css');
  1212. util.removeStyle('hightlight-style');
  1213. util.addStyle('hightlight-style', 'link', GM_getResourceURL("highlightStyle_dark"));
  1214. }
  1215.  
  1216. // 配置MutationObserver的选项
  1217. const observerConfig = {
  1218. attributes: true, // 监视属性变化
  1219. attributeFilter: ['class'], // 只监视类属性
  1220. };
  1221.  
  1222. // 创建一个新的MutationObserver,并指定触发变化时的回调函数
  1223. const observer = new MutationObserver((mutationsList, observer) => {
  1224. for(let mutation of mutationsList) {
  1225. if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
  1226. if(targetNode.classList.contains('dark-layout')){
  1227. util.addStyle('layuicss-theme-dark','link','https://s.cfn.pp.ua/layui/theme-dark/2.9.7/css/layui-theme-dark.css');
  1228. util.removeStyle('hightlight-style');
  1229. util.addStyle('hightlight-style', 'link', GM_getResourceURL("highlightStyle_dark"));
  1230. }else{
  1231. util.removeStyle('layuicss-theme-dark');
  1232. util.removeStyle('hightlight-style');
  1233. util.addStyle('hightlight-style', 'link', GM_getResourceURL("highlightStyle"));
  1234. }
  1235. }
  1236. }
  1237. });
  1238.  
  1239. // 使用给定的配置选项开始观察目标节点
  1240. observer.observe(targetNode, observerConfig);
  1241. },
  1242. init() {
  1243. Config.initValue();
  1244. Config.initializeConfig();
  1245. this.addPluginStyle();
  1246. this.checkLogin();
  1247. const codeMirrorElement = document.querySelector('.CodeMirror');
  1248. if (codeMirrorElement) {
  1249. const codeMirrorInstance = codeMirrorElement.CodeMirror;
  1250. if (codeMirrorInstance) {
  1251. let btnSubmit = document.querySelector('.md-editor button.submit.btn.focus-visible');
  1252. btnSubmit.innerText=btnSubmit.innerText+'(Ctrl+Enter)';
  1253. codeMirrorInstance.addKeyMap({"Ctrl-Enter":function(cm){ btnSubmit.click();}});
  1254. }
  1255. }
  1256. this.autoSignIn();//自动签到
  1257. this.addSignTips();//签到提示
  1258. this.autoJump();//自动点击跳转页
  1259. this.autoLoading();//无缝加载帖子和评论
  1260. this.blockMemberDOMInsert();//屏蔽用户
  1261. this.blockPost();//屏蔽帖子
  1262. this.quickComment();//快捷评论
  1263. this.addLevelTag();//添加等级标签
  1264. this.userCardEx();//用户卡片扩展
  1265. this.registerMenus();
  1266. this.addPluginScript();
  1267. this.addCodeHighlight();
  1268. this.addRunCode();
  1269. this.addImageSlide();
  1270. this.darkMode();
  1271. this.history();
  1272. this.initInstantPage();
  1273. }
  1274. }
  1275. main.init();
  1276. });
  1277. })();