如何解决Facebook拦截移除关键词的用户脚本问题?
解决Facebook CSP阻止用户脚本运行的问题
问题根源
Facebook的Content-Security-Policy(CSP)严格禁止内联脚本执行,而你的脚本设置了@grant none,Violentmonkey会将这类脚本以内联代码的方式注入页面,正好触发了CSP的限制——这也是其他用户脚本能正常运行的原因:它们大概率使用了@grant权限启用了沙箱执行模式,避开了内联脚本的拦截。
解决方案
1. 启用用户脚本沙箱(核心修复)
修改脚本的@grant字段,添加任意一个GM_*权限,让Violentmonkey在独立沙箱中运行脚本,而非注入成内联代码:
// ==UserScript== // @name Hide Elodie News // @namespace // @version 0.1.1 // @description Hide Elodie news // @author brunon // @match https://*.facebook.com/* // @grant GM_addElement // 启用沙箱的关键权限 // @run-at document-idle // 延迟到DOM就绪后执行,避免提前操作未加载的元素 // ==/UserScript==
2. 优化元素隐藏逻辑(更合规的写法)
配合沙箱模式,将直接设置元素样式改为添加全局样式规则,进一步降低触发CSP的风险:
(function() { 'use strict'; const keywords = ["elodie"]; const regexPattern = new RegExp(keywords.join('|'), 'i'); function hideMatchingItems() { const items = document.querySelectorAll('.x1lliihq'); items.forEach(item => { const hasKeyword = (el) => { if (el.nodeType === Node.TEXT_NODE) return regexPattern.test(el.textContent); for (const child of el.childNodes) { if (hasKeyword(child)) return true; } return false; }; if (hasKeyword(item)) { // 用类名标记需要隐藏的元素,而非直接修改内联样式 item.classList.add('hidden-elodie-item'); } }); } // 添加全局隐藏样式规则 GM_addElement('style', { textContent: '.hidden-elodie-item { display: none !important; }' }); document.addEventListener('DOMContentLoaded', hideMatchingItems); const observer = new MutationObserver(hideMatchingItems); observer.observe(document.body, { subtree: true, childList: true }); })();
补充说明
- 避免在Facebook脚本中使用
@grant none:Facebook的CSP几乎完全禁用内联脚本和eval类操作,这是报错的核心原因。 - 沙箱模式下,脚本的DOM操作逻辑依然有效,只是执行环境从页面内联变为独立沙箱,不会触发CSP拦截。
内容的提问来源于stack exchange,提问作者thanksalotquoraguy
相关产品推荐
相关产品推荐

