How to prevent users from opening the console to modify css (to prevent removing the watermark)

The need for watermarking is all in order to be inremovable. Therefore, we must prevent users from opening the console, performing css operations, and then taking screenshots.
The api used is window.MutationObserver.
Not much to say, the code above:

The idea is: when you monitor the style of a certain element changes, you can draw the style again.


const canvasWM = ({
    
    
  container = document.body,
  width = '160px',
  height = '130px',
  textAlign = 'center',
  font = '15px Microsoft Yahei',
  fillStyle = 'rgba(184, 184, 184, 0.6)',
  content = '请勿外传',
  rotate = '30',
  zIndex = 1000,
} = {
    
    }) => {
    
    
  // eslint-disable-next-line no-undef
  const [args] = arguments;
  const canvas = document.createElement('canvas');

  canvas.setAttribute('width', width);
  canvas.setAttribute('height', height);
  const ctx = canvas.getContext('2d');

  ctx.textAlign = textAlign;

  ctx.font = font;
  ctx.fillStyle = fillStyle;
  ctx.rotate(Math.PI / 180 * rotate);
  ctx.fillText(content, parseFloat(width) / 2, parseFloat(height) / 2);

  const base64Url = canvas.toDataURL();
  const wmInstance = document.querySelector('.__wm');

  const watermarkDiv = wmInstance || document.createElement('div');
  const styleStr = `
		position:absolute;
		top:0;
		left:0;
		width:100%;
		height:100%;
		z-index:${
      
      zIndex};
		pointer-events:none;
		background-repeat:repeat;
		background-image:url('${
      
      base64Url}')`;

  watermarkDiv.setAttribute('style', styleStr);
  watermarkDiv.classList.add('__wm');

  if (!wmInstance) {
    
    
    // eslint-disable-next-line no-param-reassign
    container.style.position = 'relative';
    container.insertBefore(watermarkDiv, container.firstChild);
  }

  const MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
  if (MutationObserver) {
    
    
    let mo = new MutationObserver(() => {
    
    
      const wmInstance = document.querySelector('.__wm');
      // 只在wmInstance元素变动才重新调用 canvasWM
      if ((wmInstance && wmInstance.getAttribute('style') !== styleStr) || !wmInstance) {
    
    
        // 避免一直触发
        mo.disconnect();
        mo = null;
        canvasWM(JSON.parse(JSON.stringify(args)));
      }
    });

    mo.observe(container, {
    
    
      attributes: true,
      subtree: true,
      childList: true,
    });
  }
};

export default canvasWM;

Guess you like

Origin blog.csdn.net/Beth__hui/article/details/106721567