知乎增强

移除登录弹窗、屏蔽首页视频、默认收起回答、快捷收起回答/评论(左键两侧)、快捷回到顶部(右键两侧)、屏蔽用户、屏蔽关键词、移除高亮链接、屏蔽盐选内容、净化搜索热门、净化标题消息、展开问题描述、显示问题作者、置顶显示时间、完整问题时间、区分问题文章、直达问题按钮、默认高清原图、默认站外直链

当前为 2022-06-05 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name 知乎增强
  3. // @name:zh-CN 知乎增强
  4. // @name:zh-TW 知乎增強
  5. // @name:en Zhihu enhancement
  6. // @version 2.0.9
  7. // @author X.I.U
  8. // @description 移除登录弹窗、屏蔽首页视频、默认收起回答、快捷收起回答/评论(左键两侧)、快捷回到顶部(右键两侧)、屏蔽用户、屏蔽关键词、移除高亮链接、屏蔽盐选内容、净化搜索热门、净化标题消息、展开问题描述、显示问题作者、置顶显示时间、完整问题时间、区分问题文章、直达问题按钮、默认高清原图、默认站外直链
  9. // @description:zh-TW 移除登錄彈窗、屏蔽首頁視頻、默認收起回答、快捷收起回答/評論、快捷回到頂部、屏蔽用戶、屏蔽關鍵詞、移除高亮鏈接、屏蔽鹽選內容、淨化搜索熱門、淨化標題消息、置頂顯示時間、完整問題時間、區分問題文章、默認高清原圖、默認站外直鏈...
  10. // @description:en A more personalized Zhihu experience~
  11. // @match *://www.zhihu.com/*
  12. // @match *://zhuanlan.zhihu.com/*
  13. // @icon https://static.zhihu.com/heifetz/favicon.ico
  14. // @grant GM_xmlhttpRequest
  15. // @grant GM_registerMenuCommand
  16. // @grant GM_unregisterMenuCommand
  17. // @grant GM_openInTab
  18. // @grant GM_getValue
  19. // @grant GM_setValue
  20. // @grant GM_notification
  21. // @grant GM_info
  22. // @grant window.onurlchange
  23. // @license GPL-3.0 License
  24. // @run-at document-end
  25. // @namespace https://greasyfork.org/scripts/4122051
  26. // @supportURL https://github.com/XIU2/UserScript
  27. // @homepageURL https://github.com/XIU2/UserScript
  28. // ==/UserScript==
  29.  
  30. 'use strict';
  31. var menu_ALL = [
  32. ['menu_defaultCollapsedAnswer', '默认收起回答', '默认收起回答', true],
  33. ['menu_collapsedAnswer', '一键收起回答', '一键收起回答', true],
  34. ['menu_collapsedNowAnswer', '快捷收起回答/评论 (点击两侧空白处)', '快捷收起回答/评论', true],
  35. ['menu_backToTop', '快捷回到顶部 (右键两侧空白处)', '快捷回到顶部', true],
  36. ['menu_blockUsers', '屏蔽指定用户', '屏蔽指定用户', true],
  37. ['menu_customBlockUsers', '自定义屏蔽用户', '自定义屏蔽用户', ['故事档案局', '盐选推荐', '盐选科普', '盐选成长计划', '知乎盐选会员', '知乎盐选创作者', '盐选心理', '盐选健康必修课', '盐选奇妙物语', '盐选生活馆', '盐选职场', '盐选文学甄选', '盐选作者小管家', '盐选博物馆', '盐选点金', '盐选测评室', '盐选科技前沿', '盐选会员精品']],
  38. ['menu_blockKeywords', '屏蔽指定关键词', '屏蔽指定关键词', true],
  39. ['menu_customBlockKeywords', '自定义屏蔽关键词', '自定义屏蔽关键词', []],
  40. ['menu_blockType', '屏蔽指定类别 (视频/文章等)', '勾选 = 屏蔽该类别的信息流', ''],
  41. ['menu_blockTypeVideo', '视频 [首页、搜索页、问题页]', '视频(首页、搜索页、问题页)', true],
  42. ['menu_blockTypeArticle', '文章 [首页、搜索页]', '文章(首页、搜索页)', false],
  43. ['menu_blockTypeTopic', '话题 [搜索页]', '话题(搜索页)', false],
  44. ['menu_blockTypeSearch', '杂志文章、相关搜索等 [搜索页]', '相关搜索、杂志等(搜索页)', false],
  45. ['menu_blockYanXuan', '屏蔽盐选内容', '屏蔽盐选内容', false],
  46. ['menu_cleanSearch', '净化搜索热门 (默认搜索词及热门搜索)', '净化搜索热门', false],
  47. ['menu_cleanTitles', '净化标题消息 (标题中的私信/消息)', '净化标题提醒', false],
  48. ['menu_questionRichTextMore', '展开问题描述', '展开问题描述', false],
  49. ['menu_publishTop', '置顶显示时间', '置顶显示时间', true],
  50. ['menu_typeTips', '区分问题文章', '区分问题文章', true],
  51. ['menu_toQuestion', '直达问题按钮', '直达问题按钮', true]
  52. ], menu_ID = [];
  53. for (let i=0;i<menu_ALL.length;i++){ // 如果读取到的值为 null 就写入默认值
  54. if (GM_getValue(menu_ALL[i][0]) == null){GM_setValue(menu_ALL[i][0], menu_ALL[i][3])};
  55. }
  56. registerMenuCommand();
  57.  
  58. // 注册脚本菜单
  59. function registerMenuCommand() {
  60. if (menu_ID.length > menu_ALL.length){ // 如果菜单ID数组多于菜单数组,说明不是首次添加菜单,需要卸载所有脚本菜单
  61. for (let i=0;i<menu_ID.length;i++){
  62. GM_unregisterMenuCommand(menu_ID[i]);
  63. }
  64. }
  65. for (let i=0;i<menu_ALL.length;i++){ // 循环注册脚本菜单
  66. menu_ALL[i][3] = GM_getValue(menu_ALL[i][0]);
  67. if (menu_ALL[i][0] === 'menu_customBlockUsers') {
  68. if (menu_value('menu_blockUsers')) menu_ID[i] = GM_registerMenuCommand(`#️⃣ ${menu_ALL[i][1]}`, function(){customBlockUsers()});
  69. } else if (menu_ALL[i][0] === 'menu_customBlockKeywords') {
  70. if (menu_value('menu_blockKeywords')) menu_ID[i] = GM_registerMenuCommand(`#️⃣ ${menu_ALL[i][1]}`, function(){customBlockKeywords()});
  71. } else if (menu_ALL[i][0] === 'menu_blockType') {
  72. menu_ID[i] = GM_registerMenuCommand(`#️⃣ ${menu_ALL[i][1]}`, function(){menu_setting('checkbox', menu_ALL[i][1], menu_ALL[i][2], true, [menu_ALL[i+1], menu_ALL[i+2], menu_ALL[i+3], menu_ALL[i+4]])});
  73. } else if (menu_ALL[i][0] != 'menu_blockTypeVideo' && menu_ALL[i][0] != 'menu_blockTypeArticle' && menu_ALL[i][0] != 'menu_blockTypeTopic' && menu_ALL[i][0] != 'menu_blockTypeSearch') {
  74. menu_ID[i] = GM_registerMenuCommand(`${menu_ALL[i][3]?'✅':'❌'} ${menu_ALL[i][1]}`, function(){menu_switch(`${menu_ALL[i][3]}`,`${menu_ALL[i][0]}`,`${menu_ALL[i][2]}`)});
  75. }
  76. }
  77. menu_ID[menu_ID.length] = GM_registerMenuCommand('💬 反馈 & 建议', function () {window.GM_openInTab('https://github.com/XIU2/UserScript#xiu2userscript', {active: true,insert: true,setParent: true});window.GM_openInTab('https://greasyfork.org/zh-CN/scripts/419081/feedback', {active: true,insert: true,setParent: true});});
  78. }
  79.  
  80.  
  81. // 菜单开关
  82. function menu_switch(menu_status, Name, Tips) {
  83. if (menu_status == 'true'){
  84. GM_setValue(`${Name}`, false);
  85. GM_notification({text: `已关闭 [${Tips}] 功能\n(点击刷新网页后生效)`, timeout: 3500, onclick: function(){location.reload();}});
  86. }else{
  87. GM_setValue(`${Name}`, true);
  88. GM_notification({text: `已开启 [${Tips}] 功能\n(点击刷新网页后生效)`, timeout: 3500, onclick: function(){location.reload();}});
  89. }
  90. registerMenuCommand(); // 重新注册脚本菜单
  91. };
  92.  
  93.  
  94. // 返回菜单值
  95. function menu_value(menuName) {
  96. for (let menu of menu_ALL) {
  97. if (menu[0] == menuName) {
  98. return menu[3]
  99. }
  100. }
  101. }
  102.  
  103.  
  104. // 脚本设置
  105. function menu_setting(type, title, tips, line, menu) {
  106. let _br = '', _html = `<style class="zhihuE_SettingStyle">.zhihuE_SettingRoot {position: absolute;top: 50%;left: 50%;-webkit-transform: translate(-50%, -50%);-moz-transform: translate(-50%, -50%);-ms-transform: translate(-50%, -50%);-o-transform: translate(-50%, -50%);transform: translate(-50%, -50%);width: auto;min-width: 400px;max-width: 600px;height: auto;min-height: 150px;max-height: 400px;color: #535353;background-color: #fff;border-radius: 3px;}
  107. .zhihuE_SettingBackdrop_1 {position: fixed;top: 0;right: 0;bottom: 0;left: 0;z-index: 203;display: -webkit-box;display: -ms-flexbox;display: flex;-webkit-box-orient: vertical;-webkit-box-direction: normal;-ms-flex-direction: column;flex-direction: column;-webkit-box-pack: center;-ms-flex-pack: center;justify-content: center;overflow-x: hidden;overflow-y: auto;-webkit-transition: opacity .3s ease-out;transition: opacity .3s ease-out;}
  108. .zhihuE_SettingBackdrop_2 {position: absolute;top: 0;right: 0;bottom: 0;left: 0;z-index: 0;background-color: rgba(18,18,18,.65);-webkit-transition: background-color .3s ease-out;transition: background-color .3s ease-out;}
  109. .zhihuE_SettingRoot .zhihuE_SettingHeader {padding: 10px 20px;color: #fff;font-weight: bold;background-color: #3994ff;border-radius: 3px 3px 0 0;}
  110. .zhihuE_SettingRoot .zhihuE_SettingMain {padding: 10px 20px;border-radius: 0 0 3px 3px;}
  111. .zhihuE_SettingHeader span {float: right;cursor: pointer;}
  112. .zhihuE_SettingMain input {margin: 10px 6px 10px 0;cursor: pointer;vertical-align:middle}
  113. .zhihuE_SettingMain label {margin-right: 20px;user-select: none;cursor: pointer;vertical-align:middle}
  114. .zhihuE_SettingMain hr {border: 0.5px solid #f4f4f4;}
  115. [data-theme="dark"] .zhihuE_SettingRoot {color: #adbac7;background-color: #343A44;}
  116. [data-theme="dark"] .zhihuE_SettingHeader {color: #d0d0d0;background-color: #2D333B;}
  117. [data-theme="dark"] .zhihuE_SettingMain hr {border: 0.5px solid #2d333b;}</style>
  118. <div class="zhihuE_SettingBackdrop_1"><div class="zhihuE_SettingBackdrop_2"></div><div class="zhihuE_SettingRoot">
  119. <div class="zhihuE_SettingHeader">${title}<span class="zhihuE_SettingClose" title="点击关闭"><svg class="Zi Zi--Close Modal-closeIcon" fill="currentColor" viewBox="0 0 24 24" width="24" height="24"><path d="M13.486 12l5.208-5.207a1.048 1.048 0 0 0-.006-1.483 1.046 1.046 0 0 0-1.482-.005L12 10.514 6.793 5.305a1.048 1.048 0 0 0-1.483.005 1.046 1.046 0 0 0-.005 1.483L10.514 12l-5.208 5.207a1.048 1.048 0 0 0 .006 1.483 1.046 1.046 0 0 0 1.482.005L12 13.486l5.207 5.208a1.048 1.048 0 0 0 1.483-.006 1.046 1.046 0 0 0 .005-1.482L13.486 12z" fill-rule="evenodd"></path></svg></span></div>
  120. <div class="zhihuE_SettingMain"><p>${tips}</p><hr>`
  121. if (line) _br = '<br>'
  122. for (let i=0; i<menu.length; i++) {
  123. if (GM_getValue(menu[i][0])) {
  124. _html += `<label><input name="zhihuE_Setting" type="checkbox" value="${menu[i][0]}" checked="checked">${menu[i][1]}</label>${_br}`
  125. } else {
  126. _html += `<label><input name="zhihuE_Setting" type="checkbox" value="${menu[i][0]}">${menu[i][1]}</label>${_br}`
  127. }
  128. }
  129. _html += `</div></div></div>`
  130. document.body.insertAdjacentHTML('beforeend', _html); // 插入网页末尾
  131. setTimeout(function() { // 延迟 100 毫秒,避免太快
  132. // 关闭按钮 点击事件
  133. document.querySelector('.zhihuE_SettingClose').onclick = function(){this.parentElement.parentElement.parentElement.remove();document.querySelector('.zhihuE_SettingStyle').remove();}
  134. // 点击周围空白处 = 点击关闭按钮
  135. document.querySelector('.zhihuE_SettingBackdrop_2').onclick = function(event){if (event.target == this) {document.querySelector('.zhihuE_SettingClose').click();};}
  136. // 复选框 点击事件
  137. document.getElementsByName('zhihuE_Setting').forEach(function (checkBox) {
  138. checkBox.addEventListener('click', function(){if (this.checked) {GM_setValue(this.value, true);} else {GM_setValue(this.value, false);}});
  139. })
  140. }, 100)
  141. }
  142.  
  143.  
  144. // 添加收起回答观察器
  145. function getCollapsedAnswerObserver() {
  146. if (!window._collapsedAnswerObserver) {
  147. const observer = new MutationObserver(mutations => {
  148. for (const mutation of mutations) {
  149. if (mutation.target.hasAttribute('script-collapsed')) return
  150. // 短的回答
  151. if (mutation.target.classList.contains('RichContent')) {
  152. for (const addedNode of mutation.addedNodes) {
  153. if (addedNode.nodeType != Node.ELEMENT_NODE) continue
  154. if (addedNode.className != 'RichContent-inner') continue
  155. if (addedNode.offsetHeight < 400) break
  156. //console.log('111',addedNode, addedNode.classList, addedNode.classList.contains('RichContent-inner'), addedNode.offsetHeight, addedNode.textContent.length)
  157. const button = mutation.target.querySelector('.ContentItem-actions.Sticky [data-zop-retract-question]');
  158. if (button) {
  159. mutation.target.setAttribute('script-collapsed', '');
  160. button.click();
  161. return
  162. }
  163. }
  164. // 长的回答
  165. } else if (mutation.target.tagName === 'DIV' && !mutation.target.style.cssText && !mutation.target.className) {
  166. if (mutation.target.parentElement.hasAttribute('script-collapsed')) return
  167. //console.log('222',mutation.target, mutation.target.querySelector('.ContentItem-actions.Sticky [data-zop-retract-question]'))
  168. const button = mutation.target.querySelector('.ContentItem-actions.Sticky [data-zop-retract-question]');
  169. if (button) {
  170. mutation.target.parentElement.setAttribute('script-collapsed', '');
  171. button.click();
  172. return
  173. }
  174. }
  175. }
  176. })
  177.  
  178. observer.start = function() {
  179. if (!this._active) {
  180. this.observe(document, { childList: true, subtree: true });
  181. this._active = true;
  182. }
  183. }
  184. observer.end = function() {
  185. if (this._active) {
  186. this.disconnect();
  187. }
  188. }
  189.  
  190. window.addEventListener('urlchange', function() {
  191. observer[location.href.indexOf('/answer/') === -1 ? 'start' : 'end']();
  192. })
  193. window._collapsedAnswerObserver = observer;
  194. }
  195. return window._collapsedAnswerObserver
  196. }
  197.  
  198.  
  199. // 默认收起回答
  200. function defaultCollapsedAnswer() {
  201. if (!menu_value('menu_defaultCollapsedAnswer')) return
  202. const observer = getCollapsedAnswerObserver();
  203. if (location.href.indexOf('/answer/') === -1) {
  204. observer.start();
  205. }
  206. }
  207.  
  208.  
  209. // 一键收起回答(全部)
  210. function collapsedAnswer() {
  211. if (!menu_value('menu_collapsedAnswer')) return
  212. //console.log('1111', document.querySelector('.CornerAnimayedFlex'))
  213. if (document.querySelector('.CornerAnimayedFlex') && !document.getElementById('collapsed-button')) {
  214. //console.log('2222')
  215. document.head.appendChild(document.createElement('style')).textContent = '.CornerButton{margin-bottom:8px !important;}.CornerButtons{bottom:45px !important;}';
  216. document.querySelector('.CornerAnimayedFlex').insertAdjacentHTML('afterBegin', '<button id="collapsed-button" data-tooltip="收起全部回答" data-tooltip-position="left" data-tooltip-will-hide-on-click="false" aria-label="收起全部回答" type="button" class="Button CornerButton Button--plain"><svg class="ContentItem-arrowIcon is-active" aria-label="收起全部回答" fill="currentColor" viewBox="0 0 24 24" width="24" height="24"><path d="M16.036 19.59a1 1 0 0 1-.997.995H9.032a.996.996 0 0 1-.997-.996v-7.005H5.03c-1.1 0-1.36-.633-.578-1.416L11.33 4.29a1.003 1.003 0 0 1 1.412 0l6.878 6.88c.782.78.523 1.415-.58 1.415h-3.004v7.005z"></path></svg></button>');
  217. document.getElementById('collapsed-button').onclick = function () {
  218. if (location.pathname === '/' || location.pathname === '/hot' || location.pathname === '/follow') {
  219. document.querySelectorAll('.ContentItem-rightButton').forEach(function (el) {
  220. if (el.hasAttribute('data-zop-retract-question')) {
  221. el.click()
  222. }
  223. });
  224. } else {
  225. document.querySelectorAll('[script-collapsed]').forEach(function(scriptCollapsed) {
  226. scriptCollapsed.querySelectorAll('.ContentItem-actions [data-zop-retract-question], .ContentItem-actions.Sticky [data-zop-retract-question]').forEach(function(button) {
  227. button.click();
  228. })
  229. })
  230. document.querySelectorAll('.RichContent:not([script-collapsed]) .ContentItem-actions.Sticky [data-zop-retract-question]').forEach(function(button) {
  231. let el = button.parentElement;
  232. while (!el.classList.contains('RichContent')) {
  233. el = el.parentElement;
  234. }
  235. if (el) {
  236. el.setAttribute('script-collapsed', '');
  237. }
  238. button.click();
  239. })
  240. const observer = getCollapsedAnswerObserver();
  241. observer.start();
  242. if (!menu_value('menu_defaultCollapsedAnswer') && !observer._disconnectListener) {
  243. window.addEventListener('urlchange', function() {
  244. observer.end();
  245. window._collapsedAnswerObserver = null;
  246. })
  247. observer._disconnectListener = true;
  248. }
  249. }
  250. }
  251. }
  252. }
  253.  
  254.  
  255. // 收起当前回答、评论(监听点击事件,点击网页两侧空白处)
  256. function collapsedNowAnswer(selectors) {
  257. backToTop(selectors) // 快捷回到顶部
  258. if (!menu_value('menu_collapsedNowAnswer')) return
  259. document.querySelector(selectors).onclick = function(event){
  260. if (event.target == this) {
  261. // 下面这段主要是 [收起回答],顺便 [收起评论](如果展开了的话)
  262. let rightButton = document.querySelector('.ContentItem-actions.Sticky.RichContent-actions.is-fixed.is-bottom')
  263. // 悬浮在底部的 [收起回答](此时正在浏览回答内容 [中间区域])
  264. if (rightButton) {
  265. // 固定的 [收起评论](先看看是否展开评论)
  266. let commentCollapseButton = rightButton.querySelector('button.Button.ContentItem-action.Button--plain.Button--withIcon.Button--withLabel:first-of-type')
  267. //console.log('111')
  268. if (commentCollapseButton && commentCollapseButton.textContent.indexOf('收起评论') > -1) commentCollapseButton.click();
  269. // 再去收起回答
  270. rightButton = rightButton.querySelector('.ContentItem-rightButton[data-zop-retract-question]')
  271. //console.log('222')
  272. if (rightButton) rightButton.click();
  273. // 固定在回答底部的 [收起回答](此时正在浏览回答内容 [尾部区域])
  274. } else {
  275. let answerCollapseButton_ = false;
  276. for (let el of document.querySelectorAll('.ContentItem-rightButton[data-zop-retract-question]')) { // 遍历所有回答底部的 [收起] 按钮
  277. if (isElementInViewport(el)) { // 判断该 [收起] 按钮是否在可视区域内
  278. // 固定的 [收起评论](先看看是否展开评论,即存在 [收起评论] 按钮)
  279. let commentCollapseButton = el.parentNode.querySelector('button.Button.ContentItem-action.Button--plain.Button--withIcon.Button--withLabel:first-of-type')
  280. // 如果展开了评论,就收起评论
  281. //console.log('333')
  282. if (commentCollapseButton && commentCollapseButton.textContent.indexOf('收起评论') > -1) commentCollapseButton.click();
  283. //console.log('444')
  284. el.click() // 再去收起回答
  285. answerCollapseButton_ = true; // 如果找到并点击收起了,就没必要执行下面的代码了(可视区域中没有 [收起回答] 时)
  286. break
  287. }
  288. }
  289. // 针对完全看不到 [收起回答] 按钮时(如 [头部区域],以及部分明明很长却不显示悬浮横条的回答)
  290. if (!answerCollapseButton_) {
  291. for (let el of document.querySelectorAll('.List-item, .Card.AnswerCard')) { // 遍历所有回答主体元素
  292. if (isElementInViewport_(el)) { // 判断该回答是否在可视区域内
  293. // 固定的 [收起评论](先看看是否展开评论,即存在 [收起评论] 按钮)
  294. let commentCollapseButton = el.parentNode.querySelector('button.Button.ContentItem-action.Button--plain.Button--withIcon.Button--withLabel:first-of-type')
  295. // 如果展开了评论,就收起评论
  296. //console.log('555')
  297. if (commentCollapseButton && commentCollapseButton.textContent.indexOf('收起评论') > -1) commentCollapseButton.click();
  298. let answerCollapseButton__ = el.querySelector('.ContentItem-rightButton[data-zop-retract-question]');
  299. //console.log('666')
  300. if (answerCollapseButton__) answerCollapseButton__.click() // 再去收起回答
  301. break
  302. }
  303. }
  304. }
  305. }
  306.  
  307. // 下面这段只针对 [收起评论](如果展开了的话)
  308. let commentCollapseButton_ = false, commentCollapseButton__ = false;
  309. // 悬浮的 [收起评论](此时正在浏览评论内容 [中间区域])
  310. let commentCollapseButton = document.querySelector('.CommentCollapseButton')
  311. if (commentCollapseButton) {
  312. //console.log('777')
  313. commentCollapseButton.click();
  314. } else { // 固定的 [收起评论](此时正在浏览评论内容 [头部区域])
  315. let commentCollapseButton_1 = document.querySelectorAll('.ContentItem-actions > button.Button.ContentItem-action.Button--plain.Button--withIcon.Button--withLabel:first-of-type, .ContentItem-action > button.Button.Button--plain.Button--withIcon.Button--withLabel:first-of-type')
  316. if (commentCollapseButton_1.length > 0) {
  317. for (let el of commentCollapseButton_1) {
  318. if (el.textContent.indexOf('收起评论') > -1) {
  319. if (isElementInViewport(el)) {
  320. //console.log('888')
  321. el.click()
  322. commentCollapseButton_ = true // 如果找到并点击了,就没必要执行下面的代码了(可视区域中没有 [收起评论] 时)
  323. break
  324. }
  325. }
  326. }
  327. }
  328. if (commentCollapseButton_ == false) { // 可视区域中没有 [收起评论] 时(此时正在浏览评论内容 [头部区域] + [尾部区域](不上不下的,既看不到固定的 [收起评论] 又看不到悬浮的 [收起评论])),需要判断可视区域中是否存在评论元素
  329. let commentCollapseButton_1 = document.querySelectorAll('.NestComment')
  330. if (commentCollapseButton_1.length > 0) {
  331. for (let el of commentCollapseButton_1) {
  332. if (isElementInViewport(el)) {
  333. let commentCollapseButton = findParentElement(el, 'ContentItem AnswerItem').querySelector('.ContentItem-actions > button.Button.ContentItem-action.Button--plain.Button--withIcon.Button--withLabel:first-of-type')
  334. if (commentCollapseButton.textContent.indexOf('收起评论') > -1) {
  335. //console.log('999')
  336. commentCollapseButton.click()
  337. commentCollapseButton__ = true // 如果找到并点击了,就没必要执行下面的代码了(可视区域中没有 评论元素 时)
  338. break
  339. }
  340. }
  341. }
  342. }
  343. if (commentCollapseButton__ == false) { // 如果上面的都没找到,那么就尝试寻找评论末尾的 [评论回复框]
  344. let commentCollapseButton_2 = document.querySelectorAll('.CommentsV2-footer.CommentEditorV2--normal .CommentEditorV2-inputWrap')
  345. if (commentCollapseButton_2.length > 0) {
  346. for (let el of commentCollapseButton_2) {
  347. if (isElementInViewport(el)) {
  348. let commentCollapseButton = findParentElement(el, 'ContentItem AnswerItem').querySelector('.ContentItem-actions > button.Button.ContentItem-action.Button--plain.Button--withIcon.Button--withLabel:first-of-type')
  349. //console.log(commentCollapseButton)
  350. if (commentCollapseButton.textContent.indexOf('收起评论') > -1) {
  351. //console.log('101010')
  352. commentCollapseButton.click()
  353. break
  354. }
  355. }
  356. }
  357. }
  358. }
  359. }
  360. }
  361. }
  362. }
  363. }
  364.  
  365.  
  366. // 回到顶部(监听点击事件,鼠标右键点击网页两侧空白处)
  367. function backToTop(selectors) {
  368. if (!menu_value('menu_backToTop')) return
  369. document.querySelector(selectors).oncontextmenu = function(event){
  370. if (event.target == this) {
  371. event.preventDefault();
  372. window.scrollTo(0,0)
  373. }
  374. }
  375. }
  376.  
  377.  
  378. //获取元素是否在可视区域(完全可见)
  379. function isElementInViewport(el) {
  380. let rect = el.getBoundingClientRect();
  381. return (
  382. rect.top >= 0 &&
  383. rect.left >= 0 &&
  384. rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
  385. rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  386. );
  387. }
  388. //获取元素是否在可视区域(部分可见)
  389. function isElementInViewport_(el) {
  390. let rect = el.getBoundingClientRect();
  391. return (
  392. rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
  393. rect.left <= (window.innerWidth || document.documentElement.clientWidth)
  394. );
  395. }
  396.  
  397.  
  398. // 自定义屏蔽用户
  399. function customBlockUsers() {
  400. let nowBlockUsers = '';
  401. menu_value('menu_customBlockUsers').forEach(function(item){nowBlockUsers += '|' + item})
  402. //console.log(nowBlockUsers.replace('|',''))
  403. let newBlockUsers = prompt('编辑 [自定义屏蔽用户]\n(不同用户名之间使用 "|" 分隔,例如:用户A|用户B|用户C )', nowBlockUsers.replace('|',''));
  404. if (newBlockUsers === '') {
  405. GM_setValue('menu_customBlockUsers', []);
  406. registerMenuCommand(); // 重新注册脚本菜单
  407. } else if (newBlockUsers != null) {
  408. GM_setValue('menu_customBlockUsers', newBlockUsers.split('|'));
  409. registerMenuCommand(); // 重新注册脚本菜单
  410. }
  411. };
  412.  
  413.  
  414. // 屏蔽指定用户
  415. function blockUsers(type) {
  416. if (!menu_value('menu_blockUsers')) return
  417. if (!menu_value('menu_customBlockUsers') || menu_value('menu_customBlockUsers').length < 1) return
  418. switch(type) {
  419. case 'index':
  420. blockUsers_('.Card.TopstoryItem.TopstoryItem-isRecommend', 'Card TopstoryItem TopstoryItem-isRecommend');
  421. break;
  422. case 'question':
  423. blockUsers_question();
  424. break;
  425. case 'search':
  426. blockUsers_search();
  427. break;
  428. case 'topic':
  429. blockUsers_('.List-item.TopicFeedItem', 'List-item TopicFeedItem');
  430. break;
  431. case 'people':
  432. blockUsers_button_people(); // 添加屏蔽用户按钮(用户主页)
  433. break;
  434. }
  435. blockUsers_comment(); // 评论区
  436. blockUsers_button(); // 加入黑名单按钮
  437.  
  438. function blockUsers_(className1, className2) {
  439. // 前几条因为是直接加载的,而不是动态插入网页的,所以需要单独判断
  440. function blockKeywords_now() {
  441. document.querySelectorAll(className1).forEach(function(item1){
  442. let item = item1.querySelector('.ContentItem.AnswerItem, .ContentItem.ArticleItem'); // 用户名所在元素
  443. if (item) {
  444. for (const keyword of menu_value('menu_customBlockUsers')) { // 遍历用户名黑名单
  445. if (keyword != '' && item.dataset.zop.indexOf('authorName":"' + keyword + '",') > -1) { // 找到就删除该信息流
  446. console.log(item.dataset.zop);
  447. item1.hidden = true;
  448. break;
  449. }
  450. }
  451. }
  452. })
  453. }
  454.  
  455. blockKeywords_now();
  456. window.addEventListener('urlchange', function(){
  457. setTimeout(blockKeywords_now, 1000); // 网页 URL 变化后再次执行
  458. })
  459.  
  460. // 这个是监听网页插入事件,用来判断后续网页动态插入的元素
  461. const callback = (mutationsList, observer) => {
  462. for (const mutation of mutationsList) {
  463. for (const target of mutation.addedNodes) {
  464. if (target.nodeType != 1) return
  465. if (target.className === className2) {
  466. let item = target.querySelector('.ContentItem.AnswerItem, .ContentItem.ArticleItem'); // 用户名所在元素
  467. if (item) {
  468. for (const keyword of menu_value('menu_customBlockUsers')) { // 遍历用户名黑名单
  469. if (keyword != '' && item.dataset.zop.indexOf('authorName":"' + keyword + '",') > -1) { // 找到就删除该信息流
  470. console.log(item.dataset.zop);
  471. target.hidden = true;
  472. break;
  473. }
  474. }
  475. }
  476. }
  477. }
  478. }
  479. };
  480. const observer = new MutationObserver(callback);
  481. observer.observe(document, { childList: true, subtree: true });
  482. }
  483.  
  484.  
  485. function blockUsers_question() {
  486. const blockUsers_question_ = (mutationsList, observer) => {
  487. for (const mutation of mutationsList) {
  488. for (const target of mutation.addedNodes) {
  489. if (target.nodeType != 1) return
  490. if (target.className === 'List-item' || target.className === 'Card AnswerCard') {
  491. let item1 = target.querySelector('.ContentItem.AnswerItem');
  492. if (item1) {
  493. menu_value('menu_customBlockUsers').forEach(function(item2){ // 遍历用户黑名单
  494. if (item1.dataset.zop.indexOf('authorName":"' + item2 + '",') > -1) { // 找到就删除该回答
  495. console.log(item1.dataset.zop)
  496. target.hidden = true;
  497. }
  498. })
  499. }
  500. }
  501. }
  502. }
  503. };
  504.  
  505. const blockUsers_question_answer_ = (mutationsList, observer) => {
  506. for (const mutation of mutationsList) {
  507. for (const target of mutation.addedNodes) {
  508. if (target.nodeType != 1) return
  509. target.querySelectorAll('.List-item, .Card.AnswerCard').forEach(function(item){
  510. let item1 = item.querySelector('.ContentItem.AnswerItem');
  511. if (item1) {
  512. menu_value('menu_customBlockUsers').forEach(function(item2){ // 遍历用户黑名单
  513. if (item1.dataset.zop.indexOf('authorName":"' + item2 + '",') > -1) { // 找到就删除该回答
  514. console.log(item1.dataset.zop)
  515. item.hidden = true;
  516. }
  517. })
  518. }
  519. })
  520. }
  521. }
  522. };
  523.  
  524. if (location.pathname.indexOf('/answer/') > -1) { // 回答页(就是只有三个回答的页面)
  525. const observer = new MutationObserver(blockUsers_question_answer_);
  526. observer.observe(document, { childList: true, subtree: true });
  527. } else { // 问题页(可以显示所有回答的页面)
  528. const observer = new MutationObserver(blockUsers_question_);
  529. observer.observe(document, { childList: true, subtree: true });
  530. }
  531.  
  532. // 针对的是打开网页后直接加载的前面几个回答(上面哪些是针对动态加载的回答)
  533. document.querySelectorAll('.List-item, .Card.AnswerCard').forEach(function(item){
  534. let item1 = item.querySelector('.ContentItem.AnswerItem');
  535. if (item1) {
  536. menu_value('menu_customBlockUsers').forEach(function(item2){ // 遍历用户黑名单
  537. if (item1.dataset.zop.indexOf('authorName":"' + item2 + '",') > -1) { // 找到就删除该回答
  538. console.log(item1.dataset.zop)
  539. item.hidden = true;
  540. }
  541. })
  542. }
  543. })
  544. }
  545.  
  546. function blockUsers_search() {
  547. function blockUsers_now() {
  548. if (location.search.indexOf('type=content') === -1) return // 目前只支持搜索页的 [综合]
  549. document.querySelectorAll('.Card.SearchResult-Card[data-za-detail-view-path-module="AnswerItem"], .Card.SearchResult-Card[data-za-detail-view-path-module="PostItem"]').forEach(function(item1){
  550. let item = item1.querySelector('.RichText.ztext.CopyrightRichText-richText b'); // 用户名所在元素
  551. if (item) {
  552. for (const keyword of menu_value('menu_customBlockUsers')) { // 遍历用户名黑名单
  553. if (keyword != '' && item.textContent === keyword) { // 找到就删除该信息流
  554. console.log(item.textContent);
  555. item1.hidden = true;
  556. break;
  557. }
  558. }
  559. }
  560. })
  561. }
  562.  
  563. setTimeout(blockUsers_now, 2000);
  564. window.addEventListener('urlchange', function(){
  565. setTimeout(blockUsers_now, 1000); // 网页 URL 变化后再次执行
  566. })
  567.  
  568. const callback = (mutationsList, observer) => {
  569. if (location.search.indexOf('type=content') === -1) return // 目前只支持搜索页的 [综合]
  570. for (const mutation of mutationsList) {
  571. for (const target of mutation.addedNodes) {
  572. if (target.nodeType != 1) return
  573. let item = target.querySelector('.Card.SearchResult-Card[data-za-detail-view-path-module="AnswerItem"] .RichText.ztext.CopyrightRichText-richText b, .Card.SearchResult-Card[data-za-detail-view-path-module="PostItem"] .RichText.ztext.CopyrightRichText-richText b');
  574. if (item) {
  575. for (const keyword of menu_value('menu_customBlockUsers')) { // 遍历用户名黑名单
  576. if (keyword != '' && item.textContent === keyword) { // 找到就删除该信息流
  577. console.log(item.textContent);
  578. target.hidden = true;
  579. break;
  580. }
  581. }
  582. }
  583. }
  584. }
  585. };
  586. const observer = new MutationObserver(callback);
  587. observer.observe(document, { childList: true, subtree: true });
  588. }
  589.  
  590. function blockUsers_comment() {
  591. const callback = (mutationsList, observer) => {
  592. for (const mutation of mutationsList) {
  593. for (const target of mutation.addedNodes) {
  594. if (target.nodeType != 1) return
  595. let item = target.querySelector('img.Avatar.UserLink-avatar')
  596. if (item) {
  597. menu_value('menu_customBlockUsers').forEach(function(item1){ // 遍历用户黑名单
  598. if (item.alt === item1) { // 找到就删除该搜索结果
  599. if (findParentElement(item, 'NestComment--rootComment', true)) {
  600. findParentElement(item, 'NestComment--rootComment', true).hidden = true;;
  601. } else if (findParentElement(item, 'NestComment--child', true)){
  602. findParentElement(item, 'NestComment--child', true).hidden = true;;
  603. } else if (findParentElement(item, 'NestComment', true)){
  604. findParentElement(item, 'NestComment', true).hidden = true;;
  605. } else if (findParentElement(item, 'CommentItemV2', true)){
  606. findParentElement(item, 'CommentItemV2', true).hidden = true;;
  607. } else if (findParentElement(item, 'CommentItemV2 CommentItemV2--highlighted', true)){
  608. findParentElement(item, 'CommentItemV2 CommentItemV2--highlighted', true).hidden = true;;
  609. }
  610. }
  611. })
  612.  
  613. // 添加屏蔽用户按钮(点赞、回复等按钮后面)
  614. if (item) {
  615. let footer = findParentElement(item, 'CommentItemV2-meta', true).parentElement.querySelector('.CommentItemV2-metaSibling > .CommentItemV2-footer'),
  616. userid = item.parentElement;
  617. if (userid && footer && !footer.lastElementChild.dataset.name) {
  618. userid = userid.href.split('/')[4];
  619. footer.insertAdjacentHTML('beforeend',`<button type="button" data-name="${item.alt}" data-userid="${userid}" class="Button CommentItemV2-hoverBtn Button--plain"><span style="display: inline-flex; align-items: center;">&#8203;<svg class="Zi Zi--Like" fill="currentColor" viewBox="0 0 24 24" width="16" height="16" style="transform: rotate(180deg); margin-right: 5px;"><path d="M18.376 5.624c-3.498-3.499-9.254-3.499-12.752 0-3.499 3.498-3.499 9.254 0 12.752 3.498 3.499 9.254 3.499 12.752 0 3.499-3.498 3.499-9.14 0-12.752zm-1.693 1.693c2.37 2.37 2.596 6.094.678 8.69l-9.367-9.48c2.708-1.919 6.32-1.58 8.69.79zm-9.48 9.48c-2.37-2.37-2.595-6.095-.676-8.69l9.48 9.48c-2.822 1.918-6.433 1.58-8.803-.79z" fill-rule="evenodd"></path></svg></span>屏蔽用户</button>`);
  620. footer.lastElementChild.onclick = function(){blockUsers_button_add(this.dataset.name, this.dataset.userid, false)}
  621. }
  622. }
  623. }
  624. }
  625. }
  626. };
  627. const observer = new MutationObserver(callback);
  628. observer.observe(document, { childList: true, subtree: true });
  629. }
  630.  
  631. // 添加屏蔽用户按钮(用户信息悬浮框中)
  632. function blockUsers_button() {
  633. const callback = (mutationsList, observer) => {
  634. for (const mutation of mutationsList) {
  635. for (const target of mutation.addedNodes) {
  636. if (target.nodeType != 1) return
  637. //console.log(target, target.className)
  638. if (target.className && (target.className.indexOf('Popover-content Popover-content--top HoverCard-popoverTarget') > -1 || target.className.indexOf('Popover-content Popover-content--bottom HoverCard-popoverTarget') > -1) || target.querySelector('.Popover-content.Popover-content--top.HoverCard-popoverTarget') || target.querySelector('.Popover-content.Popover-content--bottom.HoverCard-popoverTarget')) {
  639. let item = target.querySelector('.MemberButtonGroup.ProfileButtonGroup.HoverCard-buttons'),
  640. item1 = target.querySelector('a.UserLink-link'),
  641. name = item1.textContent,
  642. userid = item1.href.split('/')[4];
  643. if (item && !target.querySelector('button[data-name][data-userid]')) {
  644. item.insertAdjacentHTML('beforeend', `<button type="button" data-name="${name}" data-userid="${userid}" class="Button FollowButton Button--primary Button--red" style="width: 100%;margin: 7px 0 0 0;"><span style="display: inline-flex; align-items: center;">​<svg class="Zi Zi--Plus FollowButton-icon" fill="currentColor" viewBox="0 0 24 24" width="1.2em" height="1.2em"><path d="M18.376 5.624c-3.498-3.499-9.254-3.499-12.752 0-3.499 3.498-3.499 9.254 0 12.752 3.498 3.499 9.254 3.499 12.752 0 3.499-3.498 3.499-9.14 0-12.752zm-1.693 1.693c2.37 2.37 2.596 6.094.678 8.69l-9.367-9.48c2.708-1.919 6.32-1.58 8.69.79zm-9.48 9.48c-2.37-2.37-2.595-6.095-.676-8.69l9.48 9.48c-2.822 1.918-6.433 1.58-8.803-.79z" fill-rule="evenodd"></path></svg></span>屏蔽用户</button>`);
  645. item.lastElementChild.onclick = function(){blockUsers_button_add(this.dataset.name, this.dataset.userid, false)}
  646. }
  647. }
  648. }
  649. }
  650. };
  651. const observer = new MutationObserver(callback);
  652. observer.observe(document, { childList: true, subtree: true });
  653. }
  654.  
  655. // 添加屏蔽用户按钮(用户主页)
  656. function blockUsers_button_people() {
  657. let item = document.querySelector('.MemberButtonGroup.ProfileButtonGroup.ProfileHeader-buttons'), // 获取按钮元素位置
  658. name = document.querySelector('.ProfileHeader-name').firstChild.textContent, // 获取用户名
  659. users = menu_value('menu_customBlockUsers'), // 读取屏蔽列表
  660. userid = location.href.split('/')[4];
  661. for (let num = 0;num<users.length;num++) { // 判断是否已存在
  662. if (users[num] === name) { // 已存在
  663. document.querySelectorAll('.Button.Button--primary.Button--red').forEach(function(item){item.style.display = 'none';}) // 隐藏知乎自带的已屏蔽按钮
  664. item.insertAdjacentHTML('beforeend', `<button type="button" data-name="${name}" data-userid="${userid}" class="Button FollowButton Button--primary Button--red" style="margin: 0 0 0 12px;"><span style="display: inline-flex; align-items: center;">​<svg class="Zi Zi--Plus FollowButton-icon" fill="currentColor" viewBox="0 0 24 24" width="1.2em" height="1.2em"><path d="M18.376 5.624c-3.498-3.499-9.254-3.499-12.752 0-3.499 3.498-3.499 9.254 0 12.752 3.498 3.499 9.254 3.499 12.752 0 3.499-3.498 3.499-9.14 0-12.752zm-1.693 1.693c2.37 2.37 2.596 6.094.678 8.69l-9.367-9.48c2.708-1.919 6.32-1.58 8.69.79zm-9.48 9.48c-2.37-2.37-2.595-6.095-.676-8.69l9.48 9.48c-2.822 1.918-6.433 1.58-8.803-.79z" fill-rule="evenodd"></path></svg></span>取消屏蔽</button>`);
  665. item.lastElementChild.onclick = function(){blockUsers_button_del(this.dataset.name, this.dataset.userid, true)}
  666. return
  667. }
  668. };
  669. if (item) {
  670. item.insertAdjacentHTML('beforeend', `<button type="button" data-name="${name}" data-userid="${userid}" class="Button FollowButton Button--primary Button--red" style="margin: 0 0 0 12px;"><span style="display: inline-flex; align-items: center;">​<svg class="Zi Zi--Plus FollowButton-icon" fill="currentColor" viewBox="0 0 24 24" width="1.2em" height="1.2em"><path d="M18.376 5.624c-3.498-3.499-9.254-3.499-12.752 0-3.499 3.498-3.499 9.254 0 12.752 3.498 3.499 9.254 3.499 12.752 0 3.499-3.498 3.499-9.14 0-12.752zm-1.693 1.693c2.37 2.37 2.596 6.094.678 8.69l-9.367-9.48c2.708-1.919 6.32-1.58 8.69.79zm-9.48 9.48c-2.37-2.37-2.595-6.095-.676-8.69l9.48 9.48c-2.822 1.918-6.433 1.58-8.803-.79z" fill-rule="evenodd"></path></svg></span>屏蔽用户</button>`);
  671. item.lastElementChild.onclick = function(){blockUsers_button_add(this.dataset.name, this.dataset.userid, true)}
  672. }
  673. }
  674.  
  675. // 屏蔽用户按钮绑定事件(添加)
  676. function blockUsers_button_add(name, userid, reload) {
  677. if (!name || !userid) return
  678. let users = menu_value('menu_customBlockUsers'), // 读取屏蔽列表
  679. index = users.indexOf(name);
  680. if (index === -1) {
  681. users.push(name); // 追加用户名
  682. GM_setValue('menu_customBlockUsers', users); // 写入屏蔽列表
  683. // 加入知乎自带的黑名单(和本脚本互补~
  684. GM_xmlhttpRequest({url: `https://www.zhihu.com/api/v4/members/${userid}/actions/block`,method: 'POST',timeout: 2000});
  685. // 是否刷新本页
  686. if (reload) {
  687. setTimeout(function(){location.reload()}, 200); // 刷新网页,延迟 200 毫秒,避免知乎反应慢~
  688. } else {
  689. GM_notification({text: `该用户已被屏蔽~\n刷新网页后生效~`, timeout: 3000});
  690. }
  691. } else {
  692. GM_notification({text: `该用户已经被屏蔽啦,无需重复屏蔽~`, timeout: 3000});
  693. }
  694. }
  695.  
  696.  
  697. // 屏蔽用户按钮绑定事件(删除)
  698. function blockUsers_button_del(name, userid, reload) {
  699. if (!name || !userid) return
  700. let users = menu_value('menu_customBlockUsers'), // 读取屏蔽列表
  701. index = users.indexOf(name);
  702. if (index > -1) {
  703. users.splice(index, 1); // 移除用户名
  704. GM_setValue('menu_customBlockUsers', users); // 写入屏蔽列表
  705. // 移除知乎自带的黑名单
  706. GM_xmlhttpRequest({url: `https://www.zhihu.com/api/v4/members/${userid}/actions/block`,method: 'DELETE',timeout: 2000});
  707. // 是否刷新本页
  708. if (reload) {
  709. setTimeout(function(){location.reload()}, 200); // 刷新网页,延迟 200 毫秒,避免知乎反应慢~
  710. } else {
  711. GM_notification({text: `该用户已取消屏蔽啦~\n刷新网页后生效~`, timeout: 3000});
  712. }
  713. } else {
  714. GM_notification({text: `没有在屏蔽列表中找到该用户...`, timeout: 3000});
  715. }
  716. }
  717. }
  718.  
  719.  
  720. // 自定义屏蔽关键词(标题)
  721. function customBlockKeywords() {
  722. let nowBlockKeywords = '';
  723. menu_value('menu_customBlockKeywords').forEach(function(item){nowBlockKeywords += '|' + item})
  724. let newBlockKeywords = prompt('编辑 [自定义屏蔽关键词]\n(不同关键词之间使用 "|" 分隔,例如:关键词A|关键词B|关键词C \n(关键词不区分大小写,支持表情如:[捂脸]|[飙泪笑]', nowBlockKeywords.replace('|',''));
  725. if (newBlockKeywords === '') {
  726. GM_setValue('menu_customBlockKeywords', []);
  727. registerMenuCommand(); // 重新注册脚本菜单
  728. } else if (newBlockKeywords != null) {
  729. GM_setValue('menu_customBlockKeywords', newBlockKeywords.split('|'));
  730. registerMenuCommand(); // 重新注册脚本菜单
  731. }
  732. };
  733.  
  734.  
  735. // 屏蔽指定关键词
  736. function blockKeywords(type) {
  737. if (!menu_value('menu_blockKeywords')) return
  738. if (!menu_value('menu_customBlockKeywords') || menu_value('menu_customBlockKeywords').length < 1) return
  739. switch(type) {
  740. case 'index':
  741. blockKeywords_('.Card.TopstoryItem.TopstoryItem-isRecommend', 'Card TopstoryItem TopstoryItem-isRecommend');
  742. break;
  743. case 'topic':
  744. blockKeywords_('.List-item.TopicFeedItem', 'List-item TopicFeedItem');
  745. break;
  746. case 'people':
  747. blockKeywords_('.List-item', 'List-item');
  748. break;
  749. case 'collection':
  750. blockKeywords_('.Card.CollectionDetailPageItem', 'Card CollectionDetailPageItem');
  751. break;
  752. case 'search':
  753. blockKeywords_search();
  754. break;
  755. case 'comment':
  756. blockKeywords_comment();
  757. break;
  758. }
  759.  
  760.  
  761. function blockKeywords_(className1, className2) {
  762. // 前几条因为是直接加载的,而不是动态插入网页的,所以需要单独判断
  763. function blockKeywords_now() {
  764. if (location.pathname === '/hot') {
  765. console.log('222222222222')
  766. document.querySelectorAll('.HotItem').forEach(function(item1){blockKeywords_1(item1, 'h2.HotItem-title');})
  767. } else {
  768. document.querySelectorAll(className1).forEach(function(item1){blockKeywords_1(item1, 'h2.ContentItem-title meta[itemprop="name"], meta[itemprop="headline"]');})
  769. }
  770. }
  771.  
  772. blockKeywords_now();
  773. window.addEventListener('urlchange', function(){
  774. setTimeout(blockKeywords_now, 1000); // 网页 URL 变化后再次执行
  775. })
  776.  
  777. // 这个是监听网页插入事件,用来判断后续网页动态插入的元素
  778. const callback = (mutationsList, observer) => {
  779. for (const mutation of mutationsList) {
  780. for (const target of mutation.addedNodes) {
  781. if (target.nodeType != 1) return
  782. if (target.className === className2) {blockKeywords_1(target, 'h2.ContentItem-title meta[itemprop="name"], meta[itemprop="headline"]');}
  783. }
  784. }
  785. };
  786. const observer = new MutationObserver(callback);
  787. observer.observe(document, { childList: true, subtree: true });
  788. }
  789.  
  790.  
  791. function blockKeywords_search() {
  792. function blockKeywords_now() {
  793. if (location.search.indexOf('type=content') === -1) return // 目前只支持搜索页的 [综合]
  794. document.querySelectorAll('.HotLanding-contentItem, .Card.SearchResult-Card[data-za-detail-view-path-module="AnswerItem"], .Card.SearchResult-Card[data-za-detail-view-path-module="PostItem"]').forEach(function(item1){blockKeywords_1(item1, 'a[data-za-detail-view-id]');})
  795. }
  796.  
  797. setTimeout(blockKeywords_now, 2000);
  798. window.addEventListener('urlchange', function(){
  799. setTimeout(blockKeywords_now, 1000); // 网页 URL 变化后再次执行
  800. })
  801.  
  802. const callback = (mutationsList, observer) => {
  803. if (location.search.indexOf('type=content') === -1) return // 目前只支持搜索页的 [综合]
  804. for (const mutation of mutationsList) {
  805. for (const target of mutation.addedNodes) {
  806. if (target.nodeType != 1) return
  807. if (target.className === 'Card SearchResult-Card' && (target.dataset.zaDetailViewPathModule === 'AnswerItem' || target.dataset.zaDetailViewPathModule === 'PostItem')) {blockKeywords_1(target, 'a[data-za-detail-view-id]');}
  808. }
  809. }
  810. };
  811. const observer = new MutationObserver(callback);
  812. observer.observe(document, { childList: true, subtree: true });
  813. }
  814.  
  815.  
  816. function blockKeywords_comment() {
  817. function filterComment(comment) {
  818. let content = comment.querySelector('.RichText'); // 寻找评论文字所在元素
  819. let texts = [content.textContent.toLowerCase()]; // 因为要针对评论中的表情,所以需要整个数组并全部转为小写(用来不区分大小写)
  820. for (let i = 0; i < content.children.length; i++) { // 该条针对的是评论中的表情
  821. let emoticonValue = content.children[i].getAttribute('data-zhihu-emoticon'); // 确定是表情就将其添加到稍后遍历的数组中
  822. if (emoticonValue) {
  823. texts.push(emoticonValue)
  824. }
  825. }
  826.  
  827. let keywords = menu_value('menu_customBlockKeywords');
  828. for (const text of texts) {
  829. for (const keyword of keywords) { // 遍历关键词黑名单
  830. if (keyword != '' && text.indexOf(keyword.toLowerCase()) > -1) { // 找到就删除该评论
  831. console.log('已屏蔽评论:' + text);
  832. content.textContent = '[该评论已屏蔽]';
  833. break;
  834. }
  835. }
  836. }
  837. }
  838.  
  839. const callback = (mutationsList, observer) => {
  840. for (const mutation of mutationsList) {
  841. for (const target of mutation.addedNodes) {
  842. if (target.nodeType != 1) return
  843. for (const node of target.querySelectorAll('*')) {
  844. if (node.className === 'CommentItemV2-metaSibling') filterComment(node);
  845. }
  846. }
  847. }
  848. };
  849. const observer = new MutationObserver(callback);
  850. observer.observe(document, { childList: true, subtree: true });
  851. }
  852.  
  853. function blockKeywords_1(item1, css) {
  854. let item = item1.querySelector(css); // 标题所在元素
  855. console.log(item)
  856. if (item) {
  857. for (const keyword of menu_value('menu_customBlockKeywords')) { // 遍历关键词黑名单
  858. let text = item.content || item.textContent;
  859. if (keyword != '' && text.toLowerCase().indexOf(keyword.toLowerCase()) > -1) { // 找到就删除该信息流
  860. console.log(text);
  861. item1.hidden = true;
  862. item1.style.display = 'none';
  863. break;
  864. }
  865. }
  866. }
  867. }
  868. }
  869.  
  870.  
  871. // 屏蔽指定类别(视频/文章等)
  872. function blockType(type) {
  873. let name;
  874. // 一开始加载的信息流 + 添加标签样式
  875. if (type === 'search') { // 搜索页
  876. if (!menu_value('menu_blockTypeVideo') && !menu_value('menu_blockTypeArticle') && !menu_value('menu_blockTypeTopic') && !menu_value('menu_blockTypeSearch')) return
  877. if (menu_value('menu_blockTypeSearch') && location.pathname === '/search') setTimeout(function(){document.querySelector('.RelevantQuery').parentElement.parentElement.hidden = true;}, 2000)
  878. name = 'h2.ContentItem-title a:not(.zhihu_e_toQuestion), a.KfeCollection-PcCollegeCard-link, h2.SearchTopicHeader-Title a'
  879. addSetInterval_(name);
  880. } else if (type === 'question') { // 问题页
  881. if (!menu_value('menu_blockTypeVideo')) return
  882. document.lastChild.appendChild(document.createElement('style')).textContent = `.VideoAnswerPlayer, .VideoAnswerPlayer-video, .VideoAnswerPlayer-iframe {display: none !important;}`;
  883. name = '.VideoAnswerPlayer'
  884. document.querySelectorAll(name).forEach(function(item){blockType_(item);})
  885. } else { // 首页
  886. if (!menu_value('menu_blockTypeVideo') && !menu_value('menu_blockTypeArticle')) return
  887. if (menu_value('menu_blockTypeVideo')) document.lastChild.appendChild(document.createElement('style')).textContent = `.Card .ZVideoItem-video, nav.TopstoryTabs > a[aria-controls="Topstory-zvideo"] {display: none !important;}`;
  888. name = 'h2.ContentItem-title a:not(.zhihu_e_toQuestion)'
  889. document.querySelectorAll(name).forEach(function(item){blockType_(item);})
  890. }
  891.  
  892. // 后续加载的信息流
  893. const observer = new MutationObserver(mutationsList => {
  894. for (const mutation of mutationsList) {
  895. for (const target of mutation.addedNodes) {
  896. if (target.nodeType != 1) return
  897. blockType_(target.querySelector(name));
  898. }
  899. }
  900. });
  901. observer.observe(document, { childList: true, subtree: true });
  902.  
  903. window.addEventListener('urlchange', function(){
  904. addSetInterval_(name);
  905. // 移除相关搜索
  906. if (menu_value('menu_blockTypeSearch') && location.pathname === '/search' && location.search.indexOf('type=content') > -1) setTimeout(function(){document.querySelector('.RelevantQuery').parentElement.parentElement.hidden = true;}, 1500)
  907. })
  908.  
  909. function blockType_(titleA) {
  910. if (!titleA) return // 判断是否为真
  911. //console.log(titleA.href)
  912. if (location.pathname === '/search') { // 搜索页
  913. if (location.search.indexOf('type=content') === -1) return // 仅限搜索页的 [综合]
  914. if (titleA.href.indexOf('/zvideo/') > -1 || titleA.href.indexOf('video.zhihu.com') > -1) { // 如果是视频
  915. if (menu_value('menu_blockTypeVideo')) findParentElement(titleA, 'Card').hidden = true;
  916. } else if (titleA.href.indexOf('zhuanlan.zhihu.com') > -1) { // 如果是文章
  917. if (menu_value('menu_blockTypeArticle')) findParentElement(titleA, 'Card SearchResult-Card').hidden = true;
  918. } else if (titleA.href.indexOf('/topic/') > -1) { // 如果是话题
  919. if (menu_value('menu_blockTypeTopic')) findParentElement(titleA, 'Card SearchResult-Card').hidden = true;
  920. } else if (titleA.href.indexOf('/market/') > -1) { // 如果是杂志文章等乱七八糟的
  921. if (menu_value('menu_blockTypeArticle')) findParentElement(titleA, 'Card SearchResult-Card').hidden = true;
  922. }
  923. } else if (location.pathname.indexOf('/question/') > -1) { // 问题页
  924. if (menu_value('menu_blockTypeVideo')) findParentElement(titleA, 'List-item').hidden = true;
  925. } else { // 首页
  926. if (titleA.href.indexOf('/zvideo/') > -1 || titleA.href.indexOf('video.zhihu.com') > -1) { // 如果是视频
  927. if (menu_value('menu_blockTypeVideo')) findParentElement(titleA, 'Card TopstoryItem TopstoryItem-isRecommend').hidden = true;
  928. } else if (titleA.href.indexOf('/answer/') > -1) { // 如果是问题(视频回答)
  929. if (findParentElement(titleA, 'ContentItem AnswerItem').querySelector('.VideoAnswerPlayer')) {
  930. if (menu_value('menu_blockTypeVideo')) findParentElement(titleA, 'Card TopstoryItem TopstoryItem-isRecommend').hidden = true;
  931. }
  932. } else if (titleA.href.indexOf('zhuanlan.zhihu.com') > -1) { // 如果是文章
  933. if (menu_value('menu_blockTypeArticle')) findParentElement(titleA, 'Card TopstoryItem TopstoryItem-isRecommend').hidden = true;
  934. }
  935. }
  936. }
  937.  
  938. function addSetInterval_(A) {
  939. let timer = setInterval(function(){
  940. let aTag = document.querySelectorAll(A);
  941. if (aTag.length > 0) {
  942. clearInterval(timer);
  943. aTag.forEach(function(item){blockType_(item);})
  944. }
  945. });
  946. }
  947. }
  948.  
  949.  
  950. // 寻找父元素
  951. function findParentElement(item, className, type = false) {
  952. if (item.parentElement) {
  953. //console.log(item.parentElement)
  954. if (type) { // true = 完全一致,false = 包含即可
  955. if (item.parentElement.className && item.parentElement.className === className) {
  956. //console.log(item.parentElement.className)
  957. return item.parentElement;
  958. } else {
  959. let temp = findParentElement(item.parentElement, className, true)
  960. if (temp) return temp
  961. }
  962. } else {
  963. if (item.parentElement.className && item.parentElement.className.indexOf(className) > -1) {
  964. return item.parentElement;
  965. } else {
  966. let temp = findParentElement(item.parentElement, className)
  967. if (temp) return temp
  968. }
  969. }
  970. }
  971. return
  972. }
  973.  
  974.  
  975. // 移除高亮链接
  976. function removeHighlightLink() {
  977. const callback = (mutationsList, observer) => {
  978. for (const mutation of mutationsList) {
  979. for (const target of mutation.addedNodes) {
  980. if (target.nodeType != 1 || target.tagName != 'A') break
  981. if (target.dataset.zaNotTrackLink && target.href.indexOf('https://www.zhihu.com/search?q=') > -1) {
  982. target.parentElement.replaceWith(target.textContent);
  983. }
  984. }
  985. }
  986. };
  987. const observer = new MutationObserver(callback);
  988. observer.observe(document, { childList: true, subtree: true });
  989.  
  990. // 针对的是打开网页后直接加载的前面几个回答(上面哪些是针对动态加载的回答)
  991. document.querySelectorAll('span > a[data-za-not-track-link][href^="https://www.zhihu.com/search?q="]').forEach(e => e.parentElement.replaceWith(e.textContent))
  992. }
  993.  
  994.  
  995. // 屏蔽盐选内容
  996. function blockYanXuan() {
  997. if (!menu_value('menu_blockYanXuan')) return
  998. const blockYanXuan_question = (mutationsList, observer) => {
  999. for (const mutation of mutationsList) {
  1000. for (const target of mutation.addedNodes) {
  1001. if (target.nodeType != 1) return
  1002. if (target.className === 'List-item' || target.className === 'Card AnswerCard') {
  1003. if (target.querySelector('.KfeCollection-AnswerTopCard-Container, .KfeCollection-PurchaseBtn')) {
  1004. target.hidden = true;
  1005. }
  1006. }
  1007. }
  1008. }
  1009. };
  1010.  
  1011. const blockYanXuan_question_answer = (mutationsList, observer) => {
  1012. for (const mutation of mutationsList) {
  1013. for (const target of mutation.addedNodes) {
  1014. if (target.nodeType != 1) return
  1015. target.querySelectorAll('.List-item, .Card.AnswerCard').forEach(function(item){
  1016. if (item.querySelector('.KfeCollection-AnswerTopCard-Container, .KfeCollection-PurchaseBtn')) {
  1017. item.hidden = true;
  1018. }
  1019. })
  1020. }
  1021. }
  1022. };
  1023.  
  1024. if (location.pathname.indexOf('/answer/') > -1) { // 回答页(就是只有三个回答的页面)
  1025. const observer = new MutationObserver(blockYanXuan_question_answer);
  1026. observer.observe(document, { childList: true, subtree: true });
  1027. } else { // 问题页(可以显示所有回答的页面)
  1028. const observer = new MutationObserver(blockYanXuan_question);
  1029. observer.observe(document, { childList: true, subtree: true });
  1030. }
  1031.  
  1032. // 针对的是打开网页后直接加载的前面几个回答(上面哪些是针对动态加载的回答)
  1033. document.querySelectorAll('.List-item, .Card.AnswerCard').forEach(function(item){
  1034. if (item.querySelector('.KfeCollection-AnswerTopCard-Container, .KfeCollection-PurchaseBtn')) {
  1035. item.hidden = true;
  1036. }
  1037. })
  1038. }
  1039.  
  1040.  
  1041. // 区分问题文章
  1042. function addTypeTips() {
  1043. if (!menu_value('menu_typeTips')) return
  1044. let style = `font-weight: bold;font-size: 13px;padding: 1px 4px 0;border-radius: 2px;display: inline-block;vertical-align: top;margin: ${(location.pathname === '/search') ? '2' : '4'}px 4px 0 0;`
  1045. document.body.appendChild(document.createElement('style')).textContent = `/* 区分问题文章 */
  1046. .AnswerItem .ContentItem-title a:not(.zhihu_e_toQuestion)::before {content:'问题';color: #f68b83;background-color: #f68b8333;${style}}
  1047. .TopstoryQuestionAskItem .ContentItem-title a:not(.zhihu_e_toQuestion)::before {content:'问题';color: #ff5a4e;background-color: #ff5a4e33;${style}}
  1048. .ZVideoItem .ContentItem-title a::before, .ZvideoItem .ContentItem-title a::before {content:'视频';color: #00BCD4;background-color: #00BCD433;${style}}
  1049. .ArticleItem .ContentItem-title a::before {content:'文章';color: #2196F3;background-color: #2196F333;${style}}`;
  1050. }
  1051.  
  1052.  
  1053. // 直达问题按钮
  1054. function addToQuestion() {
  1055. if (!menu_value('menu_toQuestion')) return
  1056.  
  1057. // 一开始加载的信息流 + 添加按钮样式
  1058. if (location.pathname === '/search') {
  1059. document.lastChild.appendChild(document.createElement('style')).textContent = `a.zhihu_e_toQuestion {font-size: 13px !important;font-weight: normal !important;padding: 1px 6px 0 !important;border-radius: 2px !important;display: inline-block !important;vertical-align: top !important;height: 20.67px !important;line-height: 20.67px !important;margin-top: 2px !important;}`;
  1060. addSetInterval_('h2.ContentItem-title a:not(.zhihu_e_tips)');
  1061. } else {
  1062. document.lastChild.appendChild(document.createElement('style')).textContent = `a.zhihu_e_toQuestion {font-size: 13px !important;font-weight: normal !important;padding: 1px 6px 0 !important;border-radius: 2px !important;display: inline-block !important;vertical-align: top !important;margin-top: 4px !important;}`;
  1063. document.querySelectorAll('h2.ContentItem-title a:not(.zhihu_e_tips)').forEach(function(item){addTypeTips_(item);})
  1064. }
  1065.  
  1066. // 后续加载的信息流
  1067. const observer = new MutationObserver(mutationsList => {
  1068. for (const mutation of mutationsList) {
  1069. for (const target of mutation.addedNodes) {
  1070. if (target.nodeType != 1) return
  1071. addTypeTips_(target.querySelector('h2.ContentItem-title a:not(.zhihu_e_tips)'));
  1072. }
  1073. }
  1074. });
  1075. observer.observe(document, { childList: true, subtree: true });
  1076.  
  1077. window.addEventListener('urlchange', function(){
  1078. addSetInterval_('h2.ContentItem-title a:not(.zhihu_e_tips)');
  1079. })
  1080.  
  1081. function addTypeTips_(titleA) {
  1082. if (!titleA) return // 判断是否为真
  1083. if (titleA.parentElement.querySelector('a.zhihu_e_toQuestion')) return // 判断是否已添加
  1084. if (titleA.textContent.indexOf('?') != -1) { // 把问题末尾英文问好 [?] 的替换为中文问好 [?],这样按钮与标题之间的间距就刚刚好~
  1085. titleA.innerHTML = titleA.innerHTML.replace('?', "?")
  1086. }
  1087. if (/answer\/\d+/.test(titleA.href)) { // 如果是指向回答的问题(而非指向纯问题的链接)
  1088. titleA.insertAdjacentHTML('afterend', `<a class="zhihu_e_toQuestion VoteButton" href="${titleA.parentElement.querySelector('meta[itemprop="url"]').content}" target="_blank">直达问题</a>`);
  1089. }
  1090. }
  1091.  
  1092. function addSetInterval_(A) {
  1093. let timer = setInterval(function(){
  1094. let aTag = document.querySelectorAll(A);
  1095. if (aTag.length > 0) {
  1096. clearInterval(timer);
  1097. aTag.forEach(function(item){addTypeTips_(item);})
  1098. }
  1099. });
  1100. }
  1101. }
  1102.  
  1103.  
  1104. // 展开问题描述
  1105. function questionRichTextMore() {
  1106. if (!menu_value('menu_questionRichTextMore')) return
  1107. let button = document.querySelector('button.QuestionRichText-more');
  1108. if (button) button.click()
  1109. }
  1110.  
  1111.  
  1112. // 知乎免登录
  1113. function removeLogin() {
  1114. const removeLoginModal = (mutationsList, observer) => {
  1115. for (const mutation of mutationsList) {
  1116. for (const target of mutation.addedNodes) {
  1117. if (target.nodeType != 1) return
  1118. if (target.querySelector('.signFlowModal')) {
  1119. let button = target.querySelector('.Button.Modal-closeButton.Button--plain');
  1120. if (button) button.click();
  1121. } else if (getXpath('//button[text()="立即登录/注册"]',target)) {
  1122. target.remove();
  1123. }
  1124. }
  1125. }
  1126. };
  1127.  
  1128. // 未登录时才会监听并移除登录弹窗
  1129. if(location.hostname === 'zhuanlan.zhihu.com') { // 如果是文章页
  1130. if (!document.querySelector('.ColumnPageHeader-profile>.AppHeader-menu')) { // 未登录
  1131. const observer = new MutationObserver(removeLoginModal);
  1132. observer.observe(document, { childList: true, subtree: true });
  1133. getXpath('//button[text()="登录/注册"]').outerHTML = '<a class="Button AppHeader-login Button--blue" href="https://www.zhihu.com/signin" target="_blank">登录/注册</a>'; // [登录] 按钮跳转至登录页面
  1134. } else {
  1135. cleanTitles(); // 净化标题消息
  1136. }
  1137. } else { // 不是文章页
  1138. if (!document.querySelector('.AppHeader-profile>.AppHeader-menu')) { // 未登录
  1139. const observer = new MutationObserver(removeLoginModal);
  1140. observer.observe(document, { childList: true, subtree: true });
  1141. document.lastElementChild.appendChild(document.createElement('style')).textContent = '.Question-mainColumnLogin, button.AppHeader-login {display: none !important;}'; // 屏蔽问题页中间的登录提示
  1142. getXpath('//button[text()="登录/注册"]').outerHTML = '<a class="Button AppHeader-login Button--blue" href="https://www.zhihu.com/signin" target="_blank">登录/注册</a>'; // [登录] 按钮跳转至登录页面
  1143. } else {
  1144. cleanTitles(); // 净化标题消息
  1145. }
  1146. }
  1147. }
  1148.  
  1149.  
  1150. // 净化标题消息
  1151. function cleanTitles() {
  1152. if (!menu_value('menu_cleanTitles')) return
  1153.  
  1154. // 方案一
  1155. const elTitle = document.head.querySelector('title');
  1156. const original = elTitle.textContent;
  1157. const observer = new MutationObserver(function() {
  1158. if (elTitle.textContent != original) { // 避免重复执行
  1159. elTitle.textContent = original;
  1160. }
  1161. });
  1162. observer.observe(elTitle, { childList: true });
  1163.  
  1164. // 方案二
  1165. // if (Reflect.getOwnPropertyDescriptor(document, 'title')) {
  1166. // const elTitle = document.head.querySelector('title');
  1167. // const original = elTitle.textContent;
  1168. // const observer = new MutationObserver(function() {
  1169. // if (elTitle.textContent != original) { // 避免重复执行
  1170. // elTitle.textContent = original;
  1171. // }
  1172. // });
  1173. // observer.observe(elTitle, { childList: true });
  1174. // } else {
  1175. // const title = document.title;
  1176. // Reflect.defineProperty(document, 'title', {
  1177. // set: () => {},
  1178. // get: () => title,
  1179. // });
  1180. // }
  1181. }
  1182.  
  1183.  
  1184. // 净化搜索热门
  1185. function cleanSearch() {
  1186. if (!menu_value('menu_cleanSearch')) return
  1187.  
  1188. const el = document.querySelector('.SearchBar-input > input');
  1189. const observer = new MutationObserver((mutationsList, observer) => {
  1190. if (mutationsList[0].attributeName === 'placeholder' && mutationsList[0].target.placeholder != '') mutationsList[0].target.placeholder = '';
  1191. });
  1192. el.placeholder = '';
  1193. observer.observe(el, { attributes: true });
  1194. document.documentElement.appendChild(document.createElement('style')).textContent = '.AutoComplete-group > .SearchBar-label:not(.SearchBar-label--history), .AutoComplete-group > [id^="AutoComplete2-topSearch-"] {display: none !important;}';
  1195. }
  1196.  
  1197.  
  1198. // 快捷关闭悬浮评论(监听点击事件,点击网页两侧空白处)
  1199. function closeFloatingComments() {
  1200. const closeFloatingCommentsModal = (mutationsList, observer) => {
  1201. for (const mutation of mutationsList) {
  1202. for (const target of mutation.addedNodes) {
  1203. if (target.nodeType != 1) return
  1204. if (target.querySelector('.Modal-backdrop')) {
  1205. document.querySelector('.Modal-backdrop').onclick = function(event){
  1206. if (event.target == this) {
  1207. let button = document.querySelector('.Button.Modal-closeButton.Button--plain');
  1208. if (button) button.click();
  1209. }
  1210. }
  1211. }
  1212. }
  1213. }
  1214. };
  1215. const observer = new MutationObserver(closeFloatingCommentsModal);
  1216. observer.observe(document, { childList: true, subtree: true });
  1217. }
  1218.  
  1219.  
  1220. // 监听 XMLHttpRequest 事件
  1221. /*function EventXMLHttpRequest() {
  1222. var _send = window.XMLHttpRequest.prototype.send
  1223. function sendReplacement(data) {
  1224. addTypeTips();
  1225. return _send.apply(this, arguments);
  1226. }
  1227. window.XMLHttpRequest.prototype.send = sendReplacement;
  1228. }*/
  1229.  
  1230.  
  1231. // 自定义 urlchange 事件(用来监听 URL 变化)
  1232. function addUrlChangeEvent() {
  1233. history.pushState = ( f => function pushState(){
  1234. var ret = f.apply(this, arguments);
  1235. window.dispatchEvent(new Event('pushstate'));
  1236. window.dispatchEvent(new Event('urlchange'));
  1237. return ret;
  1238. })(history.pushState);
  1239.  
  1240. history.replaceState = ( f => function replaceState(){
  1241. var ret = f.apply(this, arguments);
  1242. window.dispatchEvent(new Event('replacestate'));
  1243. window.dispatchEvent(new Event('urlchange'));
  1244. return ret;
  1245. })(history.replaceState);
  1246.  
  1247. window.addEventListener('popstate',()=>{
  1248. window.dispatchEvent(new Event('urlchange'))
  1249. });
  1250. }
  1251.  
  1252.  
  1253. function getXpath(xpath, contextNode, doc = document) {
  1254. contextNode = contextNode || doc;
  1255. try {
  1256. const result = doc.evaluate(xpath, contextNode, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  1257. // 应该总是返回一个元素节点
  1258. return result.singleNodeValue && result.singleNodeValue.nodeType === 1 && result.singleNodeValue;
  1259. } catch (err) {
  1260. throw new Error(`无效 Xpath: ${xpath}`);
  1261. }
  1262. }
  1263.  
  1264.  
  1265. // 显示问题作者
  1266. function question_author() {
  1267. if (document.querySelector('.BrandQuestionSymbol, .QuestionAuthor')) return
  1268. let qJson = JSON.parse(document.querySelector('#js-initialData').textContent).initialState.entities.questions[/\d+/.exec(location.pathname)[0]].author,
  1269. html = `<div class="BrandQuestionSymbol"><a class="BrandQuestionSymbol-brandLink" href="/people/${qJson.urlToken}"><img role="presentation" src="${qJson.avatarUrl}" class="BrandQuestionSymbol-logo" alt=""><span class="BrandQuestionSymbol-name">${qJson.name}</span></a><div class="BrandQuestionSymbol-divider" style="margin-left: 5px;margin-right: 10px;"></div></div>`;
  1270. //html = `<div class="QuestionAuthor"><div class="AuthorInfo AuthorInfo--plain" itemprop="author" itemscope="" itemtype="http://schema.org/Person"><div class="AuthorInfo"><span class="UserLink AuthorInfo-avatarWrapper"><div class="Popover"><div id="Popover18-toggle" aria-haspopup="true" aria-expanded="false" aria-owns="Popover18-content"><a class="UserLink-link" data-za-detail-view-element_name="User" target="_blank" href="${qJson.urlToken}"><img class="Avatar AuthorInfo-avatar" width="24" height="24" src="${qJson.avatarUrl}"></a></div></div></span><div class="AuthorInfo-content"><div class="AuthorInfo-head"><span class="UserLink AuthorInfo-name"><div class="Popover"><div id="Popover19-toggle" aria-haspopup="true" aria-expanded="false" aria-owns="Popover19-content"><a class="UserLink-link" data-za-detail-view-element_name="User" target="_blank" href="${qJson.urlToken}">${qJson.name}</a></div></div></span></div></div></div></div></div>`
  1271. document.querySelector('.QuestionHeader-topics').insertAdjacentHTML('beforebegin', html);
  1272. //document.querySelector('.QuestionPage h1.QuestionHeader-title').insertAdjacentHTML('afterend', html);
  1273. }
  1274.  
  1275.  
  1276. // [完整显示时间 + 置顶显示时间] 功能修改自:https://greasyfork.org/scripts/402808(从 JQuery 改为原生 JavaScript,且精简、优化了代码)
  1277. // 完整显示时间 + 置顶显示时间
  1278. function topTime_(css, classs) {
  1279. document.querySelectorAll(css).forEach(function(_this) {
  1280. let t = _this.querySelector('.ContentItem-time'); if (!t) return
  1281. if (!(t.classList.contains('full')) && t.querySelector('span') && t.querySelector('span').textContent != null) {
  1282. // 完整显示时间
  1283. topTime_allTime(t)
  1284. // 发布时间置顶
  1285. topTime_publishTop(t, _this, classs)
  1286. }
  1287. });
  1288. }
  1289.  
  1290.  
  1291. // 完整显示时间 + 置顶显示时间 - 文章
  1292. function topTime_post() {
  1293. let t = document.querySelector('.ContentItem-time:not(.xiu-time)'); if (!t) return
  1294. // 完整显示时间
  1295. if (t.textContent.indexOf('编辑于') > -1 && !(t.classList.contains('xiu-time'))) {
  1296. let tt = t.textContent;
  1297. t.click();
  1298. t.textContent = (t.textContent + ' ,' + tt)
  1299. t.classList.add('xiu-time');
  1300. }
  1301.  
  1302. //发布时间置顶
  1303. if (menu_value('menu_publishTop') && !(document.querySelector('.Post-Header > .ContentItem-time')) && !(document.querySelector('.ContentItem-meta > .ContentItem-time'))) {
  1304. let temp_time = t.cloneNode(true);
  1305. temp_time.style.padding = '0px';
  1306. document.querySelector('.Post-Header').insertAdjacentElement('beforeEnd', temp_time);
  1307. }
  1308. }
  1309.  
  1310.  
  1311. // 完整显示时间
  1312. function topTime_allTime(t) {
  1313. if (t.textContent.indexOf('发布于') > -1 && t.textContent.indexOf('编辑于') == -1) {
  1314. t.querySelector('span').textContent = (t.querySelector('span').dataset.tooltip);
  1315. t.classList.add('full');
  1316. } else if (t.textContent.indexOf('发布于') == -1 && t.textContent.indexOf('编辑于') > -1) {
  1317. t.querySelector('span').textContent = (t.querySelector('span').dataset.tooltip) + ' ,' + (t.querySelector('span').textContent);
  1318. t.classList.add('full');
  1319. }
  1320. }
  1321.  
  1322.  
  1323. // 发布时间置顶
  1324. function topTime_publishTop(t, _this, _class) {
  1325. if (!menu_value('menu_publishTop')) return
  1326. if (!t.parentNode.classList.contains(_class)) {
  1327. let temp_time = t.cloneNode(true);
  1328. temp_time.style.padding = '0px';
  1329. // 对于较短的回答,隐藏回答底部的时间
  1330. if (_this.offsetHeight < 400) t.style.display = 'none';
  1331. _this.querySelector('.' + _class).insertAdjacentElement('beforeEnd', temp_time);
  1332. }
  1333. }
  1334.  
  1335.  
  1336. // 问题创建时间
  1337. function question_time() {
  1338. if (!(document.querySelector('.QuestionPage .QuestionHeader-side .QuestionTime-xiu'))) {
  1339. document.querySelector('.QuestionPage .QuestionHeader-side').insertAdjacentHTML('beforeEnd', '<div class="QuestionTime-xiu" style="color: #9098ac; margin-top: 5px; font-size: 13px; font-style: italic;"><p>创建时间:' + getUTC8(new Date(document.querySelector('.QuestionPage > meta[itemprop=dateCreated]').content)) + '</p><p>最后编辑:' + getUTC8(new Date(document.querySelector('.QuestionPage > meta[itemprop=dateModified]').content)) + '</p></div>');
  1340. }
  1341. }
  1342.  
  1343.  
  1344. // UTC 标准时转 UTC+8 北京时间,修改自:https://greasyfork.org/zh-CN/scripts/402808(精简)
  1345. function getUTC8(t) {
  1346. return (t.getFullYear() + '-' + (((t.getMonth() + 1) < 10) ? ('0' + (t.getMonth() + 1)) : (t.getMonth() + 1)) + '-' + ((t.getDate() < 10) ? ('0' + t.getDate()) : t.getDate()) + '\xa0\xa0' + ((t.getHours() < 10) ? ('0' + t.getHours()) : t.getHours()) + ':' + ((t.getMinutes() < 10) ? ('0' + t.getMinutes()) : t.getMinutes()) + ':' + ((t.getSeconds() < 10) ? ('0' + t.getSeconds()) : t.getSeconds()));
  1347. }
  1348.  
  1349.  
  1350. // 默认站外直链,修改自:https://greasyfork.org/scripts/402808(从 JQuery 改为原生 JavaScript,且精简、优化了代码)
  1351. function directLink () {
  1352. document.querySelectorAll('a.external[href*="link.zhihu.com/?target="], a.LinkCard[href*="link.zhihu.com/?target="]:not(.MCNLinkCard):not(.ZVideoLinkCard):not(.ADLinkCardContainer)').forEach(function (_this) {_this.href = decodeURIComponent(_this.href.substring(_this.href.indexOf('link.zhihu.com/?target=') + 23));});
  1353. }
  1354.  
  1355.  
  1356. // 默认高清原图,修改自:https://greasyfork.org/scripts/402808(从 JQuery 改为原生 JavaScript,且精简、优化了代码)
  1357. function originalPic(){
  1358. document.querySelectorAll('img[data-original]:not(.comment_sticker):not(.Avatar)').forEach(function(one){if (one.src != one.dataset.original) {one.src = one.dataset.original}});
  1359. }
  1360.  
  1361.  
  1362. // 默认折叠邀请,修改自:https://greasyfork.org/scripts/402808(从 JQuery 改为原生 JavaScript,且精简、优化了代码)
  1363. function questionInvitation(){
  1364. let time = setInterval(function(){
  1365. let q = document.querySelector('.QuestionInvitation-content'); if (!q) return
  1366. clearInterval(time);
  1367. q.style.display = 'none';
  1368. document.querySelector('.QuestionInvitation-title').innerHTML = document.querySelector('.QuestionInvitation-title').innerText + '<span style="cursor: pointer; font-size: 14px; color: #919aae;"> 展开/折叠</span>'
  1369. // 点击事件(展开/折叠)
  1370. document.querySelector('.Topbar').onclick = function(){
  1371. let q = document.querySelector('.QuestionInvitation-content')
  1372. if (q.style.display == 'none') {
  1373. q.style.display = ''
  1374. } else {
  1375. q.style.display = 'none'
  1376. }
  1377. }
  1378. });
  1379. }
  1380.  
  1381.  
  1382. (function() {
  1383. if (window.onurlchange === undefined) {addUrlChangeEvent();} // Tampermonkey v4.11 版本添加的 onurlchange 事件 grant,可以监控 pjax 等网页的 URL 变化
  1384. removeLogin(); // 移除登录弹窗
  1385. setInterval(originalPic,100); // 默认高清原图
  1386. setInterval(directLink, 100); // 默认站外直链
  1387. window.addEventListener('urlchange', function(){ // 针对的是从单个回答页跳转到完整回答页时
  1388. console.log(location.pathname)
  1389. if (location.pathname.indexOf('question') > -1 && location.pathname.indexOf('waiting') === -1 && location.pathname.indexOf('/answer/') === -1) { // 回答页 //
  1390. setTimeout(function(){
  1391. collapsedNowAnswer('.QuestionPage'); // 收起当前回答 + 快捷返回顶部
  1392. collapsedNowAnswer('.Question-main'); // 收起当前回答 + 快捷返回顶部
  1393. questionRichTextMore(); // 展开问题描述
  1394. blockUsers('question'); // 屏蔽指定用户
  1395. blockYanXuan(); // 屏蔽盐选内容
  1396. }, 300);
  1397. } else if (location.pathname == '/') {
  1398. setTimeout(()=>{
  1399. blockUsers('index'); // 屏蔽指定用户
  1400. blockKeywords('index'); // 屏蔽指定关键词
  1401. blockType(); // 屏蔽指定类别(视频/文章等)
  1402. }, 500);
  1403. } else if (location.pathname == '/hot') {
  1404. setTimeout(()=>{blockKeywords('index');}, 500);// 屏蔽指定关键词
  1405. }
  1406. })
  1407.  
  1408. if (GM_info.scriptHandler === 'Violentmonkey') { // Violentmonkey 比 Tampermonkey 加载更早,会导致一些元素还没加载,因此需要延迟一会儿
  1409. setTimeout(start, 300);
  1410. } else {
  1411. start();
  1412. }
  1413.  
  1414. function start(){
  1415. removeHighlightLink(); // 移除高亮链接
  1416. if (location.hostname != 'zhuanlan.zhihu.com') {
  1417. if (location.pathname.indexOf('/column/') === -1) cleanSearch(); //净化搜索热门
  1418. collapsedAnswer(); // 一键收起回答
  1419. }
  1420. closeFloatingComments(); // 快捷关闭悬浮评论(监听点击事件,点击网页两侧空白处)
  1421. blockKeywords('comment'); // 屏蔽指定关键词(评论)
  1422.  
  1423.  
  1424. if (location.pathname.indexOf('question') > -1 && location.href.indexOf('/log') == -1) { // 回答页 //
  1425. if (location.pathname.indexOf('waiting') == -1) {
  1426. collapsedNowAnswer('.QuestionPage'); // 收起当前回答 + 快捷返回顶部
  1427. collapsedNowAnswer('.Question-main'); // 收起当前回答 + 快捷返回顶部
  1428. questionRichTextMore(); // 展开问题描述
  1429. blockUsers('question'); // 屏蔽指定用户
  1430. blockYanXuan(); // 屏蔽盐选内容
  1431. blockType('question'); // 屏蔽指定类别(视频/文章等)
  1432. defaultCollapsedAnswer(); // 默认收起回答
  1433. }
  1434. setInterval(function(){topTime_('.ContentItem.AnswerItem', 'ContentItem-meta')}, 300); // 置顶显示时间
  1435. setTimeout(function(){question_time(); question_author()}, 100); //问题创建时间 + 显示问题作者
  1436. questionInvitation(); // 默认折叠邀请
  1437.  
  1438. } else if (location.pathname === '/search') { // 搜索结果页 //
  1439. collapsedNowAnswer('main div'); // 收起当前回答 + 快捷返回顶部
  1440. collapsedNowAnswer('.Search-container'); // 收起当前回答 + 快捷返回顶部
  1441. setInterval(function(){topTime_('.ContentItem.AnswerItem, .ContentItem.ArticleItem', 'SearchItem-meta')}, 300); // 置顶显示时间
  1442. addTypeTips(); // 区分问题文章
  1443. addToQuestion(); // 直达问题按钮
  1444. blockUsers('search'); // 屏蔽指定用户
  1445. blockKeywords('search'); // 屏蔽指定关键词
  1446. blockType('search'); // 屏蔽指定类别(视频/文章等)
  1447.  
  1448.  
  1449. } else if (location.pathname.indexOf('/topic/') > -1) { // 话题页 //
  1450. if (location.pathname.indexOf('/hot') > -1 || location.href.indexOf('/top-answers') > -1) { // 仅限 [讨论] [精华]
  1451. collapsedNowAnswer('main.App-main'); // 收起当前回答 + 快捷返回顶部
  1452. collapsedNowAnswer('.ContentLayout'); // 收起当前回答 + 快捷返回顶部
  1453. setInterval(function(){topTime_('.ContentItem.AnswerItem, .ContentItem.ArticleItem', 'ContentItem-meta')}, 300); // 置顶显示时间
  1454. addTypeTips(); // 区分问题文章
  1455. addToQuestion(); // 直达问题按钮
  1456. blockUsers('topic'); // 屏蔽指定用户
  1457. blockKeywords('topic'); // 屏蔽指定关键词
  1458. }
  1459.  
  1460. } else if (location.hostname === 'zhuanlan.zhihu.com'){ // 文章 //
  1461. backToTop('article.Post-Main.Post-NormalMain'); // 快捷返回顶部
  1462. backToTop('div.Post-Sub.Post-NormalSub'); // 快捷返回顶部
  1463. setTimeout(topTime_post, 300); // 置顶显示时间
  1464. blockUsers(); // 屏蔽指定用户
  1465.  
  1466.  
  1467. } else if (location.pathname.indexOf('/column/') > -1) { // 专栏 //
  1468. setTimeout(function(){
  1469. collapsedAnswer(); // 一键收起回答
  1470. collapsedNowAnswer('main div'); // 收起当前回答 + 快捷返回顶部
  1471. setInterval(function(){topTime_('.ContentItem.AnswerItem, .ContentItem.ArticleItem', 'ContentItem-meta')}, 300); // 置顶显示时间
  1472. blockUsers(); // 屏蔽指定用户
  1473. }, 300);
  1474.  
  1475.  
  1476. } else if (location.pathname.indexOf('/people/') > -1 || location.href.indexOf('org') > -1) { // 用户主页 //
  1477. if (location.pathname.split('/').length === 3) addTypeTips();addToQuestion(); // 区分问题文章、直达问题按钮
  1478. collapsedNowAnswer('main div'); // 收起当前回答 + 快捷返回顶部
  1479. collapsedNowAnswer('.Profile-main'); // 收起当前回答 + 快捷返回顶部
  1480. setInterval(function(){topTime_('.ContentItem.AnswerItem, .ContentItem.ArticleItem', 'ContentItem-meta')}, 300); // 置顶显示时间
  1481. blockUsers('people'); // 屏蔽指定用户
  1482. blockKeywords('people'); // 屏蔽指定关键词
  1483.  
  1484.  
  1485. } else if (location.pathname.indexOf('/collection/') > -1) { // 收藏夹 //
  1486. addTypeTips(); // 区分问题文章
  1487. addToQuestion(); // 直达问题按钮
  1488. collapsedNowAnswer('main'); // 收起当前回答 + 快捷返回顶部
  1489. collapsedNowAnswer('.CollectionsDetailPage'); // 收起当前回答 + 快捷返回顶部
  1490. setInterval(function(){topTime_('.ContentItem.AnswerItem, .ContentItem.ArticleItem', 'ContentItem-meta')}, 300); // 置顶显示时间
  1491. blockKeywords('collection'); // 屏蔽指定关键词
  1492.  
  1493.  
  1494. } else { // 首页 //
  1495. // 解决屏蔽类别后,因为首页信息流太少而没有滚动条导致无法加载更多内容的问题
  1496. document.lastElementChild.appendChild(document.createElement('style')).textContent = '.Topstory-container {min-height: 1500px;}';
  1497. if (menu_value('menu_blockTypeVideo')) document.lastChild.appendChild(document.createElement('style')).textContent = `.Card .ZVideoItem-video, nav.TopstoryTabs > a[aria-controls="Topstory-zvideo"] {display: none !important;}`;
  1498.  
  1499. collapsedNowAnswer('main div'); // 收起当前回答 + 快捷返回顶部
  1500. collapsedNowAnswer('.Topstory-container'); // 收起当前回答 + 快捷返回顶部
  1501. setInterval(function(){topTime_('.TopstoryItem', 'ContentItem-meta')}, 300); // 置顶显示时间
  1502. addTypeTips(); // 区分问题文章
  1503. addToQuestion(); // 直达问题按钮
  1504. if (location.pathname == '/') {
  1505. blockUsers('index'); // 屏蔽指定用户
  1506. blockKeywords('index'); // 屏蔽指定关键词
  1507. blockType(); // 屏蔽指定类别(视频/文章等)
  1508. } else if (location.pathname == '/hot') {
  1509. blockKeywords('index'); // 屏蔽指定关键词
  1510. } else {
  1511. blockUsers();
  1512. }
  1513. }
  1514. }
  1515. })();