setWaterMask() {
const userInfo = JSON.parse(sessionStorage.getItem('bsl_username'))
if (userInfo === null || userInfo['userName'] === undefined) {
if (this.timer === null) {
this.timer = setInterval(() => {
console.log('拿到用户信息设置水印')
this.setWaterMask()
}, 1000)
}
return
} else {
if (this.timer) {
clearInterval(this.timer)
this.timer = null
}
}
let width = '150px',
height = '100px',
textAlign = 'center',
textBaseline = 'middle',
font = '14px microsoft yahei',
fillStyle = 'rgba(0,0,0,0.2)',
content = userInfo['userName']
const canvas = document.createElement('canvas')
canvas.setAttribute('width', width)
canvas.setAttribute('height', height)
let ctx = canvas.getContext('2d')
ctx.textAlign = textAlign
ctx.textBaseline = textBaseline
ctx.font = font
ctx.fillStyle = fillStyle
ctx.translate(parseFloat(width) / 2, parseFloat(height) / 2)
ctx.rotate((-15 * Math.PI) / 180)
ctx.fillText(content, 0, 0)
let base64Url = canvas.toDataURL()
const divStyleStr = ` position: fixed;
left: 0;
top: 100px;
width:100%;
height:100%;
z-index: 1;
pointer-events: none;
user-select: none;
background-repeat: repeat;
overflow: hidden;
background-image: url("${base64Url}");`
const waterDom = document.querySelector('#waterMark')
waterDom.setAttribute('style', divStyleStr)
if (waterDom) {
const whiteNames = ['张三', '李四']
this.observer = new MutationObserver(function (mutationsList) {
for (let mutation of mutationsList) {
if (mutation.type === 'childList' && mutation.removedNodes.length > 0) {
const removeNode = mutation.removedNodes[0]
if (removeNode === waterDom) {
if (whiteNames.indexOf(userInfo.userName) === -1) {
window.location.reload()
}
break
}
}
}
})
this.observer.observe(this.$el, { childList: true })
}
beforeDestroy() {
this.observer && this.observer.disconnect()
},
MutationObserver API说明
MDN文档地址
const targetNode = document.getElementById("some-id");
const config = { attributes: true, childList: true, subtree: true };
const callback = function (mutationsList, observer) {
for (let mutation of mutationsList) {
if (mutation.type === "childList") {
console.log("A child node has been added or removed.");
} else if (mutation.type === "attributes") {
console.log("The " + mutation.attributeName + " attribute was modified.");
}
}
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
observer.disconnect();