前端"伪防盗链"方案
- 禁止文本选中与复制:
user-select: none;. - 禁用右键与拖拽:通过监听 contextmenu 和 dragstart 事件,禁止用户右键保存图片或拖拽图片。.
方案一:原生 JavaScript(适用于所有项目)
js
// 方案一:原生 JavaScript(适用于所有项目)
function protectImages() {
// 1. 禁用右键菜单
document.addEventListener('contextmenu', function(e) {
// 判断点击的目标是否是图片
if (e.target.tagName === 'IMG') {
e.preventDefault(); // 阻止默认的右键菜单弹出
console.log('右键保存图片已被拦截');
}
}, true); // 使用捕获阶段,确保在默认行为前拦截
// 2. 禁用拖拽
document.addEventListener('dragstart', function(e) {
if (e.target.tagName === 'IMG') {
e.preventDefault(); // 阻止图片被拖拽出浏览器
console.log('图片拖拽已被拦截');
}
}, true);
}
// 在 DOM 加载完成后执行
document.addEventListener('DOMContentLoaded', protectImages);
方案二:Vue 3 自定义指令(推荐,最优雅)
如果你使用的是 Vue,强烈建议封装成一个自定义指令(Directive)。这样你只需要在需要保护的 标签上加一个 v-protect 即可,非常干净。
- 创建指令文件(如 directives/protect.js):
ts
export const protectDirective = {
mounted(el) {
// 确保只对 img 标签生效
if (el.tagName !== 'IMG') return;
// 禁用右键
el.addEventListener('contextmenu', (e) => {
e.preventDefault();
});
// 禁用拖拽
el.addEventListener('dragstart', (e) => {
e.preventDefault();
});
}
};
- 在 main.js 中全局注册:
ts
import { createApp } from 'vue';
import { protectDirective } from './directives/protect';
const app = createApp(App);
app.directive('protect', protectDirective);
app.mount('#app');
- 在页面中使用:
html
<!-- 只需要加上 v-protect,这张图片就被保护了 -->
<img src="/path/to/image.jpg" alt="受保护的图片" v-protect />
方案三:纯 CSS 辅助方案(防拖拽与选中)
css
/* 禁止图片被选中 */
img {
user-select: none;
-webkit-user-select: none; /* Safari 兼容 */
/* 禁止长按弹出保存菜单(主要针对移动端) */
-webkit-touch-callout: none;
/* 禁止拖拽 */
pointer-events: none; /* ⚠️注意:这会导致图片上的点击事件也失效! */
}
- 禁止选中:在 CSS 中对图片添加 user-select: none; 属性。
- 添加透明水印:在图片上方覆盖一层半透明的水印图层,即使别人截图也会带上你的水印。
- 动态修改图片地址:不直接暴露真实的图片 URL,而是通过 JS 动态拼接加密参数,增加直接抓取链接的难度。