禁止键盘 F12
document.addEventListener('keydown', event => {
return 123 !== event.keyCode || event.returnValue = false;
});
禁止鼠标右键后选择检查元素
document.addEventListener('contextmenu', event => {
return event.returnValue = false;
});
基于MutationObserver检测用户改变元素属性
- MutationObserver 可以监测到 DOM 元素上任何属性的变化情况,如有需要,也可以监听其子元素的变化情况
- MutationObserver监听的是元素的属性,即attributes,如:style、class、type、href等
- 禁止用户用开发者工具修改某些属性时使用,如:用户企图修改网站水印
const options = {
childList: true,
attributes: true,
subtree: true,
attributesOldValue: true,
characterData: true,
characterDataOldValue: true,
}
const reset = (expression = () => {}) => {
setTimeout(() => {
observer.disconnect();
expression();
observer.observe(h1, options);
}, 0);
}
const callback = (records) => {
const record = records[0];
if (record.type === 'attributes' && record.attributeName === 'style') {
reset(() => {
h1.setAttribute('style', 'margin:100px;');
});
} else if (record.type === 'characterData') {
reset(() => {
h1.textContent = '需要检测的元素'
});
}
}
const observer = new MutationObserver(callback);
observer.observe(h1, options);