背景

为了保护版权,常常需要为页面添加水印,常见的有以下几种方法:

css伪元素
canvas
背景图
svg

防篡改

添加水印比较简单,难点在于如何最大程度的防止篡改和删除页面的水印。

原理:监听水印元素的变化,出现变化把水印元素清除,再重新生成一个,清除变动记录,继续监听

我是水印
1
2
3
4
5
6
7
8
9
10
11
#wm {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
pointer-events: none;
text-align: center;
margin-top: 200px;
font-size: 30px;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const mutationObserver = new MutationObserver((mutationsList, observer) => {
// mutationsList mutationRecord数组 记录了DOM的变化
// observer MutationObserver的实例

// 监听回调
console.log('mutationsList', mutationsList);
console.log('observer', observer)
if (mutationsList.length > 0) {
if (document.getElementById('wm')) document.body.removeChild(document.getElementById('wm'))
const dom = document.createElement('div')
dom.setAttribute('id', 'wm')
dom.innerHTML = '我是水印'
document.body.appendChild(dom)
// 清除变动记录
mutationObserver.takeRecords()
// 停止监听
mutationObserver.disconnect()
// 重新获取dom,重新监听
observe()
}
})

// node 监听的节点
// config 监听配置(要监听哪些内容)
function observe() {
mutationObserver.observe(document.getElementById('wm'), {
attributes: true, // 属性变化
attributeOldValue: true, // 观察attributes变动时,是否需要记录变动前的属性值
attributeFilter: ['class', 'src'], // 需要观察的特定属性
characterData: true, // 节点内容、文本的变化
characterDataOldValue: true, // 观察characterData变动时,是否需要记录变动前的属性值
childList: true, // 子结点变化
subtree: true, // 所有后代节点
});
}

observe()